blob: 82eb425d4d4d77d814e3faeee7e0a71ebea1289a [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020028#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070029#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "logging/rtc_event_log/ice_logger.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070062#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080073using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080074using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080075using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080078using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070079using cricket::RELAY_PORT_TYPE;
80using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080081
Steve Antonba818672017-11-06 10:21:57 -080082namespace webrtc {
83
Steve Anton75737c02017-11-06 10:37:17 -080084// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080088const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080096const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
Steve Anton75737c02017-11-06 10:37:17 -0800108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800110// UMA metric names.
111const char kSimulcastVersionApplyLocalDescription[] =
112 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
113const char kSimulcastVersionApplyRemoteDescription[] =
114 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
115const char kSimulcastNumberOfEncodings[] =
116 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
117const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
118
Seth Hampson845e8782018-03-02 11:34:10 -0800119static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800120static const char kDefaultAudioSenderId[] = "defaulta0";
121static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700122
zhihuang8f65cdf2016-05-06 18:40:30 -0700123// The length of RTCP CNAMEs.
124static const int kRtcpCnameLength = 16;
125
Steve Antonad182762018-09-05 20:22:40 +0000126enum {
127 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
128 MSG_SET_SESSIONDESCRIPTION_FAILED,
129 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
130 MSG_GETSTATS,
131 MSG_FREE_DATACHANNELS,
132 MSG_REPORT_USAGE_PATTERN,
133};
134
Harald Alvestrand19793842018-06-25 12:03:50 +0200135static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
136
Steve Antonad182762018-09-05 20:22:40 +0000137struct SetSessionDescriptionMsg : public rtc::MessageData {
138 explicit SetSessionDescriptionMsg(
139 webrtc::SetSessionDescriptionObserver* observer)
140 : observer(observer) {}
141
142 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
143 RTCError error;
144};
145
146struct CreateSessionDescriptionMsg : public rtc::MessageData {
147 explicit CreateSessionDescriptionMsg(
148 webrtc::CreateSessionDescriptionObserver* observer)
149 : observer(observer) {}
150
151 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
152 RTCError error;
153};
154
155struct GetStatsMsg : public rtc::MessageData {
156 GetStatsMsg(webrtc::StatsObserver* observer,
157 webrtc::MediaStreamTrackInterface* track)
158 : observer(observer), track(track) {}
159 rtc::scoped_refptr<webrtc::StatsObserver> observer;
160 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
161};
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163// Check if we can send |new_stream| on a PeerConnection.
164bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
165 webrtc::MediaStreamInterface* new_stream) {
166 if (!new_stream || !current_streams) {
167 return false;
168 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700169 if (current_streams->find(new_stream->id()) != nullptr) {
170 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100171 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700172 return false;
173 }
174 return true;
175}
176
deadbeef5e97fb52015-10-15 12:49:08 -0700177// If the direction is "recvonly" or "inactive", treat the description
178// as containing no streams.
179// See: https://code.google.com/p/webrtc/issues/detail?id=5054
180std::vector<cricket::StreamParams> GetActiveStreams(
181 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800182 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700183 ? desc->streams()
184 : std::vector<cricket::StreamParams>();
185}
186
deadbeefab9b2d12015-10-14 11:33:11 -0700187bool IsValidOfferToReceiveMedia(int value) {
188 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
189 return (value >= Options::kUndefined) &&
190 (value <= Options::kMaxOfferToReceiveMedia);
191}
192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800194void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700195 const std::vector<rtc::scoped_refptr<
196 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700197 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200198 cricket::MediaDescriptionOptions* video_media_description_options,
199 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700200 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700201 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
202 if (audio_media_description_options) {
203 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700204 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700205 }
206 } else {
207 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
208 if (video_media_description_options) {
209 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800210 sender->id(), sender->internal()->stream_ids(), {},
211 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700212 }
213 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700214 }
zhihuang1c378ed2017-08-17 14:10:50 -0700215}
olka3c747662017-08-17 06:50:32 -0700216
zhihuang1c378ed2017-08-17 14:10:50 -0700217// Add options to |session_options| from |rtp_data_channels|.
218void AddRtpDataChannelOptions(
219 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
220 rtp_data_channels,
221 cricket::MediaDescriptionOptions* data_media_description_options) {
222 if (!data_media_description_options) {
223 return;
224 }
deadbeefab9b2d12015-10-14 11:33:11 -0700225 // Check for data channels.
226 for (const auto& kv : rtp_data_channels) {
227 const DataChannel* channel = kv.second;
228 if (channel->state() == DataChannel::kConnecting ||
229 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700230 // Legacy RTP data channels are signaled with the track/stream ID set to
231 // the data channel's label.
232 data_media_description_options->AddRtpDataChannel(channel->label(),
233 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700234 }
235 }
236}
237
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238uint32_t ConvertIceTransportTypeToCandidateFilter(
239 PeerConnectionInterface::IceTransportsType type) {
240 switch (type) {
241 case PeerConnectionInterface::kNone:
242 return cricket::CF_NONE;
243 case PeerConnectionInterface::kRelay:
244 return cricket::CF_RELAY;
245 case PeerConnectionInterface::kNoHost:
246 return (cricket::CF_ALL & ~cricket::CF_HOST);
247 case PeerConnectionInterface::kAll:
248 return cricket::CF_ALL;
249 default:
nissec80e7412017-01-11 05:56:46 -0800250 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700251 }
252 return cricket::CF_NONE;
253}
254
deadbeef293e9262017-01-11 12:28:30 -0800255// Helper to set an error and return from a method.
256bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
257 if (error) {
258 error->set_type(type);
259 }
260 return type == webrtc::RTCErrorType::NONE;
261}
262
Steve Anton038834f2017-07-14 15:59:59 -0700263bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700264 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700265 if (error_out) {
266 *error_out = std::move(error);
267 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700269}
270
Steve Antonba818672017-11-06 10:21:57 -0800271std::string GetSignalingStateString(
272 PeerConnectionInterface::SignalingState state) {
273 switch (state) {
274 case PeerConnectionInterface::kStable:
275 return "kStable";
276 case PeerConnectionInterface::kHaveLocalOffer:
277 return "kHaveLocalOffer";
278 case PeerConnectionInterface::kHaveLocalPrAnswer:
279 return "kHavePrAnswer";
280 case PeerConnectionInterface::kHaveRemoteOffer:
281 return "kHaveRemoteOffer";
282 case PeerConnectionInterface::kHaveRemotePrAnswer:
283 return "kHaveRemotePrAnswer";
284 case PeerConnectionInterface::kClosed:
285 return "kClosed";
286 }
287 RTC_NOTREACHED();
288 return "";
289}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290
Steve Anton75737c02017-11-06 10:37:17 -0800291IceCandidatePairType GetIceCandidatePairCounter(
292 const cricket::Candidate& local,
293 const cricket::Candidate& remote) {
294 const auto& l = local.type();
295 const auto& r = remote.type();
296 const auto& host = LOCAL_PORT_TYPE;
297 const auto& srflx = STUN_PORT_TYPE;
298 const auto& relay = RELAY_PORT_TYPE;
299 const auto& prflx = PRFLX_PORT_TYPE;
300 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800301 bool local_hostname =
302 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
303 bool remote_hostname = !remote.address().hostname().empty() &&
304 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800305 bool local_private = IPIsPrivate(local.address().ipaddr());
306 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800307 if (local_hostname) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostNameHostName;
310 } else if (remote_private) {
311 return kIceCandidatePairHostNameHostPrivate;
312 } else {
313 return kIceCandidatePairHostNameHostPublic;
314 }
315 } else if (local_private) {
316 if (remote_hostname) {
317 return kIceCandidatePairHostPrivateHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPrivateHostPrivate;
320 } else {
321 return kIceCandidatePairHostPrivateHostPublic;
322 }
323 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800324 if (remote_hostname) {
325 return kIceCandidatePairHostPublicHostName;
326 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800327 return kIceCandidatePairHostPublicHostPrivate;
328 } else {
329 return kIceCandidatePairHostPublicHostPublic;
330 }
331 }
332 }
333 if (l == host && r == srflx)
334 return kIceCandidatePairHostSrflx;
335 if (l == host && r == relay)
336 return kIceCandidatePairHostRelay;
337 if (l == host && r == prflx)
338 return kIceCandidatePairHostPrflx;
339 if (l == srflx && r == host)
340 return kIceCandidatePairSrflxHost;
341 if (l == srflx && r == srflx)
342 return kIceCandidatePairSrflxSrflx;
343 if (l == srflx && r == relay)
344 return kIceCandidatePairSrflxRelay;
345 if (l == srflx && r == prflx)
346 return kIceCandidatePairSrflxPrflx;
347 if (l == relay && r == host)
348 return kIceCandidatePairRelayHost;
349 if (l == relay && r == srflx)
350 return kIceCandidatePairRelaySrflx;
351 if (l == relay && r == relay)
352 return kIceCandidatePairRelayRelay;
353 if (l == relay && r == prflx)
354 return kIceCandidatePairRelayPrflx;
355 if (l == prflx && r == host)
356 return kIceCandidatePairPrflxHost;
357 if (l == prflx && r == srflx)
358 return kIceCandidatePairPrflxSrflx;
359 if (l == prflx && r == relay)
360 return kIceCandidatePairPrflxRelay;
361 return kIceCandidatePairMax;
362}
363
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800364// Logic to decide if an m= section can be recycled. This means that the new
365// m= section is not rejected, but the old local or remote m= section is
366// rejected. |old_content_one| and |old_content_two| refer to the m= section
367// of the old remote and old local descriptions in no particular order.
368// We need to check both the old local and remote because either
369// could be the most current from the latest negotation.
370bool IsMediaSectionBeingRecycled(SdpType type,
371 const ContentInfo& content,
372 const ContentInfo* old_content_one,
373 const ContentInfo* old_content_two) {
374 return type == SdpType::kOffer && !content.rejected &&
375 ((old_content_one && old_content_one->rejected) ||
376 (old_content_two && old_content_two->rejected));
377}
378
Steve Anton75737c02017-11-06 10:37:17 -0800379// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380// |current_desc|. The number of m= sections in |new_desc| should be no
381// less than |current_desc|. In the case of checking an answer's
382// |new_desc|, the |current_desc| is the last offer that was set as the
383// local or remote. In the case of checking an offer's |new_desc| we
384// check against the local and remote descriptions stored from the last
385// negotiation, because either of these could be the most up to date for
386// possible rejected m sections. These are the |current_desc| and
387// |secondary_current_desc|.
388bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
389 const SessionDescription* secondary_current_desc,
390 const SessionDescription& new_desc,
391 const SdpType type) {
392 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800393 return false;
394 }
395
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
397 const cricket::ContentInfo* secondary_content_info = nullptr;
398 if (secondary_current_desc &&
399 i < secondary_current_desc->contents().size()) {
400 secondary_content_info = &secondary_current_desc->contents()[i];
401 }
402 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
403 &current_desc.contents()[i],
404 secondary_content_info)) {
405 // For new offer descriptions, if the media section can be recycled, it's
406 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800407 continue;
408 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800409 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800410 return false;
411 }
412 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 new_desc.contents()[i].media_description();
414 const MediaContentDescription* current_desc_mdesc =
415 current_desc.contents()[i].media_description();
416 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800417 return false;
418 }
419 }
420 return true;
421}
422
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800423bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
424 const SessionDescription& desc2) {
425 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800426}
427
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700428void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
429 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200430 // Array of structs needed to map {KeyExchangeProtocolType,
431 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
432 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
433 static constexpr struct {
434 KeyExchangeProtocolType protocol_type;
435 cricket::MediaType media_type;
436 KeyExchangeProtocolMedia protocol_media;
437 } kEnumCounterKeyProtocolMediaMap[] = {
438 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
439 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
440 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
441 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
443 kEnumCounterKeyProtocolMediaTypeDtlsData},
444 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
445 kEnumCounterKeyProtocolMediaTypeSdesAudio},
446 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
447 kEnumCounterKeyProtocolMediaTypeSdesVideo},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
449 kEnumCounterKeyProtocolMediaTypeSdesData},
450 };
451
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
453 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100454
Mirko Bonadeiab499822018-09-11 10:43:20 +0200455 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
456 if (i.protocol_type == protocol_type && i.media_type == media_type) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
458 i.protocol_media,
459 kEnumCounterKeyProtocolMediaTypeMax);
460 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100461 }
462}
463
Harald Alvestrand76829d72018-07-18 23:24:36 +0200464void NoteAddIceCandidateResult(int result) {
465 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
466 kAddIceCandidateMax);
467}
468
Steve Anton75737c02017-11-06 10:37:17 -0800469// Checks that each non-rejected content has SDES crypto keys or a DTLS
470// fingerprint, unless it's in a BUNDLE group, in which case only the
471// BUNDLE-tag section (first media section/description in the BUNDLE group)
472// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
473// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
474// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700475RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100482 // Note what media is used with each crypto protocol, for all sections.
483 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
484 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700485 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800486 const std::string& mid = content_info.name;
487 if (bundle && bundle->HasContentName(mid) &&
488 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800489 // This isn't the first media section in the BUNDLE group, so it's not
490 // required to have crypto attributes, since only the crypto attributes
491 // from the first section actually get used.
492 continue;
493 }
494
495 // If the content isn't rejected or bundled into another m= section, crypto
496 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800498 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800499 if (!media || !tinfo) {
500 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 if (dtls_enabled) {
504 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
506 << "Session description must have DTLS fingerprint if "
507 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800508 return RTCError(RTCErrorType::INVALID_PARAMETER,
509 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800510 }
511 } else {
512 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100513 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800514 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800515 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800516 }
517 }
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800520}
521
522// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
523// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
524// media section/description in the BUNDLE group) needs a ufrag and pwd.
525bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
526 const cricket::ContentGroup* bundle =
527 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800528 for (const cricket::ContentInfo& content_info : desc->contents()) {
529 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800530 continue;
531 }
Steve Anton8a006912017-12-04 15:25:56 -0800532 const std::string& mid = content_info.name;
533 if (bundle && bundle->HasContentName(mid) &&
534 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800535 // This isn't the first media section in the BUNDLE group, so it's not
536 // required to have ufrag/password, since only the ufrag/password from
537 // the first section actually get used.
538 continue;
539 }
540
541 // If the content isn't rejected or bundled into another m= section,
542 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800543 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800544 if (!tinfo) {
545 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800547 return false;
548 }
549 if (tinfo->description.ice_ufrag.empty() ||
550 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100551 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800552 return false;
553 }
554 }
555 return true;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
559bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
560 const SessionDescriptionInterface* new_desc,
561 const std::string& content_name) {
562 if (!old_desc) {
563 return false;
564 }
565 const SessionDescription* new_sd = new_desc->description();
566 const SessionDescription* old_sd = old_desc->description();
567 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
568 if (!cinfo || cinfo->rejected) {
569 return false;
570 }
571 // If the content isn't rejected, check if ufrag and password has changed.
572 const cricket::TransportDescription* new_transport_desc =
573 new_sd->GetTransportDescriptionByName(content_name);
574 const cricket::TransportDescription* old_transport_desc =
575 old_sd->GetTransportDescriptionByName(content_name);
576 if (!new_transport_desc || !old_transport_desc) {
577 // No transport description exists. This is not an ICE restart.
578 return false;
579 }
580 if (cricket::IceCredentialsChanged(
581 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
582 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-16 17:08:42 -0800590// Generates a string error message for SetLocalDescription/SetRemoteDescription
591// from an RTCError.
592std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
593 SdpType type,
594 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200595 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800596 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
597 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200598 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800599}
600
Seth Hampson5b4f0752018-04-02 16:31:36 -0700601std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
602 std::string output = "streams=[";
603 const char* separator = "";
604 for (const auto& stream_id : stream_ids) {
605 output.append(separator).append(stream_id);
606 separator = ", ";
607 }
608 output.append("]");
609 return output;
610}
611
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 }
618 return rtc_configuration_parameter;
619}
620
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800621cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
622 switch (type) {
623 case DataMessageType::kText:
624 return cricket::DMT_TEXT;
625 case DataMessageType::kBinary:
626 return cricket::DMT_BINARY;
627 case DataMessageType::kControl:
628 return cricket::DMT_CONTROL;
629 default:
630 return cricket::DMT_NONE;
631 }
632 return cricket::DMT_NONE;
633}
634
635DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
636 switch (type) {
637 case cricket::DMT_TEXT:
638 return DataMessageType::kText;
639 case cricket::DMT_BINARY:
640 return DataMessageType::kBinary;
641 case cricket::DMT_CONTROL:
642 return DataMessageType::kControl;
643 case cricket::DMT_NONE:
644 default:
645 RTC_NOTREACHED();
646 }
647 return DataMessageType::kControl;
648}
649
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800650void ReportSimulcastApiVersion(const char* name,
651 const SessionDescription& session) {
652 bool has_legacy = false;
653 bool has_spec_compliant = false;
654 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200655 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800656 continue;
657 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200658 has_spec_compliant |= content.media_description()->HasSimulcast();
659 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800660 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
661 }
662 }
663
664 if (has_legacy) {
665 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
666 kSimulcastApiVersionMax);
667 }
668 if (has_spec_compliant) {
669 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
670 kSimulcastApiVersionMax);
671 }
672 if (!has_legacy && !has_spec_compliant) {
673 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
674 kSimulcastApiVersionMax);
675 }
676}
677
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200678const ContentInfo* FindTransceiverMSection(
679 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
680 const SessionDescriptionInterface* session_description) {
681 return transceiver->mid()
682 ? session_description->description()->GetContentByName(
683 *transceiver->mid())
684 : nullptr;
685}
686
Steve Anton75737c02017-11-06 10:37:17 -0800687} // namespace
688
Henrik Boström31638672017-11-23 17:48:32 +0100689// Upon completion, posts a task to execute the callback of the
690// SetSessionDescriptionObserver asynchronously on the same thread. At this
691// point, the state of the peer connection might no longer reflect the effects
692// of the SetRemoteDescription operation, as the peer connection could have been
693// modified during the post.
694// TODO(hbos): Remove this class once we remove the version of
695// PeerConnectionInterface::SetRemoteDescription() that takes a
696// SetSessionDescriptionObserver as an argument.
697class PeerConnection::SetRemoteDescriptionObserverAdapter
698 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
699 public:
700 SetRemoteDescriptionObserverAdapter(
701 rtc::scoped_refptr<PeerConnection> pc,
702 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
703 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
704
705 // SetRemoteDescriptionObserverInterface implementation.
706 void OnSetRemoteDescriptionComplete(RTCError error) override {
707 if (error.ok())
708 pc_->PostSetSessionDescriptionSuccess(wrapper_);
709 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100710 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100711 }
712
713 private:
714 rtc::scoped_refptr<PeerConnection> pc_;
715 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
716};
717
deadbeef293e9262017-01-11 12:28:30 -0800718bool PeerConnectionInterface::RTCConfiguration::operator==(
719 const PeerConnectionInterface::RTCConfiguration& o) const {
720 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700721 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800722 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000723 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700724 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800725 BundlePolicy bundle_policy;
726 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700727 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
728 int ice_candidate_pool_size;
729 bool disable_ipv6;
730 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700731 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100732 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200734 absl::optional<int> screencast_min_bitrate;
735 absl::optional<bool> combined_audio_video_bwe;
736 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800737 TcpCandidatePolicy tcp_candidate_policy;
738 CandidateNetworkPolicy candidate_network_policy;
739 int audio_jitter_buffer_max_packets;
740 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100741 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100742 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800743 int ice_connection_receiving_timeout;
744 int ice_backup_candidate_pair_ping_interval;
745 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800746 bool prioritize_most_likely_ice_candidate_pairs;
747 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800748 bool prune_turn_ports;
749 bool presume_writable_when_fully_relayed;
750 bool enable_ice_renomination;
751 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700752 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200753 absl::optional<int> ice_check_interval_strong_connectivity;
754 absl::optional<int> ice_check_interval_weak_connectivity;
755 absl::optional<int> ice_check_min_interval;
756 absl::optional<int> ice_unwritable_timeout;
757 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800758 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200759 absl::optional<int> stun_candidate_keepalive_interval;
760 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200761 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800762 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700764 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700765 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700766 bool use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700767 bool use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700768 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100769 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800770 };
771 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
772 "Did you add something to RTCConfiguration and forget to "
773 "update operator==?");
774 return type == o.type && servers == o.servers &&
775 bundle_policy == o.bundle_policy &&
776 rtcp_mux_policy == o.rtcp_mux_policy &&
777 tcp_candidate_policy == o.tcp_candidate_policy &&
778 candidate_network_policy == o.candidate_network_policy &&
779 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
780 audio_jitter_buffer_fast_accelerate ==
781 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100782 audio_jitter_buffer_min_delay_ms ==
783 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100784 audio_jitter_buffer_enable_rtx_handling ==
785 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800786 ice_connection_receiving_timeout ==
787 o.ice_connection_receiving_timeout &&
788 ice_backup_candidate_pair_ping_interval ==
789 o.ice_backup_candidate_pair_ping_interval &&
790 continual_gathering_policy == o.continual_gathering_policy &&
791 certificates == o.certificates &&
792 prioritize_most_likely_ice_candidate_pairs ==
793 o.prioritize_most_likely_ice_candidate_pairs &&
794 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800795 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700796 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100797 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800798 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800799 screencast_min_bitrate == o.screencast_min_bitrate &&
800 combined_audio_video_bwe == o.combined_audio_video_bwe &&
801 enable_dtls_srtp == o.enable_dtls_srtp &&
802 ice_candidate_pool_size == o.ice_candidate_pool_size &&
803 prune_turn_ports == o.prune_turn_ports &&
804 presume_writable_when_fully_relayed ==
805 o.presume_writable_when_fully_relayed &&
806 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800807 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700808 surface_ice_candidates_on_ice_transport_type_changed ==
809 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800810 ice_check_interval_strong_connectivity ==
811 o.ice_check_interval_strong_connectivity &&
812 ice_check_interval_weak_connectivity ==
813 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700814 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700815 ice_unwritable_timeout == o.ice_unwritable_timeout &&
816 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800817 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800818 stun_candidate_keepalive_interval ==
819 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200820 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800821 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800822 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700823 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700824 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700825 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700826 use_media_transport_for_data_channels ==
827 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700828 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100829 crypto_options == o.crypto_options &&
830 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800831}
832
833bool PeerConnectionInterface::RTCConfiguration::operator!=(
834 const PeerConnectionInterface::RTCConfiguration& o) const {
835 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800836}
837
zhihuang8f65cdf2016-05-06 18:40:30 -0700838// Generate a RTCP CNAME when a PeerConnection is created.
839std::string GenerateRtcpCname() {
840 std::string cname;
841 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100842 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800843 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700844 }
845 return cname;
846}
847
zhihuang1c378ed2017-08-17 14:10:50 -0700848bool ValidateOfferAnswerOptions(
849 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
850 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
851 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700852}
853
zhihuang1c378ed2017-08-17 14:10:50 -0700854// From |rtc_options|, fill parts of |session_options| shared by all generated
855// m= sections (in other words, nothing that involves a map/array).
856void ExtractSharedMediaSessionOptions(
857 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
858 cricket::MediaSessionOptions* session_options) {
859 session_options->vad_enabled = rtc_options.voice_activity_detection;
860 session_options->bundle_enabled = rtc_options.use_rtp_mux;
861}
zhihuanga77e6bb2017-08-14 18:17:48 -0700862
zhihuang38ede132017-06-15 12:52:32 -0700863PeerConnection::PeerConnection(PeerConnectionFactory* factory,
864 std::unique_ptr<RtcEventLog> event_log,
865 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700867 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100868 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700869 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700870 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700871 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100872 call_(std::move(call)),
873 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874
875PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100876 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800877 RTC_DCHECK_RUN_ON(signaling_thread());
878
Steve Anton8af21862017-12-15 11:20:13 -0800879 // Need to stop transceivers before destroying the stats collector because
880 // AudioRtpSender has a reference to the StatsCollector it will update when
881 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100882 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800883 transceiver->Stop();
884 }
Steve Anton4171afb2017-11-20 10:20:22 -0800885
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700886 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800887 if (stats_collector_) {
888 stats_collector_->WaitForPendingRequest();
889 stats_collector_ = nullptr;
890 }
Steve Anton75737c02017-11-06 10:37:17 -0800891
Steve Anton8af21862017-12-15 11:20:13 -0800892 // Don't destroy BaseChannels until after stats has been cleaned up so that
893 // the last stats request can still read from the channels.
894 DestroyAllChannels();
895
Mirko Bonadei675513b2017-11-09 11:09:25 +0100896 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800897
898 webrtc_session_desc_factory_.reset();
899 sctp_invoker_.reset();
900 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800901 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800902 transport_controller_.reset();
903
deadbeef91dd5672016-05-18 16:55:30 -0700904 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100905 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
906 RTC_DCHECK_RUN_ON(network_thread());
907 port_allocator_.reset();
908 });
eladalon248fd4f2017-09-06 05:18:15 -0700909 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700910 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100911 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700912 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800913 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700914 event_log_.reset();
915 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916}
917
Steve Anton8af21862017-12-15 11:20:13 -0800918void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800919 // Destroy video channels first since they may have a pointer to a voice
920 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100921 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800922 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800923 DestroyTransceiverChannel(transceiver);
924 }
925 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100926 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800927 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800928 DestroyTransceiverChannel(transceiver);
929 }
930 }
931 DestroyDataChannel();
932}
933
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000935 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700936 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100937 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100938 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100939 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700940
941 RTCError config_error = ValidateConfiguration(configuration);
942 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100943 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700944 return false;
945 }
946
Benjamin Wrightcab58882018-05-02 15:12:47 -0700947 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100948 RTC_LOG(LS_ERROR)
949 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100950 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800951 return false;
952 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200953
Benjamin Wrightcab58882018-05-02 15:12:47 -0700954 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800955 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100956 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100957 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800958 return false;
959 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700960
Benjamin Wrightcab58882018-05-02 15:12:47 -0700961 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700962 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700963 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700964 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800965
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200966 cricket::ServerAddresses stun_servers;
967 std::vector<cricket::RelayServerConfig> turn_servers;
968
969 RTCErrorType parse_error =
970 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
971 if (parse_error != RTCErrorType::NONE) {
972 return false;
973 }
974
deadbeef91dd5672016-05-18 16:55:30 -0700975 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700976 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100977 const auto pa_result =
978 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200979 RTC_FROM_HERE,
980 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100981 stun_servers, turn_servers, configuration));
982
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200983 // If initialization was successful, note if STUN or TURN servers
984 // were supplied.
985 if (!stun_servers.empty()) {
986 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
987 }
988 if (!turn_servers.empty()) {
989 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
990 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700992 // Send information about IPv4/IPv6 status.
993 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +0100994 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700995 address_family = kPeerConnection_IPv6;
996 } else {
997 address_family = kPeerConnection_IPv4;
998 }
999 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1000 kPeerConnectionAddressFamilyCounter_Max);
1001
Zhi Huange830e682018-03-30 10:48:35 -07001002 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1003
Steve Anton75737c02017-11-06 10:37:17 -08001004 // RFC 3264: The numeric value of the session id and version in the
1005 // o line MUST be representable with a "64 bit signed integer".
1006 // Due to this constraint session id |session_id_| is max limited to
1007 // LLONG_MAX.
1008 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001009 JsepTransportController::Config config;
1010 config.redetermine_role_on_ice_restart =
1011 configuration.redetermine_role_on_ice_restart;
1012 config.ssl_max_version = factory_->options().ssl_max_version;
1013 config.disable_encryption = options.disable_encryption;
1014 config.bundle_policy = configuration.bundle_policy;
1015 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001016 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1017 // stub.
1018 config.crypto_options = configuration.crypto_options.has_value()
1019 ? *configuration.crypto_options
1020 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001021 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001022 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001023#if defined(ENABLE_EXTERNAL_AUTH)
1024 config.enable_external_auth = true;
1025#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001026 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001027
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001028 if (configuration.use_datagram_transport ||
1029 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001030 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001031 if (!factory_->media_transport_factory()) {
1032 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001033 << "PeerConnecton is initialized with use_media_transport = true or "
1034 << "use_media_transport_for_data_channels = true "
1035 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001036 return false;
1037 }
1038
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001039 if (configuration.use_media_transport ||
1040 configuration.use_media_transport_for_data_channels) {
1041 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1042 // RTP media transport is introduced. But until then, we require SDES to
1043 // be enabled.
1044 if (configuration.enable_dtls_srtp.has_value() &&
1045 configuration.enable_dtls_srtp.value()) {
1046 RTC_LOG(LS_WARNING)
1047 << "When media transport is used, SDES must be enabled. Set "
1048 "configuration.enable_dtls_srtp to false. use_media_transport="
1049 << configuration.use_media_transport
1050 << ", use_media_transport_for_data_channels="
1051 << configuration.use_media_transport_for_data_channels;
1052 return false;
1053 }
1054 }
1055
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001056 config.use_media_transport_for_media = configuration.use_media_transport;
1057 config.use_media_transport_for_data_channels =
1058 configuration.use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001059 config.use_datagram_transport = configuration.use_datagram_transport;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001060 config.media_transport_factory = factory_->media_transport_factory();
1061 }
1062
Zhi Huange830e682018-03-30 10:48:35 -07001063 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001064 signaling_thread(), network_thread(), port_allocator_.get(),
1065 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001066 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001067 this, &PeerConnection::OnTransportControllerConnectionState);
1068 transport_controller_->SignalStandardizedIceConnectionState.connect(
1069 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001070 transport_controller_->SignalConnectionState.connect(
1071 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001072 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001073 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001074 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001075 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001076 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001077 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1078 transport_controller_->SignalDtlsHandshakeError.connect(
1079 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1080
1081 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001082
deadbeefab9b2d12015-10-14 11:33:11 -07001083 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001084 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085
Steve Antonba818672017-11-06 10:21:57 -08001086 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001087 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001088
Steve Anton75737c02017-11-06 10:37:17 -08001089 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1090 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1091 if (!configuration.certificates.empty()) {
1092 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1093 // just picking the first one. The decision should be made based on the DTLS
1094 // handshake. The DTLS negotiations need to know about all certificates.
1095 certificate = configuration.certificates[0];
1096 }
1097
Steve Antond25da372017-11-06 14:50:29 -08001098 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001099
1100 if (options.disable_encryption) {
1101 dtls_enabled_ = false;
1102 } else {
1103 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001104 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001105 // |configuration| can override the default |dtls_enabled_| value.
1106 if (configuration.enable_dtls_srtp) {
1107 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1108 }
1109 }
1110
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001111 if (configuration.use_media_transport_for_data_channels) {
1112 if (configuration.enable_rtp_data_channel) {
1113 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1114 "use_media_transport_for_data_channels are "
1115 "incompatible and cannot both be set to true";
1116 return false;
1117 }
1118 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1119 } else if (configuration.enable_rtp_data_channel) {
1120 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1121 // set. It takes precendence over the disable_sctp_data_channels
1122 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001123 data_channel_type_ = cricket::DCT_RTP;
1124 } else {
1125 // DTLS has to be enabled to use SCTP.
1126 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1127 data_channel_type_ = cricket::DCT_SCTP;
1128 }
1129 }
1130
1131 video_options_.screencast_min_bitrate_kbps =
1132 configuration.screencast_min_bitrate;
1133 audio_options_.combined_audio_video_bwe =
1134 configuration.combined_audio_video_bwe;
1135
1136 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001137 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001138
1139 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001140 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001141
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001142 audio_options_.audio_jitter_buffer_min_delay_ms =
1143 configuration.audio_jitter_buffer_min_delay_ms;
1144
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001145 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1146 configuration.audio_jitter_buffer_enable_rtx_handling;
1147
Steve Anton75737c02017-11-06 10:37:17 -08001148 // Whether the certificate generator/certificate is null or not determines
1149 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1150 // the right instructions by clearing the variables if needed.
1151 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001152 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001153 certificate = nullptr;
1154 } else if (certificate) {
1155 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001156 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001157 }
1158
1159 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1160 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001161 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001162 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1163 this, &PeerConnection::OnCertificateReady);
1164
1165 if (options.disable_encryption) {
1166 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1167 }
1168
1169 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001170 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001171 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172
Steve Anton4171afb2017-11-20 10:20:22 -08001173 // Add default audio/video transceivers for Plan B SDP.
1174 if (!IsUnifiedPlan()) {
1175 transceivers_.push_back(
1176 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1177 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1178 transceivers_.push_back(
1179 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1180 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1181 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001182 int delay_ms =
1183 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001184 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1185 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001186
1187 if (dependencies.video_bitrate_allocator_factory) {
1188 video_bitrate_allocator_factory_ =
1189 std::move(dependencies.video_bitrate_allocator_factory);
1190 } else {
1191 video_bitrate_allocator_factory_ =
1192 CreateBuiltinVideoBitrateAllocatorFactory();
1193 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194 return true;
1195}
1196
Steve Anton038834f2017-07-14 15:59:59 -07001197RTCError PeerConnection::ValidateConfiguration(
1198 const RTCConfiguration& config) const {
1199 if (config.ice_regather_interval_range &&
1200 config.continual_gathering_policy == GATHER_ONCE) {
1201 return RTCError(RTCErrorType::INVALID_PARAMETER,
1202 "ice_regather_interval_range specified but continual "
1203 "gathering policy is GATHER_ONCE");
1204 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001205 auto result =
1206 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1207 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001208}
1209
Yves Gerey665174f2018-06-19 15:03:05 +02001210rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001211 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001212 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1213 "Plan SdpSemantics. Please use GetSenders "
1214 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001215 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216}
1217
Yves Gerey665174f2018-06-19 15:03:05 +02001218rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001219 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001220 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1221 "Plan SdpSemantics. Please use GetReceivers "
1222 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001223 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001224}
1225
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001226bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001227 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001228 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1229 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001230 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 if (IsClosed()) {
1232 return false;
1233 }
deadbeefab9b2d12015-10-14 11:33:11 -07001234 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 return false;
1236 }
deadbeefab9b2d12015-10-14 11:33:11 -07001237
1238 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001239 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1240 observer->SignalAudioTrackAdded.connect(this,
1241 &PeerConnection::OnAudioTrackAdded);
1242 observer->SignalAudioTrackRemoved.connect(
1243 this, &PeerConnection::OnAudioTrackRemoved);
1244 observer->SignalVideoTrackAdded.connect(this,
1245 &PeerConnection::OnVideoTrackAdded);
1246 observer->SignalVideoTrackRemoved.connect(
1247 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001248 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001249
deadbeefab9b2d12015-10-14 11:33:11 -07001250 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001251 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001252 }
1253 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001254 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001255 }
1256
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001257 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001258 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 return true;
1260}
1261
1262void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001263 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001264 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1265 "Plan SdpSemantics. Please use RemoveTrack "
1266 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001267 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001268 if (!IsClosed()) {
1269 for (const auto& track : local_stream->GetAudioTracks()) {
1270 RemoveAudioTrack(track.get(), local_stream);
1271 }
1272 for (const auto& track : local_stream->GetVideoTracks()) {
1273 RemoveVideoTrack(track.get(), local_stream);
1274 }
deadbeefab9b2d12015-10-14 11:33:11 -07001275 }
deadbeefab9b2d12015-10-14 11:33:11 -07001276 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001277 stream_observers_.erase(
1278 std::remove_if(
1279 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001280 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001281 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001282 }),
1283 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001284
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 if (IsClosed()) {
1286 return;
1287 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001288 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289}
1290
Steve Anton2d6c76a2018-01-05 17:10:52 -08001291RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001292 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001293 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001294 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001295 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001296 if (!track) {
1297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1298 }
1299 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1300 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1301 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1302 "Track has invalid kind: " + track->kind());
1303 }
Steve Antonf9381f02017-12-14 10:23:57 -08001304 if (IsClosed()) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1306 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001307 }
Steve Anton4171afb2017-11-20 10:20:22 -08001308 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001309 LOG_AND_RETURN_ERROR(
1310 RTCErrorType::INVALID_PARAMETER,
1311 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001312 }
Steve Antonf9381f02017-12-14 10:23:57 -08001313 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001314 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1315 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001316 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001317 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001318 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001319 }
1320 return sender_or_error;
1321}
deadbeefe1f9d832016-01-14 15:35:42 -08001322
Steve Antonf9381f02017-12-14 10:23:57 -08001323RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1324PeerConnection::AddTrackPlanB(
1325 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001326 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001327 if (stream_ids.size() > 1u) {
1328 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1329 "AddTrack with more than one stream is not "
1330 "supported with Plan B semantics.");
1331 }
1332 std::vector<std::string> adjusted_stream_ids = stream_ids;
1333 if (adjusted_stream_ids.empty()) {
1334 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1335 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001336 cricket::MediaType media_type =
1337 (track->kind() == MediaStreamTrackInterface::kAudioKind
1338 ? cricket::MEDIA_TYPE_AUDIO
1339 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001340 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001341 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001342 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001343 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001344 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001345 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001346 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001347 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001348 if (sender_info) {
1349 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001350 }
Steve Antonf9381f02017-12-14 10:23:57 -08001351 } else {
1352 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001353 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001354 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001355 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001356 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001357 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001358 if (sender_info) {
1359 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001360 }
deadbeefe1f9d832016-01-14 15:35:42 -08001361 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001362 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001363}
deadbeefe1f9d832016-01-14 15:35:42 -08001364
Steve Antonf9381f02017-12-14 10:23:57 -08001365RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1366PeerConnection::AddTrackUnifiedPlan(
1367 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001368 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001369 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1370 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001371 RTC_LOG(LS_INFO) << "Reusing an existing "
1372 << cricket::MediaTypeToString(transceiver->media_type())
1373 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001374 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001375 transceiver->internal()->set_direction(
1376 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001377 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001378 transceiver->internal()->set_direction(
1379 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001380 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001381 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001382 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001383 } else {
1384 cricket::MediaType media_type =
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind
1386 ? cricket::MEDIA_TYPE_AUDIO
1387 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001388 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1389 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001390 std::string sender_id = track->id();
1391 // Avoid creating a sender with an existing ID by generating a random ID.
1392 // This can happen if this is the second time AddTrack has created a sender
1393 // for this track.
1394 if (FindSenderById(sender_id)) {
1395 sender_id = rtc::CreateRandomUuid();
1396 }
Florent Castelli892acf02018-10-01 22:47:20 +02001397 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1399 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001400 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001401 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001402 }
Steve Antonf9381f02017-12-14 10:23:57 -08001403 return transceiver->sender();
1404}
1405
1406rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1407PeerConnection::FindFirstTransceiverForAddedTrack(
1408 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1409 RTC_DCHECK(track);
1410 for (auto transceiver : transceivers_) {
1411 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001412 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001413 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001414 !transceiver->internal()->has_ever_been_used_to_send() &&
1415 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001416 return transceiver;
1417 }
1418 }
1419 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001420}
1421
1422bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1423 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001424 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001425}
1426
Steve Anton24db5732018-07-23 10:27:33 -07001427RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001428 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001429 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001430 if (!sender) {
1431 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1432 }
deadbeefe1f9d832016-01-14 15:35:42 -08001433 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001434 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1435 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001436 }
Steve Antonf9381f02017-12-14 10:23:57 -08001437 if (IsUnifiedPlan()) {
1438 auto transceiver = FindTransceiverBySender(sender);
1439 if (!transceiver || !sender->track()) {
1440 return RTCError::OK();
1441 }
1442 sender->SetTrack(nullptr);
1443 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001444 transceiver->internal()->set_direction(
1445 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001446 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001447 transceiver->internal()->set_direction(
1448 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001449 }
Steve Anton4171afb2017-11-20 10:20:22 -08001450 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001451 bool removed;
1452 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1453 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1454 } else {
1455 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1456 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1457 }
1458 if (!removed) {
1459 LOG_AND_RETURN_ERROR(
1460 RTCErrorType::INVALID_PARAMETER,
1461 "Couldn't find sender " + sender->id() + " to remove.");
1462 }
Steve Anton4171afb2017-11-20 10:20:22 -08001463 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001464 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001465 return RTCError::OK();
1466}
1467
1468rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1469PeerConnection::FindTransceiverBySender(
1470 rtc::scoped_refptr<RtpSenderInterface> sender) {
1471 for (auto transceiver : transceivers_) {
1472 if (transceiver->sender() == sender) {
1473 return transceiver;
1474 }
1475 }
1476 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001477}
1478
Steve Anton9158ef62017-11-27 13:01:52 -08001479RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1480PeerConnection::AddTransceiver(
1481 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1482 return AddTransceiver(track, RtpTransceiverInit());
1483}
1484
1485RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1486PeerConnection::AddTransceiver(
1487 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1488 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001489 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001490 RTC_CHECK(IsUnifiedPlan())
1491 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001492 if (!track) {
1493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1494 }
1495 cricket::MediaType media_type;
1496 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1497 media_type = cricket::MEDIA_TYPE_AUDIO;
1498 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1499 media_type = cricket::MEDIA_TYPE_VIDEO;
1500 } else {
1501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1502 "Track kind is not audio or video");
1503 }
1504 return AddTransceiver(media_type, track, init);
1505}
1506
1507RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1508PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1509 return AddTransceiver(media_type, RtpTransceiverInit());
1510}
1511
1512RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1513PeerConnection::AddTransceiver(cricket::MediaType media_type,
1514 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001515 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001516 RTC_CHECK(IsUnifiedPlan())
1517 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001518 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1519 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1520 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1521 "media type is not audio or video");
1522 }
1523 return AddTransceiver(media_type, nullptr, init);
1524}
1525
1526RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1527PeerConnection::AddTransceiver(
1528 cricket::MediaType media_type,
1529 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001530 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001531 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001532 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1533 media_type == cricket::MEDIA_TYPE_VIDEO));
1534 if (track) {
1535 RTC_DCHECK_EQ(media_type,
1536 (track->kind() == MediaStreamTrackInterface::kAudioKind
1537 ? cricket::MEDIA_TYPE_AUDIO
1538 : cricket::MEDIA_TYPE_VIDEO));
1539 }
1540
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001541 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1542 init.send_encodings.size(), 0, 7, 8);
1543
Amit Hilbuchaa584152019-02-06 17:09:52 -08001544 size_t num_rids = absl::c_count_if(init.send_encodings,
1545 [](const RtpEncodingParameters& encoding) {
1546 return !encoding.rid.empty();
1547 });
1548 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001549 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001550 RTCErrorType::INVALID_PARAMETER,
1551 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001552 }
1553
Amit Hilbuchf4770402019-04-08 14:11:57 -07001554 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1555 [](const RtpEncodingParameters& encoding) {
1556 return !IsLegalRsidName(encoding.rid);
1557 })) {
1558 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1559 "Invalid RID value provided.");
1560 }
1561
Amit Hilbuchaa584152019-02-06 17:09:52 -08001562 if (absl::c_any_of(init.send_encodings,
1563 [](const RtpEncodingParameters& encoding) {
1564 return encoding.ssrc.has_value();
1565 })) {
1566 LOG_AND_RETURN_ERROR(
1567 RTCErrorType::UNSUPPORTED_PARAMETER,
1568 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001569 }
1570
1571 RtpParameters parameters;
1572 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001573
1574 // Encodings are dropped from the tail if too many are provided.
1575 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1576 parameters.encodings.erase(
1577 parameters.encodings.begin() + kMaxSimulcastStreams,
1578 parameters.encodings.end());
1579 }
1580
1581 // Single RID should be removed.
1582 if (parameters.encodings.size() == 1 &&
1583 !parameters.encodings[0].rid.empty()) {
1584 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1585 parameters.encodings[0].rid.clear();
1586 }
1587
1588 // If RIDs were not provided, they are generated for simulcast scenario.
1589 if (parameters.encodings.size() > 1 && num_rids == 0) {
1590 rtc::UniqueStringGenerator rid_generator;
1591 for (RtpEncodingParameters& encoding : parameters.encodings) {
1592 encoding.rid = rid_generator();
1593 }
1594 }
1595
Florent Castelli892acf02018-10-01 22:47:20 +02001596 if (UnimplementedRtpParameterHasValue(parameters)) {
1597 LOG_AND_RETURN_ERROR(
1598 RTCErrorType::UNSUPPORTED_PARAMETER,
1599 "Attempted to set an unimplemented parameter of RtpParameters.");
1600 }
Steve Anton9158ef62017-11-27 13:01:52 -08001601
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001602 auto result = cricket::CheckRtpParametersValues(parameters);
1603 if (!result.ok()) {
1604 LOG_AND_RETURN_ERROR(result.type(), result.message());
1605 }
1606
Steve Anton3d954a62018-04-02 11:27:23 -07001607 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1608 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001609 // Set the sender ID equal to the track ID if the track is specified unless
1610 // that sender ID is already in use.
1611 std::string sender_id =
1612 (track && !FindSenderById(track->id()) ? track->id()
1613 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001614 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001615 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001616 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1617 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1618 transceiver->internal()->set_direction(init.direction);
1619
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001620 if (update_negotiation_needed) {
1621 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001622 }
Steve Antonf9381f02017-12-14 10:23:57 -08001623
1624 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1625}
1626
Steve Anton02ee47c2018-01-10 16:26:06 -08001627rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1628PeerConnection::CreateSender(
1629 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001630 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001631 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001632 const std::vector<std::string>& stream_ids,
1633 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001634 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001635 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001636 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1637 RTC_DCHECK(!track ||
1638 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1639 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1640 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001641 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001642 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001643 } else {
1644 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1645 RTC_DCHECK(!track ||
1646 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1647 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001648 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001649 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001650 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001651 bool set_track_succeeded = sender->SetTrack(track);
1652 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001653 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001654 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001655 return sender;
1656}
1657
1658rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1659PeerConnection::CreateReceiver(cricket::MediaType media_type,
1660 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001661 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1662 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001663 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001664 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001665 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1666 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001667 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001668 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001669 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001670 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001671 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1672 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001673 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001674 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001675 return receiver;
1676}
1677
1678rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1679PeerConnection::CreateAndAddTransceiver(
1680 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1681 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1682 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001683 // Ensure that the new sender does not have an ID that is already in use by
1684 // another sender.
1685 // Allow receiver IDs to conflict since those come from remote SDP (which
1686 // could be invalid, but should not cause a crash).
1687 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001688 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001689 signaling_thread(),
1690 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001691 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001692 transceiver->internal()->SignalNegotiationNeeded.connect(
1693 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001694 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001695}
1696
Steve Anton52d86772018-02-20 15:48:12 -08001697void PeerConnection::OnNegotiationNeeded() {
1698 RTC_DCHECK_RUN_ON(signaling_thread());
1699 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001700 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001701}
1702
deadbeeffac06552015-11-25 11:26:01 -08001703rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001704 const std::string& kind,
1705 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001706 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001707 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1708 "Plan SdpSemantics. Please use AddTransceiver "
1709 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001710 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001711 if (IsClosed()) {
1712 return nullptr;
1713 }
Steve Anton4171afb2017-11-20 10:20:22 -08001714
Seth Hampson5b4f0752018-04-02 16:31:36 -07001715 // Internally we need to have one stream with Plan B semantics, so we
1716 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001717 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001718 if (stream_id.empty()) {
1719 stream_ids.push_back(rtc::CreateRandomUuid());
1720 RTC_LOG(LS_INFO)
1721 << "No stream_id specified for sender. Generated stream ID: "
1722 << stream_ids[0];
1723 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001724 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001725 }
1726
Steve Anton4171afb2017-11-20 10:20:22 -08001727 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001728 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001729 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001730 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001731 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001732 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001733 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001734 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001735 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001736 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001737 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001738 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001739 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001740 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001741 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001742 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001743 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001744 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001745 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001746 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001747 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001748
deadbeefe1f9d832016-01-14 15:35:42 -08001749 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001750}
1751
deadbeef70ab1a12015-09-28 16:53:55 -07001752std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1753 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001754 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001755 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001756 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001757 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001758 }
1759 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001760}
1761
Steve Anton4171afb2017-11-20 10:20:22 -08001762std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1763PeerConnection::GetSendersInternal() const {
1764 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1765 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001766 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001767 auto senders = transceiver->internal()->senders();
1768 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1769 }
1770 return all_senders;
1771}
1772
deadbeef70ab1a12015-09-28 16:53:55 -07001773std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1774PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001775 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001776 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001777 for (const auto& receiver : GetReceiversInternal()) {
1778 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001779 }
1780 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001781}
1782
Steve Anton4171afb2017-11-20 10:20:22 -08001783std::vector<
1784 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1785PeerConnection::GetReceiversInternal() const {
1786 std::vector<
1787 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1788 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001789 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001790 auto receivers = transceiver->internal()->receivers();
1791 all_receivers.insert(all_receivers.end(), receivers.begin(),
1792 receivers.end());
1793 }
1794 return all_receivers;
1795}
1796
Steve Anton9158ef62017-11-27 13:01:52 -08001797std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1798PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001799 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001800 RTC_CHECK(IsUnifiedPlan())
1801 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001802 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001803 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001804 all_transceivers.push_back(transceiver);
1805 }
1806 return all_transceivers;
1807}
1808
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001810 MediaStreamTrackInterface* track,
1811 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001812 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001813 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001814 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001815 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001816 return false;
1817 }
1818
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001819 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001820 // The StatsCollector is used to tell if a track is valid because it may
1821 // remember tracks that the PeerConnection previously removed.
1822 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001823 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1824 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001825 return false;
1826 }
Steve Antonad182762018-09-05 20:22:40 +00001827 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1828 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001829 return true;
1830}
1831
hbos74e1a4f2016-09-15 23:33:01 -07001832void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001833 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001834 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001835 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001836 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001837 stats_collector_->GetStatsReport(callback);
1838}
1839
Henrik Boström1df1bf82018-03-20 13:24:20 +01001840void PeerConnection::GetStats(
1841 rtc::scoped_refptr<RtpSenderInterface> selector,
1842 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1843 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001844 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001845 RTC_DCHECK(callback);
1846 RTC_DCHECK(stats_collector_);
1847 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1848 if (selector) {
1849 for (const auto& proxy_transceiver : transceivers_) {
1850 for (const auto& proxy_sender :
1851 proxy_transceiver->internal()->senders()) {
1852 if (proxy_sender == selector) {
1853 internal_sender = proxy_sender->internal();
1854 break;
1855 }
1856 }
1857 if (internal_sender)
1858 break;
1859 }
1860 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001861 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001862 // belong to the PeerConnection (in Plan B, senders can be removed from the
1863 // PeerConnection). This means that "all the stats objects representing the
1864 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1865 // produces an empty stats report.
1866 stats_collector_->GetStatsReport(internal_sender, callback);
1867}
1868
1869void PeerConnection::GetStats(
1870 rtc::scoped_refptr<RtpReceiverInterface> selector,
1871 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1872 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001873 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001874 RTC_DCHECK(callback);
1875 RTC_DCHECK(stats_collector_);
1876 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1877 if (selector) {
1878 for (const auto& proxy_transceiver : transceivers_) {
1879 for (const auto& proxy_receiver :
1880 proxy_transceiver->internal()->receivers()) {
1881 if (proxy_receiver == selector) {
1882 internal_receiver = proxy_receiver->internal();
1883 break;
1884 }
1885 }
1886 if (internal_receiver)
1887 break;
1888 }
1889 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001890 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001891 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1892 // the PeerConnection). This means that "all the stats objects representing
1893 // the selector" is an empty set. Invoking GetStatsReport() with a null
1894 // selector produces an empty stats report.
1895 stats_collector_->GetStatsReport(internal_receiver, callback);
1896}
1897
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001899 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900 return signaling_state_;
1901}
1902
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001903PeerConnectionInterface::IceConnectionState
1904PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001905 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001906 return ice_connection_state_;
1907}
1908
Alex Loiko9289eda2018-11-23 16:18:59 +00001909PeerConnectionInterface::IceConnectionState
1910PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001911 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001912 return standardized_ice_connection_state_;
1913}
1914
Jonas Olsson635474e2018-10-18 15:58:17 +02001915PeerConnectionInterface::PeerConnectionState
1916PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001917 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001918 return connection_state_;
1919}
1920
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921PeerConnectionInterface::IceGatheringState
1922PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001923 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924 return ice_gathering_state_;
1925}
1926
Yves Gerey665174f2018-06-19 15:03:05 +02001927rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 const std::string& label,
1929 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001930 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001931 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001932
deadbeefab9b2d12015-10-14 11:33:11 -07001933 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001934
kwibergd1fe2812016-04-27 06:47:29 -07001935 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001936 if (config) {
1937 internal_config.reset(new InternalDataChannelInit(*config));
1938 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001939 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001940 InternalCreateDataChannel(label, internal_config.get()));
1941 if (!channel.get()) {
1942 return nullptr;
1943 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001945 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1946 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001947 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001948 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001949 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001950 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951 return DataChannelProxy::Create(signaling_thread(), channel.get());
1952}
1953
1954void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001955 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001956 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001957 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001958
nisse7ce109a2017-01-31 00:57:56 -08001959 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001960 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001961 return;
1962 }
deadbeefab9b2d12015-10-14 11:33:11 -07001963
Steve Anton8d3444d2017-10-20 15:30:51 -07001964 if (IsClosed()) {
1965 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001966 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001967 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001968 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001969 return;
1970 }
1971
zhihuang1c378ed2017-08-17 14:10:50 -07001972 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001973 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001974 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001975 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001976 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001977 return;
1978 }
1979
Steve Anton22da89f2018-01-25 13:58:07 -08001980 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1981 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1982 if (IsUnifiedPlan()) {
1983 RTCError error = HandleLegacyOfferOptions(options);
1984 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001985 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001986 return;
1987 }
1988 }
1989
zhihuang1c378ed2017-08-17 14:10:50 -07001990 cricket::MediaSessionOptions session_options;
1991 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001992 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993}
1994
Steve Anton22da89f2018-01-25 13:58:07 -08001995RTCError PeerConnection::HandleLegacyOfferOptions(
1996 const RTCOfferAnswerOptions& options) {
1997 RTC_DCHECK(IsUnifiedPlan());
1998
1999 if (options.offer_to_receive_audio == 0) {
2000 RemoveRecvDirectionFromReceivingTransceiversOfType(
2001 cricket::MEDIA_TYPE_AUDIO);
2002 } else if (options.offer_to_receive_audio == 1) {
2003 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2004 } else if (options.offer_to_receive_audio > 1) {
2005 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2006 "offer_to_receive_audio > 1 is not supported.");
2007 }
2008
2009 if (options.offer_to_receive_video == 0) {
2010 RemoveRecvDirectionFromReceivingTransceiversOfType(
2011 cricket::MEDIA_TYPE_VIDEO);
2012 } else if (options.offer_to_receive_video == 1) {
2013 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2014 } else if (options.offer_to_receive_video > 1) {
2015 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2016 "offer_to_receive_video > 1 is not supported.");
2017 }
2018
2019 return RTCError::OK();
2020}
2021
2022void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2023 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002024 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002025 RtpTransceiverDirection new_direction =
2026 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2027 if (new_direction != transceiver->direction()) {
2028 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2029 << " transceiver (MID="
2030 << transceiver->mid().value_or("<not set>") << ") from "
2031 << RtpTransceiverDirectionToString(
2032 transceiver->direction())
2033 << " to "
2034 << RtpTransceiverDirectionToString(new_direction)
2035 << " since CreateOffer specified offer_to_receive=0";
2036 transceiver->internal()->set_direction(new_direction);
2037 }
Steve Anton22da89f2018-01-25 13:58:07 -08002038 }
2039}
2040
2041void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2042 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002043 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002044 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002045 RTC_LOG(LS_INFO)
2046 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2047 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002048 RtpTransceiverInit init;
2049 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002050 AddTransceiver(media_type, nullptr, init,
2051 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002052 }
2053}
2054
2055std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2056PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2057 std::vector<
2058 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2059 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002060 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002061 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002062 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2063 receiving_transceivers.push_back(transceiver);
2064 }
2065 }
2066 return receiving_transceivers;
2067}
2068
htaa2a49d92016-03-04 02:51:39 -08002069void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2070 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002071 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002072 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002073 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002074 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002075 return;
2076 }
2077
Steve Antondffead82018-02-06 10:31:29 -08002078 if (!(signaling_state_ == kHaveRemoteOffer ||
2079 signaling_state_ == kHaveLocalPrAnswer)) {
2080 std::string error =
2081 "PeerConnection cannot create an answer in a state other than "
2082 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002083 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002084 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002085 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002086 return;
2087 }
2088
Steve Antondffead82018-02-06 10:31:29 -08002089 // The remote description should be set if we're in the right state.
2090 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002091
Steve Anton22da89f2018-01-25 13:58:07 -08002092 if (IsUnifiedPlan()) {
2093 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2094 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2095 "supported with Unified Plan semantics. Use the "
2096 "RtpTransceiver API instead.";
2097 }
2098 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2099 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2100 "supported with Unified Plan semantics. Use the "
2101 "RtpTransceiver API instead.";
2102 }
2103 }
2104
htaa2a49d92016-03-04 02:51:39 -08002105 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002106 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002107
Steve Antond25da372017-11-06 14:50:29 -08002108 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002109}
2110
2111void PeerConnection::SetLocalDescription(
2112 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002113 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002114 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002115 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002116
Steve Anton80dd7b52018-02-16 17:08:42 -08002117 // The SetLocalDescription contract is that we take ownership of the session
2118 // description regardless of the outcome, so wrap it in a unique_ptr right
2119 // away. Ideally, SetLocalDescription's signature will be changed to take the
2120 // description as a unique_ptr argument to formalize this agreement.
2121 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2122
nisse7ce109a2017-01-31 00:57:56 -08002123 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002124 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125 return;
2126 }
Steve Anton8a006912017-12-04 15:25:56 -08002127
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002129 PostSetSessionDescriptionFailure(
2130 observer,
2131 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132 return;
2133 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002134
Steve Anton80dd7b52018-02-16 17:08:42 -08002135 // If a session error has occurred the PeerConnection is in a possibly
2136 // inconsistent state so fail right away.
2137 if (session_error() != SessionError::kNone) {
2138 std::string error_message = GetSessionErrorMsg();
2139 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002140 PostSetSessionDescriptionFailure(
2141 observer,
2142 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002143 return;
2144 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002145
Steve Anton80dd7b52018-02-16 17:08:42 -08002146 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2147 if (!error.ok()) {
2148 std::string error_message = GetSetDescriptionErrorMessage(
2149 cricket::CS_LOCAL, desc->GetType(), error);
2150 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002151 PostSetSessionDescriptionFailure(
2152 observer,
2153 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002154 return;
2155 }
2156
2157 // Grab the description type before moving ownership to ApplyLocalDescription,
2158 // which may destroy it before returning.
2159 const SdpType type = desc->GetType();
2160
2161 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002162 // |desc| may be destroyed at this point.
2163
2164 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002165 // If ApplyLocalDescription fails, the PeerConnection could be in an
2166 // inconsistent state, so act conservatively here and set the session error
2167 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2168 SetSessionError(SessionError::kContent, error.message());
2169 std::string error_message =
2170 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2171 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002172 PostSetSessionDescriptionFailure(
2173 observer,
2174 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002175 return;
2176 }
Steve Anton8a006912017-12-04 15:25:56 -08002177 RTC_DCHECK(local_description());
2178
2179 PostSetSessionDescriptionSuccess(observer);
2180
Steve Antonad182762018-09-05 20:22:40 +00002181 // MaybeStartGathering needs to be called after posting
2182 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2183 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002184 transport_controller_->MaybeStartGathering();
2185
Steve Antona3a92c22017-12-07 10:27:41 -08002186 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002187 // TODO(deadbeef): We already had to hop to the network thread for
2188 // MaybeStartGathering...
2189 network_thread()->Invoke<void>(
2190 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2191 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002192 // Make UMA notes about what was agreed to.
2193 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002194 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002195
2196 if (IsUnifiedPlan()) {
2197 bool was_negotiation_needed = is_negotiation_needed_;
2198 UpdateNegotiationNeeded();
2199 if (signaling_state() == kStable && was_negotiation_needed &&
2200 is_negotiation_needed_) {
2201 Observer()->OnRenegotiationNeeded();
2202 }
2203 }
2204
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002205 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002206}
2207
2208RTCError PeerConnection::ApplyLocalDescription(
2209 std::unique_ptr<SessionDescriptionInterface> desc) {
2210 RTC_DCHECK_RUN_ON(signaling_thread());
2211 RTC_DCHECK(desc);
2212
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 // Update stats here so that we have the most recent stats for tracks and
2214 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002215 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002216
Steve Antondcc3c022017-12-22 16:02:54 -08002217 // Take a reference to the old local description since it's used below to
2218 // compare against the new local description. When setting the new local
2219 // description, grab ownership of the replaced session description in case it
2220 // is the same as |old_local_description|, to keep it alive for the duration
2221 // of the method.
2222 const SessionDescriptionInterface* old_local_description =
2223 local_description();
2224 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002225 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002226 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002227 replaced_local_description = pending_local_description_
2228 ? std::move(pending_local_description_)
2229 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002230 current_local_description_ = std::move(desc);
2231 pending_local_description_ = nullptr;
2232 current_remote_description_ = std::move(pending_remote_description_);
2233 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002234 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002235 pending_local_description_ = std::move(desc);
2236 }
2237 // The session description to apply now must be accessed by
2238 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002239 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002240
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002241 // Report statistics about any use of simulcast.
2242 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2243 *local_description()->description());
2244
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002245 if (!is_caller_) {
2246 if (remote_description()) {
2247 // Remote description was applied first, so this PC is the callee.
2248 is_caller_ = false;
2249 } else {
2250 // Local description is applied first, so this PC is the caller.
2251 is_caller_ = true;
2252 }
2253 }
2254
Zhi Huange830e682018-03-30 10:48:35 -07002255 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2256 if (!error.ok()) {
2257 return error;
2258 }
2259
Steve Antondcc3c022017-12-22 16:02:54 -08002260 if (IsUnifiedPlan()) {
2261 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002262 cricket::CS_LOCAL, *local_description(), old_local_description,
2263 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002264 if (!error.ok()) {
2265 return error;
2266 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002267 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2268 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002269 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002270 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2271 // Note that code paths that don't set MID won't be able to use
2272 // information about DTLS transports.
2273 if (transceiver->mid()) {
2274 auto dtls_transport =
2275 LookupDtlsTransportByMidInternal(*transceiver->mid());
2276 transceiver->internal()->sender_internal()->set_transport(
2277 dtls_transport);
2278 transceiver->internal()->receiver_internal()->set_transport(
2279 dtls_transport);
2280 }
2281
Steve Antondcc3c022017-12-22 16:02:54 -08002282 const ContentInfo* content =
2283 FindMediaSectionForTransceiver(transceiver, local_description());
2284 if (!content) {
2285 continue;
2286 }
2287 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002288 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2289 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002290 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002291 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2292 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2293 // "recvonly", process the removal of a remote track for the media
2294 // description, given transceiver, removeList, and muteTracks.
2295 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2296 (transceiver->internal()->fired_direction() &&
2297 RtpTransceiverDirectionHasRecv(
2298 *transceiver->internal()->fired_direction()))) {
2299 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2300 &removed_streams);
2301 }
2302 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2303 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002304 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002305 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002306 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002307 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002308 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002309 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002310 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002311 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002312 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002313 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002314 }
2315 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002316 // Media channels will be created only when offer is set. These may use new
2317 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002318 if (type == SdpType::kOffer) {
2319 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2320 // description is applied. Restore back to old description.
2321 RTCError error = CreateChannels(*local_description()->description());
2322 if (!error.ok()) {
2323 return error;
2324 }
2325 }
Steve Antondcc3c022017-12-22 16:02:54 -08002326 // Remove unused channels if MediaContentDescription is rejected.
2327 RemoveUnusedChannels(local_description()->description());
2328 }
Steve Anton8a006912017-12-04 15:25:56 -08002329
Zhi Huange830e682018-03-30 10:48:35 -07002330 error = UpdateSessionState(type, cricket::CS_LOCAL,
2331 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002332 if (!error.ok()) {
2333 return error;
2334 }
Steve Antondcc3c022017-12-22 16:02:54 -08002335
Steve Anton8a006912017-12-04 15:25:56 -08002336 if (remote_description()) {
2337 // Now that we have a local description, we can push down remote candidates.
2338 UseCandidatesInSessionDescription(remote_description());
2339 }
2340
2341 pending_ice_restarts_.clear();
2342 if (session_error() != SessionError::kNone) {
2343 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2344 }
2345
deadbeefab9b2d12015-10-14 11:33:11 -07002346 // If setting the description decided our SSL role, allocate any necessary
2347 // SCTP sids.
2348 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002349 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002350 AllocateSctpSids(role);
2351 }
2352
Steve Antond3679212018-01-17 17:41:02 -08002353 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002354 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002355 const ContentInfo* content =
2356 FindMediaSectionForTransceiver(transceiver, local_description());
2357 if (!content) {
2358 continue;
2359 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002360 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2361 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002362 // 0 is a special value meaning "this sender has no associated send
2363 // stream". Need to call this so the sender won't attempt to configure
2364 // a no longer existing stream and run into DCHECKs in the lower
2365 // layers.
2366 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002367 } else {
2368 // Get the StreamParams from the channel which could generate SSRCs.
2369 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002370 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002371 streams[0].stream_ids());
2372 transceiver->internal()->sender_internal()->SetSsrc(
2373 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002374 }
2375 }
2376 } else {
2377 // Plan B semantics.
2378
Steve Antondcc3c022017-12-22 16:02:54 -08002379 // Update state and SSRC of local MediaStreams and DataChannels based on the
2380 // local session description.
2381 const cricket::ContentInfo* audio_content =
2382 GetFirstAudioContent(local_description()->description());
2383 if (audio_content) {
2384 if (audio_content->rejected) {
2385 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2386 } else {
2387 const cricket::AudioContentDescription* audio_desc =
2388 audio_content->media_description()->as_audio();
2389 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2390 }
deadbeeffaac4972015-11-12 15:33:07 -08002391 }
deadbeefab9b2d12015-10-14 11:33:11 -07002392
Steve Antondcc3c022017-12-22 16:02:54 -08002393 const cricket::ContentInfo* video_content =
2394 GetFirstVideoContent(local_description()->description());
2395 if (video_content) {
2396 if (video_content->rejected) {
2397 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2398 } else {
2399 const cricket::VideoContentDescription* video_desc =
2400 video_content->media_description()->as_video();
2401 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2402 }
deadbeeffaac4972015-11-12 15:33:07 -08002403 }
deadbeefab9b2d12015-10-14 11:33:11 -07002404 }
2405
2406 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002407 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002408 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002409 const cricket::RtpDataContentDescription* rtp_data_desc =
2410 data_content->media_description()->as_rtp_data();
2411 // rtp_data_desc will be null if this is an SCTP description.
2412 if (rtp_data_desc) {
2413 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002414 }
2415 }
2416
Steve Anton8a006912017-12-04 15:25:56 -08002417 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002418}
2419
Steve Anton06817cd2018-12-18 15:55:30 -08002420// The SDP parser used to populate these values by default for the 'content
2421// name' if an a=mid line was absent.
2422static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2423 switch (media_type) {
2424 case cricket::MEDIA_TYPE_AUDIO:
2425 return cricket::CN_AUDIO;
2426 case cricket::MEDIA_TYPE_VIDEO:
2427 return cricket::CN_VIDEO;
2428 case cricket::MEDIA_TYPE_DATA:
2429 return cricket::CN_DATA;
2430 }
2431 RTC_NOTREACHED();
2432 return "";
2433}
2434
2435void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002436 cricket::SessionDescription* new_remote_description) {
2437 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002438 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002439 const cricket::ContentInfos& local_contents =
2440 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002441 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002442 const cricket::ContentInfos& remote_contents =
2443 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002444 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002445 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2446 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002447 if (!content.name.empty()) {
2448 continue;
2449 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002450 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002451 absl::string_view source_explanation;
2452 if (IsUnifiedPlan()) {
2453 if (i < local_contents.size()) {
2454 new_mid = local_contents[i].name;
2455 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002456 } else if (i < remote_contents.size()) {
2457 new_mid = remote_contents[i].name;
2458 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002459 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002460 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002461 source_explanation = "generated just now";
2462 }
2463 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002464 new_mid = std::string(
2465 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002466 source_explanation = "to match pre-existing behavior";
2467 }
Steve Antond7180cc2019-02-07 10:44:53 -08002468 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002469 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002470 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002471 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2472 << " is missing an a=mid line. Filling in the value '"
2473 << new_mid << "' " << source_explanation << ".";
2474 }
2475}
2476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002477void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002478 SetSessionDescriptionObserver* observer,
2479 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002480 SetRemoteDescription(
2481 std::unique_ptr<SessionDescriptionInterface>(desc),
2482 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2483 new SetRemoteDescriptionObserverAdapter(this, observer)));
2484}
2485
2486void PeerConnection::SetRemoteDescription(
2487 std::unique_ptr<SessionDescriptionInterface> desc,
2488 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002489 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002490 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002491
nisse7ce109a2017-01-31 00:57:56 -08002492 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002493 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494 return;
2495 }
Steve Anton8a006912017-12-04 15:25:56 -08002496
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002497 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002498 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002499 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002500 return;
2501 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002502
Steve Anton80dd7b52018-02-16 17:08:42 -08002503 // If a session error has occurred the PeerConnection is in a possibly
2504 // inconsistent state so fail right away.
2505 if (session_error() != SessionError::kNone) {
2506 std::string error_message = GetSessionErrorMsg();
2507 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2508 observer->OnSetRemoteDescriptionComplete(
2509 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2510 return;
2511 }
Steve Anton71439a62018-02-15 11:53:06 -08002512
Steve Antonba42e992018-04-09 14:10:01 -07002513 if (desc->GetType() == SdpType::kOffer) {
2514 // Report to UMA the format of the received offer.
2515 ReportSdpFormatReceived(*desc);
2516 }
2517
Steve Anton06817cd2018-12-18 15:55:30 -08002518 // Handle remote descriptions missing a=mid lines for interop with legacy end
2519 // points.
2520 FillInMissingRemoteMids(desc->description());
2521
Steve Anton80dd7b52018-02-16 17:08:42 -08002522 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002523 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002524 std::string error_message = GetSetDescriptionErrorMessage(
2525 cricket::CS_REMOTE, desc->GetType(), error);
2526 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002527 observer->OnSetRemoteDescriptionComplete(
2528 RTCError(error.type(), std::move(error_message)));
2529 return;
2530 }
Steve Anton71439a62018-02-15 11:53:06 -08002531
Steve Anton80dd7b52018-02-16 17:08:42 -08002532 // Grab the description type before moving ownership to
2533 // ApplyRemoteDescription, which may destroy it before returning.
2534 const SdpType type = desc->GetType();
2535
2536 error = ApplyRemoteDescription(std::move(desc));
2537 // |desc| may be destroyed at this point.
2538
2539 if (!error.ok()) {
2540 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2541 // inconsistent state, so act conservatively here and set the session error
2542 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2543 SetSessionError(SessionError::kContent, error.message());
2544 std::string error_message =
2545 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2546 RTC_LOG(LS_ERROR) << error_message;
2547 observer->OnSetRemoteDescriptionComplete(
2548 RTCError(error.type(), std::move(error_message)));
2549 return;
2550 }
2551 RTC_DCHECK(remote_description());
2552
2553 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002554 // TODO(deadbeef): We already had to hop to the network thread for
2555 // MaybeStartGathering...
2556 network_thread()->Invoke<void>(
2557 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2558 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002559 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002560 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002561 }
2562
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002563 if (IsUnifiedPlan()) {
2564 bool was_negotiation_needed = is_negotiation_needed_;
2565 UpdateNegotiationNeeded();
2566 if (signaling_state() == kStable && was_negotiation_needed &&
2567 is_negotiation_needed_) {
2568 Observer()->OnRenegotiationNeeded();
2569 }
2570 }
2571
Steve Anton8a006912017-12-04 15:25:56 -08002572 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002573 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002574}
2575
2576RTCError PeerConnection::ApplyRemoteDescription(
2577 std::unique_ptr<SessionDescriptionInterface> desc) {
2578 RTC_DCHECK_RUN_ON(signaling_thread());
2579 RTC_DCHECK(desc);
2580
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002581 // Update stats here so that we have the most recent stats for tracks and
2582 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002583 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002584
Steve Antondcc3c022017-12-22 16:02:54 -08002585 // Take a reference to the old remote description since it's used below to
2586 // compare against the new remote description. When setting the new remote
2587 // description, grab ownership of the replaced session description in case it
2588 // is the same as |old_remote_description|, to keep it alive for the duration
2589 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002590 const SessionDescriptionInterface* old_remote_description =
2591 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002592 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002593 SdpType type = desc->GetType();
2594 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002595 replaced_remote_description = pending_remote_description_
2596 ? std::move(pending_remote_description_)
2597 : std::move(current_remote_description_);
2598 current_remote_description_ = std::move(desc);
2599 pending_remote_description_ = nullptr;
2600 current_local_description_ = std::move(pending_local_description_);
2601 } else {
2602 replaced_remote_description = std::move(pending_remote_description_);
2603 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604 }
Steve Anton8a006912017-12-04 15:25:56 -08002605 // The session description to apply now must be accessed by
2606 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002607 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002608
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002609 // Report statistics about any use of simulcast.
2610 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2611 *remote_description()->description());
2612
Zhi Huange830e682018-03-30 10:48:35 -07002613 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2614 if (!error.ok()) {
2615 return error;
2616 }
Steve Anton8a006912017-12-04 15:25:56 -08002617 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002618 if (IsUnifiedPlan()) {
2619 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002620 cricket::CS_REMOTE, *remote_description(), local_description(),
2621 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002622 if (!error.ok()) {
2623 return error;
2624 }
Steve Antondcc3c022017-12-22 16:02:54 -08002625 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002626 // Media channels will be created only when offer is set. These may use new
2627 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002628 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002629 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002630 // description is applied. Restore back to old description.
2631 RTCError error = CreateChannels(*remote_description()->description());
2632 if (!error.ok()) {
2633 return error;
2634 }
2635 }
Steve Antondcc3c022017-12-22 16:02:54 -08002636 // Remove unused channels if MediaContentDescription is rejected.
2637 RemoveUnusedChannels(remote_description()->description());
2638 }
Steve Anton8a006912017-12-04 15:25:56 -08002639
Zhi Huange830e682018-03-30 10:48:35 -07002640 // NOTE: Candidates allocation will be initiated only when
2641 // SetLocalDescription is called.
2642 error = UpdateSessionState(type, cricket::CS_REMOTE,
2643 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002644 if (!error.ok()) {
2645 return error;
2646 }
2647
2648 if (local_description() &&
2649 !UseCandidatesInSessionDescription(remote_description())) {
2650 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2651 }
2652
2653 if (old_remote_description) {
2654 for (const cricket::ContentInfo& content :
2655 old_remote_description->description()->contents()) {
2656 // Check if this new SessionDescription contains new ICE ufrag and
2657 // password that indicates the remote peer requests an ICE restart.
2658 // TODO(deadbeef): When we start storing both the current and pending
2659 // remote description, this should reset pending_ice_restarts and compare
2660 // against the current description.
2661 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2662 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002663 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002664 pending_ice_restarts_.insert(content.name);
2665 }
2666 } else {
2667 // We retain all received candidates only if ICE is not restarted.
2668 // When ICE is restarted, all previous candidates belong to an old
2669 // generation and should not be kept.
2670 // TODO(deadbeef): This goes against the W3C spec which says the remote
2671 // description should only contain candidates from the last set remote
2672 // description plus any candidates added since then. We should remove
2673 // this once we're sure it won't break anything.
2674 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2675 old_remote_description, content.name, mutable_remote_description());
2676 }
2677 }
2678 }
2679
2680 if (session_error() != SessionError::kNone) {
2681 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2682 }
2683
2684 // Set the the ICE connection state to connecting since the connection may
2685 // become writable with peer reflexive candidates before any remote candidate
2686 // is signaled.
2687 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2688 // is to have a new signal the indicates a change in checking state from the
2689 // transport and expose a new checking() member from transport that can be
2690 // read to determine the current checking state. The existing SignalConnecting
2691 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002692 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002693 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002694 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2695 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2696 }
2697
deadbeefab9b2d12015-10-14 11:33:11 -07002698 // If setting the description decided our SSL role, allocate any necessary
2699 // SCTP sids.
2700 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002701 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002702 AllocateSctpSids(role);
2703 }
2704
Steve Antondcc3c022017-12-22 16:02:54 -08002705 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002706 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002707 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002708 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002709 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002710 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002711 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002712 const ContentInfo* content =
2713 FindMediaSectionForTransceiver(transceiver, remote_description());
2714 if (!content) {
2715 continue;
2716 }
2717 const MediaContentDescription* media_desc = content->media_description();
2718 RtpTransceiverDirection local_direction =
2719 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002720 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2721 // RTCSessionDescription: Set the associated remote streams given
2722 // transceiver.[[Receiver]], msids, addList, and removeList".
2723 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2724 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2725 std::vector<std::string> stream_ids;
2726 if (!media_desc->streams().empty()) {
2727 // The remote description has signaled the stream IDs.
2728 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002729 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002730 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2731 << " (" << GetStreamIdsString(stream_ids) << ").";
2732 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2733 stream_ids, &added_streams,
2734 &removed_streams);
2735 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2736 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2737 // and transceiver's current direction is neither sendrecv nor recvonly,
2738 // process the addition of a remote track for the media description.
2739 if (!transceiver->fired_direction() ||
2740 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2741 RTC_LOG(LS_INFO)
2742 << "Processing the addition of a remote track for MID="
2743 << content->name << ".";
2744 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002745 }
Steve Antondcc3c022017-12-22 16:02:54 -08002746 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002747 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002748 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2749 // removal of a remote track for the media description, given transceiver,
2750 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002751 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002752 (transceiver->fired_direction() &&
2753 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2754 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2755 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002756 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002757 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002758 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002759 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002760 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002761 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002762 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002763 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002764 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002765 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2766 if (transceiver->mid()) {
2767 auto dtls_transport =
2768 LookupDtlsTransportByMidInternal(*transceiver->mid());
2769 transceiver->internal()->sender_internal()->set_transport(
2770 dtls_transport);
2771 transceiver->internal()->receiver_internal()->set_transport(
2772 dtls_transport);
2773 }
Steve Antondcc3c022017-12-22 16:02:54 -08002774 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002775 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002776 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002777 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002778 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2779 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002780 transceiver->Stop();
2781 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002782 if (!content->rejected &&
2783 RtpTransceiverDirectionHasRecv(local_direction)) {
2784 // Set ssrc to 0 in the case of an unsignalled ssrc.
2785 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002786 if (!media_desc->streams().empty() &&
2787 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002788 ssrc = media_desc->streams()[0].first_ssrc();
2789 }
2790 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002791 }
Steve Antondcc3c022017-12-22 16:02:54 -08002792 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002793 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002794 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002795 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002796 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002797 observer->OnTrack(transceiver);
2798 observer->OnAddTrack(transceiver->receiver(),
2799 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002800 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002801 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002802 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002803 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002804 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002805 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002806 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002807 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002808 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002809 }
Steve Antondcc3c022017-12-22 16:02:54 -08002810 }
2811
Henrik Boströmfdb92012017-11-09 19:55:44 +01002812 const cricket::ContentInfo* audio_content =
2813 GetFirstAudioContent(remote_description()->description());
2814 const cricket::ContentInfo* video_content =
2815 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002816 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002817 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002818 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002819 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002820 const cricket::RtpDataContentDescription* rtp_data_desc =
2821 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002822
2823 // Check if the descriptions include streams, just in case the peer supports
2824 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002825 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002826 (audio_desc && !audio_desc->streams().empty()) ||
2827 (video_desc && !video_desc->streams().empty())) {
2828 remote_peer_supports_msid_ = true;
2829 }
deadbeefab9b2d12015-10-14 11:33:11 -07002830
2831 // We wait to signal new streams until we finish processing the description,
2832 // since only at that point will new streams have all their tracks.
2833 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2834
Steve Antondcc3c022017-12-22 16:02:54 -08002835 if (!IsUnifiedPlan()) {
2836 // TODO(steveanton): When removing RTP senders/receivers in response to a
2837 // rejected media section, there is some cleanup logic that expects the
2838 // voice/ video channel to still be set. But in this method the voice/video
2839 // channel would have been destroyed by the SetRemoteDescription caller
2840 // above so the cleanup that relies on them fails to run. The RemoveSenders
2841 // calls should be moved to right before the DestroyChannel calls to fix
2842 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002843
Steve Antondcc3c022017-12-22 16:02:54 -08002844 // Find all audio rtp streams and create corresponding remote AudioTracks
2845 // and MediaStreams.
2846 if (audio_content) {
2847 if (audio_content->rejected) {
2848 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2849 } else {
2850 bool default_audio_track_needed =
2851 !remote_peer_supports_msid_ &&
2852 RtpTransceiverDirectionHasSend(audio_desc->direction());
2853 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2854 default_audio_track_needed, audio_desc->type(),
2855 new_streams);
2856 }
deadbeeffaac4972015-11-12 15:33:07 -08002857 }
deadbeefab9b2d12015-10-14 11:33:11 -07002858
Steve Antondcc3c022017-12-22 16:02:54 -08002859 // Find all video rtp streams and create corresponding remote VideoTracks
2860 // and MediaStreams.
2861 if (video_content) {
2862 if (video_content->rejected) {
2863 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2864 } else {
2865 bool default_video_track_needed =
2866 !remote_peer_supports_msid_ &&
2867 RtpTransceiverDirectionHasSend(video_desc->direction());
2868 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2869 default_video_track_needed, video_desc->type(),
2870 new_streams);
2871 }
deadbeeffaac4972015-11-12 15:33:07 -08002872 }
deadbeefab9b2d12015-10-14 11:33:11 -07002873
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002874 // If this is an RTP data transport, update the DataChannels with the
2875 // information from the remote peer.
2876 if (rtp_data_desc) {
2877 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002878 }
deadbeefab9b2d12015-10-14 11:33:11 -07002879
Steve Antondcc3c022017-12-22 16:02:54 -08002880 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002881 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002882 for (size_t i = 0; i < new_streams->count(); ++i) {
2883 MediaStreamInterface* new_stream = new_streams->at(i);
2884 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002885 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002886 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2887 }
deadbeefab9b2d12015-10-14 11:33:11 -07002888
Steve Antondcc3c022017-12-22 16:02:54 -08002889 UpdateEndedRemoteMediaStreams();
2890 }
deadbeefab9b2d12015-10-14 11:33:11 -07002891
Steve Anton8a006912017-12-04 15:25:56 -08002892 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002893}
2894
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002895void PeerConnection::SetAssociatedRemoteStreams(
2896 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2897 const std::vector<std::string>& stream_ids,
2898 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2899 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2900 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2901 for (const std::string& stream_id : stream_ids) {
2902 rtc::scoped_refptr<MediaStreamInterface> stream =
2903 remote_streams_->find(stream_id);
2904 if (!stream) {
2905 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2906 MediaStream::Create(stream_id));
2907 remote_streams_->AddStream(stream);
2908 added_streams->push_back(stream);
2909 }
2910 media_streams.push_back(stream);
2911 }
2912 // Special case: "a=msid" missing, use random stream ID.
2913 if (media_streams.empty() &&
2914 !(remote_description()->description()->msid_signaling() &
2915 cricket::kMsidSignalingMediaSection)) {
2916 if (!missing_msid_default_stream_) {
2917 missing_msid_default_stream_ = MediaStreamProxy::Create(
2918 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2919 added_streams->push_back(missing_msid_default_stream_);
2920 }
2921 media_streams.push_back(missing_msid_default_stream_);
2922 }
2923 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2924 receiver->streams();
2925 // SetStreams() will add/remove the receiver's track to/from the streams. This
2926 // differs from the spec - the spec uses an "addList" and "removeList" to
2927 // update the stream-track relationships in a later step. We do this earlier,
2928 // changing the order of things, but the end-result is the same.
2929 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2930 // instead. https://crbug.com/webrtc/9480
2931 receiver->SetStreams(media_streams);
2932 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2933}
2934
Steve Anton0f5400a2018-07-17 14:25:36 -07002935void PeerConnection::ProcessRemovalOfRemoteTrack(
2936 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2937 transceiver,
2938 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2939 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2940 RTC_DCHECK(transceiver->mid());
2941 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2942 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002943 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002944 transceiver->internal()->receiver_internal()->streams();
2945 // This will remove the remote track from the streams.
2946 transceiver->internal()->receiver_internal()->set_stream_ids({});
2947 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002948 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2949}
2950
2951void PeerConnection::RemoveRemoteStreamsIfEmpty(
2952 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2953 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2954 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2955 // streams, see if the stream was removed by checking if this was the last
2956 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002957 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002958 if (remote_stream->GetAudioTracks().empty() &&
2959 remote_stream->GetVideoTracks().empty()) {
2960 remote_streams_->RemoveStream(remote_stream);
2961 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002962 }
2963 }
2964}
2965
Steve Antondcc3c022017-12-22 16:02:54 -08002966RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2967 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002968 const SessionDescriptionInterface& new_session,
2969 const SessionDescriptionInterface* old_local_description,
2970 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002971 RTC_DCHECK(IsUnifiedPlan());
2972
Steve Anton7464fca2018-01-19 11:10:37 -08002973 const cricket::ContentGroup* bundle_group = nullptr;
2974 if (new_session.GetType() == SdpType::kOffer) {
2975 auto bundle_group_or_error =
2976 GetEarlyBundleGroup(*new_session.description());
2977 if (!bundle_group_or_error.ok()) {
2978 return bundle_group_or_error.MoveError();
2979 }
2980 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002981 }
Steve Antondcc3c022017-12-22 16:02:54 -08002982
Steve Antondcc3c022017-12-22 16:02:54 -08002983 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002984 for (size_t i = 0; i < new_contents.size(); ++i) {
2985 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002986 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002987 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002988 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2989 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002990 const cricket::ContentInfo* old_local_content = nullptr;
2991 if (old_local_description &&
2992 i < old_local_description->description()->contents().size()) {
2993 old_local_content =
2994 &old_local_description->description()->contents()[i];
2995 }
2996 const cricket::ContentInfo* old_remote_content = nullptr;
2997 if (old_remote_description &&
2998 i < old_remote_description->description()->contents().size()) {
2999 old_remote_content =
3000 &old_remote_description->description()->contents()[i];
3001 }
Steve Antondcc3c022017-12-22 16:02:54 -08003002 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003003 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3004 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003005 if (!transceiver_or_error.ok()) {
3006 return transceiver_or_error.MoveError();
3007 }
3008 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003009 RTCError error =
3010 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3011 if (!error.ok()) {
3012 return error;
3013 }
3014 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003015 if (GetDataMid() && new_content.name != *GetDataMid()) {
3016 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003017 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3018 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003019 continue;
3020 }
3021 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3022 if (!error.ok()) {
3023 return error;
3024 }
Steve Antondcc3c022017-12-22 16:02:54 -08003025 } else {
3026 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3027 "Unknown section type.");
3028 }
3029 }
3030
3031 return RTCError::OK();
3032}
3033
3034RTCError PeerConnection::UpdateTransceiverChannel(
3035 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3036 transceiver,
3037 const cricket::ContentInfo& content,
3038 const cricket::ContentGroup* bundle_group) {
3039 RTC_DCHECK(IsUnifiedPlan());
3040 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003041 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003042 if (content.rejected) {
3043 if (channel) {
3044 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003045 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003046 }
3047 } else {
3048 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003049 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003050 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003051 } else {
Steve Anton69470252018-02-09 11:43:08 -08003052 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003053 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003054 }
3055 if (!channel) {
3056 LOG_AND_RETURN_ERROR(
3057 RTCErrorType::INTERNAL_ERROR,
3058 "Failed to create channel for mid=" + content.name);
3059 }
3060 transceiver->internal()->SetChannel(channel);
3061 }
3062 }
3063 return RTCError::OK();
3064}
3065
Steve Antonfa2260d2017-12-28 16:38:23 -08003066RTCError PeerConnection::UpdateDataChannel(
3067 cricket::ContentSource source,
3068 const cricket::ContentInfo& content,
3069 const cricket::ContentGroup* bundle_group) {
3070 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003071 // If data channels are disabled, ignore this media section. CreateAnswer
3072 // will take care of rejecting it.
3073 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003074 }
3075 if (content.rejected) {
3076 DestroyDataChannel();
3077 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003078 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003079 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003080 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3081 "Failed to create data channel.");
3082 }
3083 }
3084 if (source == cricket::CS_REMOTE) {
3085 const MediaContentDescription* data_desc = content.media_description();
3086 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3087 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3088 }
3089 }
3090 }
3091 return RTCError::OK();
3092}
3093
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003094// This method will extract any send encodings that were sent by the remote
3095// connection. This is currently only relevant for Simulcast scenario (where
3096// the number of layers may be communicated by the server).
3097static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3098 const MediaContentDescription& desc) {
3099 if (!desc.HasSimulcast()) {
3100 return {};
3101 }
3102 std::vector<RtpEncodingParameters> result;
3103 const SimulcastDescription& simulcast = desc.simulcast_description();
3104
3105 // This is a remote description, the parameters we are after should appear
3106 // as receive streams.
3107 for (const auto& alternatives : simulcast.receive_layers()) {
3108 RTC_DCHECK(!alternatives.empty());
3109 // There is currently no way to specify or choose from alternatives.
3110 // We will always use the first alternative, which is the most preferred.
3111 const SimulcastLayer& layer = alternatives[0];
3112 RtpEncodingParameters parameters;
3113 parameters.rid = layer.rid;
3114 parameters.active = !layer.is_paused;
3115 result.push_back(parameters);
3116 }
3117
3118 return result;
3119}
3120
3121static RTCError UpdateSimulcastLayerStatusInSender(
3122 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003123 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003124 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003125 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003126 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003127
3128 // The simulcast envelope cannot be changed, only the status of the streams.
3129 // So we will iterate over the send encodings rather than the layers.
3130 for (RtpEncodingParameters& encoding : parameters.encodings) {
3131 auto iter = std::find_if(layers.begin(), layers.end(),
3132 [&encoding](const SimulcastLayer& layer) {
3133 return layer.rid == encoding.rid;
3134 });
3135 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003136 if (iter == layers.end()) {
3137 disabled_layers.push_back(encoding.rid);
3138 continue;
3139 }
3140
3141 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003142 }
3143
Amit Hilbuch619b2942019-02-26 15:55:19 -08003144 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003145 if (result.ok()) {
3146 result = sender->DisableEncodingLayers(disabled_layers);
3147 }
3148
3149 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003150}
3151
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003152static bool SimulcastIsRejected(
3153 const ContentInfo* local_content,
3154 const MediaContentDescription& answer_media_desc) {
3155 bool simulcast_offered = local_content &&
3156 local_content->media_description() &&
3157 local_content->media_description()->HasSimulcast();
3158 bool simulcast_answered = answer_media_desc.HasSimulcast();
3159 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3160 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3161 return simulcast_offered && (!simulcast_answered || !rids_supported);
3162}
3163
Amit Hilbuch2297d332019-02-19 12:49:22 -08003164static RTCError DisableSimulcastInSender(
3165 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003166 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003167 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003168 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003169 return RTCError::OK();
3170 }
3171
Amit Hilbuch2297d332019-02-19 12:49:22 -08003172 std::vector<std::string> disabled_layers;
3173 std::transform(
3174 parameters.encodings.begin() + 1, parameters.encodings.end(),
3175 std::back_inserter(disabled_layers),
3176 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3177 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003178}
3179
Steve Antondcc3c022017-12-22 16:02:54 -08003180RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3181PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003182 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003183 size_t mline_index,
3184 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003185 const ContentInfo* old_local_content,
3186 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003187 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003188 // If this is an offer then the m= section might be recycled. If the m=
3189 // section is being recycled (defined as: rejected in the current local or
3190 // remote description and not rejected in new description), dissociate the
3191 // currently associated RtpTransceiver by setting its mid property to null,
3192 // and discard the mapping between the transceiver and its m= section index.
3193 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3194 old_remote_content)) {
3195 // We want to dissociate the transceiver that has the rejected mid.
3196 const std::string& old_mid =
3197 (old_local_content && old_local_content->rejected)
3198 ? old_local_content->name
3199 : old_remote_content->name;
3200 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003201 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003202 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3203 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003204 old_transceiver->internal()->set_mid(absl::nullopt);
3205 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003206 }
3207 }
3208 const MediaContentDescription* media_desc = content.media_description();
3209 auto transceiver = GetAssociatedTransceiver(content.name);
3210 if (source == cricket::CS_LOCAL) {
3211 // Find the RtpTransceiver that corresponds to this m= section, using the
3212 // mapping between transceivers and m= section indices established when
3213 // creating the offer.
3214 if (!transceiver) {
3215 transceiver = GetTransceiverByMLineIndex(mline_index);
3216 }
3217 if (!transceiver) {
3218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3219 "Unknown transceiver");
3220 }
3221 } else {
3222 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3223 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3224 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003225 // When simulcast is requested, a transceiver cannot be associated because
3226 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003227 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003228 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3229 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003230 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3231 }
3232 // If no RtpTransceiver was found in the previous step, create one with a
3233 // recvonly direction.
3234 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003235 RTC_LOG(LS_INFO) << "Adding "
3236 << cricket::MediaTypeToString(media_desc->type())
3237 << " transceiver for MID=" << content.name
3238 << " at i=" << mline_index
3239 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003240 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003241 std::vector<RtpEncodingParameters> send_encodings =
3242 GetSendEncodingsFromRemoteDescription(*media_desc);
3243 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3244 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003245 std::string receiver_id;
3246 if (!media_desc->streams().empty()) {
3247 receiver_id = media_desc->streams()[0].id;
3248 } else {
3249 receiver_id = rtc::CreateRandomUuid();
3250 }
3251 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003252 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003253 transceiver->internal()->set_direction(
3254 RtpTransceiverDirection::kRecvOnly);
3255 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003256
3257 // Check if the offer indicated simulcast but the answer rejected it.
3258 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003259 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003260 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003261 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003262 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003263 if (!error.ok()) {
3264 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3265 return std::move(error);
3266 }
3267 }
Steve Antondcc3c022017-12-22 16:02:54 -08003268 }
3269 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003270 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003271 LOG_AND_RETURN_ERROR(
3272 RTCErrorType::INVALID_PARAMETER,
3273 "Transceiver type does not match media description type.");
3274 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003275 if (media_desc->HasSimulcast()) {
3276 std::vector<SimulcastLayer> layers =
3277 source == cricket::CS_LOCAL
3278 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3279 : media_desc->simulcast_description()
3280 .receive_layers()
3281 .GetAllLayers();
3282 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003283 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003284 if (!error.ok()) {
3285 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3286 return std::move(error);
3287 }
3288 }
Steve Antondcc3c022017-12-22 16:02:54 -08003289 // Associate the found or created RtpTransceiver with the m= section by
3290 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3291 // section, and establish a mapping between the transceiver and the index of
3292 // the m= section.
3293 transceiver->internal()->set_mid(content.name);
3294 transceiver->internal()->set_mline_index(mline_index);
3295 return std::move(transceiver);
3296}
3297
3298rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3299PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3300 RTC_DCHECK(IsUnifiedPlan());
3301 for (auto transceiver : transceivers_) {
3302 if (transceiver->mid() == mid) {
3303 return transceiver;
3304 }
3305 }
3306 return nullptr;
3307}
3308
3309rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3310PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3311 RTC_DCHECK(IsUnifiedPlan());
3312 for (auto transceiver : transceivers_) {
3313 if (transceiver->internal()->mline_index() == mline_index) {
3314 return transceiver;
3315 }
3316 }
3317 return nullptr;
3318}
3319
3320rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3321PeerConnection::FindAvailableTransceiverToReceive(
3322 cricket::MediaType media_type) const {
3323 RTC_DCHECK(IsUnifiedPlan());
3324 // From JSEP section 5.10 (Applying a Remote Description):
3325 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3326 // the same type that were added to the PeerConnection by addTrack and are not
3327 // associated with any m= section and are not stopped, find the first such
3328 // RtpTransceiver.
3329 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003330 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003331 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3332 !transceiver->stopped()) {
3333 return transceiver;
3334 }
3335 }
3336 return nullptr;
3337}
3338
Steve Antoned10bd92017-12-05 10:52:59 -08003339const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3340 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3341 transceiver,
3342 const SessionDescriptionInterface* sdesc) const {
3343 RTC_DCHECK(transceiver);
3344 RTC_DCHECK(sdesc);
3345 if (IsUnifiedPlan()) {
3346 if (!transceiver->internal()->mid()) {
3347 // This transceiver is not associated with a media section yet.
3348 return nullptr;
3349 }
3350 return sdesc->description()->GetContentByName(
3351 *transceiver->internal()->mid());
3352 } else {
3353 // Plan B only allows at most one audio and one video section, so use the
3354 // first media section of that type.
3355 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003356 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003357 }
3358}
3359
deadbeef46c73892016-11-16 19:42:04 -08003360PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003361 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003362 return configuration_;
3363}
3364
deadbeef293e9262017-01-11 12:28:30 -08003365bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3366 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003367 RTC_DCHECK_RUN_ON(signaling_thread());
3368 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003369 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003370 if (IsClosed()) {
3371 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3372 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3373 }
3374
Qingsi Wanga2d60672018-04-11 16:57:45 -07003375 // According to JSEP, after setLocalDescription, changing the candidate pool
3376 // size is not allowed, and changing the set of ICE servers will not result
3377 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003378 if (local_description() && configuration.ice_candidate_pool_size !=
3379 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003380 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3381 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003382 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003383 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003384
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003385 if (local_description() &&
3386 configuration.use_media_transport != configuration_.use_media_transport) {
3387 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3388 "SetLocalDescription.";
3389 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3390 }
3391
3392 if (remote_description() &&
3393 configuration.use_media_transport != configuration_.use_media_transport) {
3394 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3395 "SetRemoteDescription.";
3396 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3397 }
3398
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003399 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003400 configuration.use_media_transport_for_data_channels !=
3401 configuration_.use_media_transport_for_data_channels) {
3402 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3403 "after calling SetLocalDescription.";
3404 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3405 }
3406
3407 if (remote_description() &&
3408 configuration.use_media_transport_for_data_channels !=
3409 configuration_.use_media_transport_for_data_channels) {
3410 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3411 "after calling SetRemoteDescription.";
3412 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3413 }
3414
3415 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003416 configuration.crypto_options != configuration_.crypto_options) {
3417 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3418 "SetLocalDescription.";
3419 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3420 }
3421
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003422 if (local_description() && configuration.use_datagram_transport !=
3423 configuration_.use_datagram_transport) {
3424 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3425 "after calling SetLocalDescription.";
3426 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3427 }
3428
3429 if (remote_description() && configuration.use_datagram_transport !=
3430 configuration_.use_datagram_transport) {
3431 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3432 "after calling SetRemoteDescription.";
3433 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3434 }
3435
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003436 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003437 configuration.use_media_transport ||
3438 configuration.use_datagram_transport) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003439 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3440 << "Media transport requires MaxBundle policy.";
3441 }
3442
deadbeef293e9262017-01-11 12:28:30 -08003443 // The simplest (and most future-compatible) way to tell if the config was
3444 // modified in an invalid way is to copy each property we do support
3445 // modifying, then use operator==. There are far more properties we don't
3446 // support modifying than those we do, and more could be added.
3447 RTCConfiguration modified_config = configuration_;
3448 modified_config.servers = configuration.servers;
3449 modified_config.type = configuration.type;
3450 modified_config.ice_candidate_pool_size =
3451 configuration.ice_candidate_pool_size;
3452 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003453 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003454 modified_config.ice_check_interval_strong_connectivity =
3455 configuration.ice_check_interval_strong_connectivity;
3456 modified_config.ice_check_interval_weak_connectivity =
3457 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003458 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3459 modified_config.ice_unwritable_min_checks =
3460 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003461 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003462 modified_config.stun_candidate_keepalive_interval =
3463 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003464 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003465 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003466 modified_config.active_reset_srtp_params =
3467 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003468 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003469 modified_config.use_media_transport_for_data_channels =
3470 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003471 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003472 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003473 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3474 }
3475
Steve Anton038834f2017-07-14 15:59:59 -07003476 // Validate the modified configuration.
3477 RTCError validate_error = ValidateConfiguration(modified_config);
3478 if (!validate_error.ok()) {
3479 return SafeSetError(std::move(validate_error), error);
3480 }
3481
deadbeef293e9262017-01-11 12:28:30 -08003482 // Note that this isn't possible through chromium, since it's an unsigned
3483 // short in WebIDL.
3484 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003485 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003486 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3487 }
3488
3489 // Parse ICE servers before hopping to network thread.
3490 cricket::ServerAddresses stun_servers;
3491 std::vector<cricket::RelayServerConfig> turn_servers;
3492 RTCErrorType parse_error =
3493 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3494 if (parse_error != RTCErrorType::NONE) {
3495 return SafeSetError(parse_error, error);
3496 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003497 // Note if STUN or TURN servers were supplied.
3498 if (!stun_servers.empty()) {
3499 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3500 }
3501 if (!turn_servers.empty()) {
3502 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3503 }
deadbeef293e9262017-01-11 12:28:30 -08003504
3505 // In theory this shouldn't fail.
3506 if (!network_thread()->Invoke<bool>(
3507 RTC_FROM_HERE,
3508 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3509 stun_servers, turn_servers, modified_config.type,
3510 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003511 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003512 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003513 modified_config.stun_candidate_keepalive_interval,
3514 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003515 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003516 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3517 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003518
deadbeefd1a38b52016-12-10 13:15:33 -08003519 // As described in JSEP, calling setConfiguration with new ICE servers or
3520 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3521 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003522 if (modified_config.servers != configuration_.servers ||
3523 modified_config.type != configuration_.type ||
3524 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003525 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003526 }
skvladd1f5fda2017-02-03 16:54:05 -08003527
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003528 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003529 transport_controller_->SetMediaTransportSettings(
3530 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003531 modified_config.use_media_transport_for_data_channels,
3532 modified_config.use_datagram_transport);
skvladd1f5fda2017-02-03 16:54:05 -08003533
Zhi Huangb57e1692018-06-12 11:41:11 -07003534 if (configuration_.active_reset_srtp_params !=
3535 modified_config.active_reset_srtp_params) {
3536 transport_controller_->SetActiveResetSrtpParams(
3537 modified_config.active_reset_srtp_params);
3538 }
3539
deadbeef293e9262017-01-11 12:28:30 -08003540 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003541 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003542 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003543}
3544
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003545bool PeerConnection::AddIceCandidate(
3546 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003547 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003548 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003549 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003550 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003551 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003552 return false;
3553 }
Steve Antond25da372017-11-06 14:50:29 -08003554
3555 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003556 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003557 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003558 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003559 return false;
3560 }
3561
3562 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003563 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003564 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003565 return false;
3566 }
3567
3568 bool valid = false;
3569 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3570 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003571 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003572 return false;
3573 }
3574
3575 // Add this candidate to the remote session description.
3576 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003577 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003578 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003579 return false;
3580 }
3581
3582 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003583 bool result = UseCandidate(ice_candidate);
3584 if (result) {
3585 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003586 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3587 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3588 }
3589 if (ice_candidate->candidate().address().IsPrivateIP()) {
3590 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3591 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003592 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3593 } else {
3594 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3595 }
3596 return result;
Steve Antond25da372017-11-06 14:50:29 -08003597 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003598 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003599 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003600 return true;
3601 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003602}
3603
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003604bool PeerConnection::RemoveIceCandidates(
3605 const std::vector<cricket::Candidate>& candidates) {
3606 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003607 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003608 if (IsClosed()) {
3609 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3610 return false;
3611 }
3612
Steve Antond25da372017-11-06 14:50:29 -08003613 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003614 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3615 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003616 return false;
3617 }
3618
3619 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003620 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003621 return false;
3622 }
3623
3624 size_t number_removed =
3625 mutable_remote_description()->RemoveCandidates(candidates);
3626 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003627 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003628 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003629 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003630 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003631 }
3632
3633 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003634 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3635 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003636 RTC_LOG(LS_ERROR)
3637 << "RemoveIceCandidates: Error when removing remote candidates: "
3638 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003639 }
3640 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003641}
3642
Niels Möller0c4f7be2018-05-07 14:01:37 +02003643RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003644 if (!worker_thread()->IsCurrent()) {
3645 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003646 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003647 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003648 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003649
Niels Möller0c4f7be2018-05-07 14:01:37 +02003650 const bool has_min = bitrate.min_bitrate_bps.has_value();
3651 const bool has_start = bitrate.start_bitrate_bps.has_value();
3652 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003653 if (has_min && *bitrate.min_bitrate_bps < 0) {
3654 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3655 "min_bitrate_bps <= 0");
3656 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003657 if (has_start) {
3658 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003659 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003660 "start_bitrate_bps < min_bitrate_bps");
3661 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003662 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3663 "curent_bitrate_bps < 0");
3664 }
3665 }
3666 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003667 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003668 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003669 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003670 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3671 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3672 "max_bitrate_bps < min_bitrate_bps");
3673 } else if (*bitrate.max_bitrate_bps < 0) {
3674 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3675 "max_bitrate_bps < 0");
3676 }
3677 }
3678
zstein4b979802017-06-02 14:37:37 -07003679 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003680 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003681
3682 return RTCError::OK();
3683}
3684
Alex Narest78609d52017-10-20 10:37:47 +02003685void PeerConnection::SetBitrateAllocationStrategy(
3686 std::unique_ptr<rtc::BitrateAllocationStrategy>
3687 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003688 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003689 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3690 // move-capture values in lambdas.
3691 struct Task {
3692 PeerConnection* const pc;
3693 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3694 void operator()() {
3695 RTC_DCHECK_RUN_ON(pc->worker_thread());
3696 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3697 }
3698 };
3699 worker_thread()->Invoke<void>(
3700 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003701 return;
3702 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003703 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003704 RTC_DCHECK(call_.get());
3705 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3706}
3707
henrika5f6bf242017-11-01 11:06:56 +01003708void PeerConnection::SetAudioPlayout(bool playout) {
3709 if (!worker_thread()->IsCurrent()) {
3710 worker_thread()->Invoke<void>(
3711 RTC_FROM_HERE,
3712 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3713 return;
3714 }
3715 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003716 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003717 audio_state->SetPlayout(playout);
3718}
3719
3720void PeerConnection::SetAudioRecording(bool recording) {
3721 if (!worker_thread()->IsCurrent()) {
3722 worker_thread()->Invoke<void>(
3723 RTC_FROM_HERE,
3724 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3725 return;
3726 }
3727 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003728 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003729 audio_state->SetRecording(recording);
3730}
3731
Steve Anton8c0f7a72017-10-03 10:03:10 -07003732std::unique_ptr<rtc::SSLCertificate>
3733PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003734 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3735 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003736 return nullptr;
3737 }
Steve Antonf25303e2018-10-16 15:23:31 -07003738 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003739}
3740
Zhi Huang70b820f2018-01-27 14:16:15 -08003741std::unique_ptr<rtc::SSLCertChain>
3742PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003743 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003744 auto audio_transceiver = GetFirstAudioTransceiver();
3745 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003746 return nullptr;
3747 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003748 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003749 audio_transceiver->internal()->channel()->transport_name());
3750}
3751
3752rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3753PeerConnection::GetFirstAudioTransceiver() const {
3754 for (auto transceiver : transceivers_) {
3755 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3756 return transceiver;
3757 }
3758 }
3759 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003760}
3761
Bjorn Tereliusde939432017-11-20 17:38:14 +01003762bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3763 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003764 // TODO(eladalon): In C++14, this can be done with a lambda.
3765 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003766 bool operator()() {
3767 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3768 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003769 PeerConnection* const pc;
3770 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003771 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003772 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003773 return worker_thread()->Invoke<bool>(
3774 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003775}
3776
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003777bool PeerConnection::StartRtcEventLog(
3778 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003779 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3780 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3781 output_period_ms = 5000;
3782 }
3783 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003784}
3785
ivoc14d5dbe2016-07-04 07:06:55 -07003786void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003787 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003788 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3789}
3790
Harald Alvestrandad88c882018-11-28 16:47:46 +01003791rtc::scoped_refptr<DtlsTransportInterface>
3792PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003793 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003794 return transport_controller_->LookupDtlsTransportByMid(mid);
3795}
3796
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003797rtc::scoped_refptr<DtlsTransport>
3798PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003799 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003800 return transport_controller_->LookupDtlsTransportByMid(mid);
3801}
3802
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003803rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3804 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003805 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003806 return sctp_transport_;
3807}
3808
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003809const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003810 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003811 return pending_local_description_ ? pending_local_description_.get()
3812 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003813}
3814
3815const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003816 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003817 return pending_remote_description_ ? pending_remote_description_.get()
3818 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003819}
3820
deadbeeffe4a8a42016-12-20 17:56:17 -08003821const SessionDescriptionInterface* PeerConnection::current_local_description()
3822 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003823 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003824 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003825}
3826
3827const SessionDescriptionInterface* PeerConnection::current_remote_description()
3828 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003829 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003830 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003831}
3832
3833const SessionDescriptionInterface* PeerConnection::pending_local_description()
3834 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003835 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003836 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003837}
3838
3839const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3840 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003841 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003842 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003843}
3844
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003845void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003846 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003847 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003848 // Update stats here so that we have the most recent stats for tracks and
3849 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003850 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003851
Steve Anton75737c02017-11-06 10:37:17 -08003852 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003853 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003854
Mirko Bonadei739baf02019-01-27 17:29:42 +01003855 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003856 transceiver->Stop();
3857 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003858
3859 // Ensure that all asynchronous stats requests are completed before destroying
3860 // the transport controller below.
3861 if (stats_collector_) {
3862 stats_collector_->WaitForPendingRequest();
3863 }
3864
3865 // Don't destroy BaseChannels until after stats has been cleaned up so that
3866 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003867 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003868
Qingsi Wang93a84392018-01-30 17:13:09 -08003869 // The event log is used in the transport controller, which must be outlived
3870 // by the former. CreateOffer by the peer connection is implemented
3871 // asynchronously and if the peer connection is closed without resetting the
3872 // WebRTC session description factory, the session description factory would
3873 // call the transport controller.
3874 webrtc_session_desc_factory_.reset();
3875 transport_controller_.reset();
3876
deadbeef42a42632017-03-10 15:18:00 -08003877 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003878 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3879 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003880
Steve Anton978b8762017-09-29 12:15:02 -07003881 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003882 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003883 call_.reset();
3884 // The event log must outlive call (and any other object that uses it).
3885 event_log_.reset();
3886 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003887 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003888 // The .h file says that observer can be discarded after close() returns.
3889 // Make sure this is true.
3890 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003891}
3892
Steve Antonad182762018-09-05 20:22:40 +00003893void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003894 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003895 switch (msg->message_id) {
3896 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3897 SetSessionDescriptionMsg* param =
3898 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3899 param->observer->OnSuccess();
3900 delete param;
3901 break;
3902 }
3903 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3904 SetSessionDescriptionMsg* param =
3905 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3906 param->observer->OnFailure(std::move(param->error));
3907 delete param;
3908 break;
3909 }
3910 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3911 CreateSessionDescriptionMsg* param =
3912 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3913 param->observer->OnFailure(std::move(param->error));
3914 delete param;
3915 break;
3916 }
3917 case MSG_GETSTATS: {
3918 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3919 StatsReports reports;
3920 stats_->GetStats(param->track, &reports);
3921 param->observer->OnComplete(reports);
3922 delete param;
3923 break;
3924 }
3925 case MSG_FREE_DATACHANNELS: {
3926 sctp_data_channels_to_free_.clear();
3927 break;
3928 }
3929 case MSG_REPORT_USAGE_PATTERN: {
3930 ReportUsagePattern();
3931 break;
3932 }
3933 default:
3934 RTC_NOTREACHED() << "Not implemented";
3935 break;
3936 }
3937}
3938
Steve Antonafb0bb72018-02-20 11:35:37 -08003939cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3940 RTC_DCHECK(!IsUnifiedPlan());
3941 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3942 GetAudioTransceiver()->internal()->channel());
3943 if (voice_channel) {
3944 return voice_channel->media_channel();
3945 } else {
3946 return nullptr;
3947 }
3948}
3949
3950cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3951 RTC_DCHECK(!IsUnifiedPlan());
3952 auto* video_channel = static_cast<cricket::VideoChannel*>(
3953 GetVideoTransceiver()->internal()->channel());
3954 if (video_channel) {
3955 return video_channel->media_channel();
3956 } else {
3957 return nullptr;
3958 }
3959}
3960
Steve Anton4171afb2017-11-20 10:20:22 -08003961void PeerConnection::CreateAudioReceiver(
3962 MediaStreamInterface* stream,
3963 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003964 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3965 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003966 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3967 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003968 auto* audio_receiver = new AudioRtpReceiver(
3969 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003970 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003971 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3972 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3973 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003974 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003975 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003976 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003977}
3978
Steve Anton4171afb2017-11-20 10:20:22 -08003979void PeerConnection::CreateVideoReceiver(
3980 MediaStreamInterface* stream,
3981 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003982 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3983 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003984 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3985 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003986 auto* video_receiver = new VideoRtpReceiver(
3987 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003988 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003989 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3990 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3991 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003992 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003993 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003994 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003995}
3996
deadbeef70ab1a12015-09-28 16:53:55 -07003997// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3998// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003999rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004000 const RtpSenderInfo& remote_sender_info) {
4001 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4002 if (!receiver) {
4003 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4004 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004005 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004006 }
Steve Anton4171afb2017-11-20 10:20:22 -08004007 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4008 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4009 } else {
4010 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4011 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004012 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004013}
4014
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004015void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4016 MediaStreamInterface* stream) {
4017 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004018 RTC_DCHECK(track);
4019 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004020 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004021 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004022 // We already have a sender for this track, so just change the stream_id
4023 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004024 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004025 return;
4026 }
4027
4028 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004029 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004030 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004031 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004032 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004033 // If the sender has already been configured in SDP, we call SetSsrc,
4034 // which will connect the sender to the underlying transport. This can
4035 // occur if a local session description that contains the ID of the sender
4036 // is set before AddStream is called. It can also occur if the local
4037 // session description is not changed and RemoveStream is called, and
4038 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004039 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004040 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004041 if (sender_info) {
4042 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004043 }
4044}
4045
4046// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4047// indefinitely, when we have unified plan SDP.
4048void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4049 MediaStreamInterface* stream) {
4050 RTC_DCHECK(!IsClosed());
4051 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004052 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004053 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4054 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004055 return;
4056 }
Steve Anton4171afb2017-11-20 10:20:22 -08004057 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004058}
4059
4060void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4061 MediaStreamInterface* stream) {
4062 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004063 RTC_DCHECK(track);
4064 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004065 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004066 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004067 // We already have a sender for this track, so just change the stream_id
4068 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004069 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004070 return;
4071 }
4072
4073 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004074 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004075 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004076 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004077 GetVideoTransceiver()->internal()->AddSender(new_sender);
4078 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004079 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004080 if (sender_info) {
4081 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004082 }
4083}
4084
4085void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4086 MediaStreamInterface* stream) {
4087 RTC_DCHECK(!IsClosed());
4088 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004089 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004090 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4091 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004092 return;
4093 }
Steve Anton4171afb2017-11-20 10:20:22 -08004094 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004095}
4096
Steve Antonba818672017-11-06 10:21:57 -08004097void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004098 if (ice_connection_state_ == new_state) {
4099 return;
4100 }
4101
deadbeefcbecd352015-09-23 11:50:27 -07004102 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004103 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004104 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004105 return;
4106 }
Steve Antonba818672017-11-06 10:21:57 -08004107
Mirko Bonadei675513b2017-11-09 11:09:25 +01004108 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4109 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004110 RTC_DCHECK(ice_connection_state_ !=
4111 PeerConnectionInterface::kIceConnectionClosed);
4112
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004113 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004114 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004115}
4116
Alex Loiko9289eda2018-11-23 16:18:59 +00004117void PeerConnection::SetStandardizedIceConnectionState(
4118 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004119 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004120 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004121 }
4122
4123 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004124 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004125 }
4126
4127 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4128 << standardized_ice_connection_state_ << " => " << new_state;
4129
Alex Loiko9289eda2018-11-23 16:18:59 +00004130 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004131 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004132}
4133
Jonas Olsson635474e2018-10-18 15:58:17 +02004134void PeerConnection::SetConnectionState(
4135 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004136 if (connection_state_ == new_state)
4137 return;
4138 if (IsClosed())
4139 return;
4140 connection_state_ = new_state;
4141 Observer()->OnConnectionChange(new_state);
4142}
4143
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004144void PeerConnection::OnIceGatheringChange(
4145 PeerConnectionInterface::IceGatheringState new_state) {
4146 if (IsClosed()) {
4147 return;
4148 }
4149 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004150 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004151}
4152
jbauch81bf7b02017-03-25 08:31:12 -07004153void PeerConnection::OnIceCandidate(
4154 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004155 if (IsClosed()) {
4156 return;
4157 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004158 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004159 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4160 candidate->candidate().address().IsPrivateIP()) {
4161 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4162 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004163 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4164 candidate->candidate().address().IsUnresolvedIP()) {
4165 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4166 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004167 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004168}
4169
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004170void PeerConnection::OnIceCandidatesRemoved(
4171 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004172 if (IsClosed()) {
4173 return;
4174 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004175 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004176}
4177
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004178void PeerConnection::ChangeSignalingState(
4179 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004180 if (signaling_state_ == signaling_state) {
4181 return;
4182 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004183 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4184 << GetSignalingStateString(signaling_state_)
4185 << " New state: "
4186 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004187 signaling_state_ = signaling_state;
4188 if (signaling_state == kClosed) {
4189 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004190 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004191 standardized_ice_connection_state_ =
4192 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004193 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4194 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004195 if (ice_gathering_state_ != kIceGatheringComplete) {
4196 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004197 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004198 }
4199 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004200 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004201}
4202
deadbeefeb459812015-12-15 19:24:43 -08004203void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4204 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004205 if (IsClosed()) {
4206 return;
4207 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004208 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004209 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004210}
4211
deadbeefeb459812015-12-15 19:24:43 -08004212void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4213 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004214 if (IsClosed()) {
4215 return;
4216 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004217 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004218 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004219}
4220
4221void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4222 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004223 if (IsClosed()) {
4224 return;
4225 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004226 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004227 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004228}
4229
4230void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4231 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004232 if (IsClosed()) {
4233 return;
4234 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004235 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004236 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004237}
4238
Henrik Boström31638672017-11-23 17:48:32 +01004239void PeerConnection::PostSetSessionDescriptionSuccess(
4240 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004241 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4242 signaling_thread()->Post(RTC_FROM_HERE, this,
4243 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004244}
4245
deadbeefab9b2d12015-10-14 11:33:11 -07004246void PeerConnection::PostSetSessionDescriptionFailure(
4247 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004248 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004249 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004250 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4251 msg->error = std::move(error);
4252 signaling_thread()->Post(RTC_FROM_HERE, this,
4253 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004254}
4255
4256void PeerConnection::PostCreateSessionDescriptionFailure(
4257 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004258 RTCError error) {
4259 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004260 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4261 msg->error = std::move(error);
4262 signaling_thread()->Post(RTC_FROM_HERE, this,
4263 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004264}
4265
zhihuang1c378ed2017-08-17 14:10:50 -07004266void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004267 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004268 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004269 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004270
Steve Antondcc3c022017-12-22 16:02:54 -08004271 if (IsUnifiedPlan()) {
4272 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4273 } else {
4274 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4275 }
4276
Steve Antonfa2260d2017-12-28 16:38:23 -08004277 // Intentionally unset the data channel type for RTP data channel with the
4278 // second condition. Otherwise the RTP data channels would be successfully
4279 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4280 // when building with chromium. We want to leave RTP data channels broken, so
4281 // people won't try to use them.
4282 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4283 session_options->data_channel_type = data_channel_type();
4284 }
4285
Steve Antondcc3c022017-12-22 16:02:54 -08004286 // Apply ICE restart flag and renomination flag.
4287 for (auto& options : session_options->media_description_options) {
4288 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4289 options.transport_options.enable_ice_renomination =
4290 configuration_.enable_ice_renomination;
4291 }
4292
4293 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004294 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004295 session_options->pooled_ice_credentials =
4296 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4297 RTC_FROM_HERE,
4298 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4299 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004300 session_options->offer_extmap_allow_mixed =
4301 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004302
4303 if (configuration_.enable_dtls_srtp &&
4304 !configuration_.enable_dtls_srtp.value()) {
4305 session_options->media_transport_settings =
4306 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4307 }
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004308 // Allow fallback for using obsolete SCTP syntax.
4309 // Note that the default in |session_options| is true, while
4310 // the default in |options| is false.
4311 session_options->use_obsolete_sctp_sdp =
4312 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004313}
4314
4315void PeerConnection::GetOptionsForPlanBOffer(
4316 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4317 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004318 // Figure out transceiver directional preferences.
4319 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4320 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4321
4322 // By default, generate sendrecv/recvonly m= sections.
4323 bool recv_audio = true;
4324 bool recv_video = true;
4325
4326 // By default, only offer a new m= section if we have media to send with it.
4327 bool offer_new_audio_description = send_audio;
4328 bool offer_new_video_description = send_video;
4329 bool offer_new_data_description = HasDataChannels();
4330
4331 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004332 if (offer_answer_options.offer_to_receive_audio !=
4333 RTCOfferAnswerOptions::kUndefined) {
4334 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004335 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004336 offer_new_audio_description ||
4337 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004338 }
Steve Antondcc3c022017-12-22 16:02:54 -08004339 if (offer_answer_options.offer_to_receive_video !=
4340 RTCOfferAnswerOptions::kUndefined) {
4341 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004342 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004343 offer_new_video_description ||
4344 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004345 }
4346
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004347 absl::optional<size_t> audio_index;
4348 absl::optional<size_t> video_index;
4349 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004350 // If a current description exists, generate m= sections in the same order,
4351 // using the first audio/video/data section that appears and rejecting
4352 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004353 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004354 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004355 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004356 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4357 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4358 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004359 }
4360
zhihuang1c378ed2017-08-17 14:10:50 -07004361 // Add audio/video/data m= sections to the end if needed.
4362 if (!audio_index && offer_new_audio_description) {
4363 session_options->media_description_options.push_back(
4364 cricket::MediaDescriptionOptions(
4365 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004366 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4367 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004368 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004369 }
zhihuang1c378ed2017-08-17 14:10:50 -07004370 if (!video_index && offer_new_video_description) {
4371 session_options->media_description_options.push_back(
4372 cricket::MediaDescriptionOptions(
4373 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004374 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4375 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004376 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004377 }
zhihuang1c378ed2017-08-17 14:10:50 -07004378 if (!data_index && offer_new_data_description) {
4379 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004380 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004381 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004382 }
4383
4384 cricket::MediaDescriptionOptions* audio_media_description_options =
4385 !audio_index ? nullptr
4386 : &session_options->media_description_options[*audio_index];
4387 cricket::MediaDescriptionOptions* video_media_description_options =
4388 !video_index ? nullptr
4389 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004390
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004391 AddPlanBRtpSenderOptions(GetSendersInternal(),
4392 audio_media_description_options,
4393 video_media_description_options,
4394 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004395}
4396
Steve Antondcc3c022017-12-22 16:02:54 -08004397static cricket::MediaDescriptionOptions
4398GetMediaDescriptionOptionsForTransceiver(
4399 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4400 transceiver,
4401 const std::string& mid) {
4402 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004403 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004404 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004405 media_description_options.codec_preferences =
4406 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004407 // This behavior is specified in JSEP. The gist is that:
4408 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4409 // sendrecv.
4410 // 2. If the MSID is included, then it must be included in any subsequent
4411 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004412 if (transceiver->stopped() ||
4413 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4414 !transceiver->internal()->has_ever_been_used_to_send())) {
4415 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004416 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004417
4418 cricket::SenderOptions sender_options;
4419 sender_options.track_id = transceiver->sender()->id();
4420 sender_options.stream_ids = transceiver->sender()->stream_ids();
4421
4422 // The following sets up RIDs and Simulcast.
4423 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004424 RtpParameters send_parameters =
4425 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004426 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4427 send_parameters.encodings.end(),
4428 [](const RtpEncodingParameters& encoding) {
4429 return !encoding.rid.empty();
4430 });
4431
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004432 std::vector<RidDescription> send_rids;
4433 SimulcastLayerList send_layers;
4434 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4435 if (encoding.rid.empty()) {
4436 continue;
4437 }
4438 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4439 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4440 }
4441
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004442 if (has_rids) {
4443 sender_options.rids = send_rids;
4444 }
4445
4446 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004447 // When RIDs are configured, we must set num_sim_layers to 0 to.
4448 // Otherwise, num_sim_layers must be 1 because either there is no
4449 // simulcast, or simulcast is acheived by munging the SDP.
4450 sender_options.num_sim_layers = has_rids ? 0 : 1;
4451 media_description_options.sender_options.push_back(sender_options);
4452
Steve Antondcc3c022017-12-22 16:02:54 -08004453 return media_description_options;
4454}
4455
Steve Anton5c72e712018-12-10 14:25:30 -08004456// Returns the ContentInfo at mline index |i|, or null if none exists.
4457static const ContentInfo* GetContentByIndex(
4458 const SessionDescriptionInterface* sdesc,
4459 size_t i) {
4460 if (!sdesc) {
4461 return nullptr;
4462 }
4463 const ContentInfos& contents = sdesc->description()->contents();
4464 return (i < contents.size() ? &contents[i] : nullptr);
4465}
4466
Steve Antondcc3c022017-12-22 16:02:54 -08004467void PeerConnection::GetOptionsForUnifiedPlanOffer(
4468 const RTCOfferAnswerOptions& offer_answer_options,
4469 cricket::MediaSessionOptions* session_options) {
4470 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4471 // Offers) and 5.2.2 (Subsequent Offers).
4472 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004473 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004474 const ContentInfos& local_contents =
4475 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004476 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004477 const ContentInfos& remote_contents =
4478 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004479 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004480 // The mline indices that can be recycled. New transceivers should reuse these
4481 // slots first.
4482 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004483 // First, go through each media section that exists in either the local or
4484 // remote description and generate a media section in this offer for the
4485 // associated transceiver. If a media section can be recycled, generate a
4486 // default, rejected media section here that can be later overwritten.
4487 for (size_t i = 0;
4488 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4489 // Either |local_content| or |remote_content| is non-null.
4490 const ContentInfo* local_content =
4491 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004492 const ContentInfo* current_local_content =
4493 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004494 const ContentInfo* remote_content =
4495 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004496 const ContentInfo* current_remote_content =
4497 GetContentByIndex(current_remote_description(), i);
4498 bool had_been_rejected =
4499 (current_local_content && current_local_content->rejected) ||
4500 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004501 const std::string& mid =
4502 (local_content ? local_content->name : remote_content->name);
4503 cricket::MediaType media_type =
4504 (local_content ? local_content->media_description()->type()
4505 : remote_content->media_description()->type());
4506 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4507 media_type == cricket::MEDIA_TYPE_VIDEO) {
4508 auto transceiver = GetAssociatedTransceiver(mid);
4509 RTC_CHECK(transceiver);
4510 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004511 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004512 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004513 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004514 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4515 RtpTransceiverDirection::kInactive,
4516 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004517 recycleable_mline_indices.push(i);
4518 } else {
4519 session_options->media_description_options.push_back(
4520 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4521 // CreateOffer shouldn't really cause any state changes in
4522 // PeerConnection, but we need a way to match new transceivers to new
4523 // media sections in SetLocalDescription and JSEP specifies this is done
4524 // by recording the index of the media section generated for the
4525 // transceiver in the offer.
4526 transceiver->internal()->set_mline_index(i);
4527 }
4528 } else {
4529 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004530 RTC_CHECK(GetDataMid());
4531 if (had_been_rejected || mid != *GetDataMid()) {
4532 session_options->media_description_options.push_back(
4533 GetMediaDescriptionOptionsForRejectedData(mid));
4534 } else {
4535 session_options->media_description_options.push_back(
4536 GetMediaDescriptionOptionsForActiveData(mid));
4537 }
Steve Antondcc3c022017-12-22 16:02:54 -08004538 }
4539 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004540
Steve Antondcc3c022017-12-22 16:02:54 -08004541 // Next, look for transceivers that are newly added (that is, are not stopped
4542 // and not associated). Reuse media sections marked as recyclable first,
4543 // otherwise append to the end of the offer. New media sections should be
4544 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004545 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004546 if (transceiver->mid() || transceiver->stopped()) {
4547 continue;
4548 }
4549 size_t mline_index;
4550 if (!recycleable_mline_indices.empty()) {
4551 mline_index = recycleable_mline_indices.front();
4552 recycleable_mline_indices.pop();
4553 session_options->media_description_options[mline_index] =
4554 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004555 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004556 } else {
4557 mline_index = session_options->media_description_options.size();
4558 session_options->media_description_options.push_back(
4559 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004560 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004561 }
4562 // See comment above for why CreateOffer changes the transceiver's state.
4563 transceiver->internal()->set_mline_index(mline_index);
4564 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004565 // Lastly, add a m-section if we have local data channels and an m section
4566 // does not already exist.
4567 if (!GetDataMid() && HasDataChannels()) {
4568 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004569 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004570 }
Steve Antondcc3c022017-12-22 16:02:54 -08004571}
4572
4573void PeerConnection::GetOptionsForAnswer(
4574 const RTCOfferAnswerOptions& offer_answer_options,
4575 cricket::MediaSessionOptions* session_options) {
4576 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4577
4578 if (IsUnifiedPlan()) {
4579 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4580 } else {
4581 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4582 }
4583
Steve Antonfa2260d2017-12-28 16:38:23 -08004584 // Intentionally unset the data channel type for RTP data channel. Otherwise
4585 // the RTP data channels would be successfully negotiated by default and the
4586 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4587 // We want to leave RTP data channels broken, so people won't try to use them.
4588 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4589 session_options->data_channel_type = data_channel_type();
4590 }
4591
Steve Antondcc3c022017-12-22 16:02:54 -08004592 // Apply ICE renomination flag.
4593 for (auto& options : session_options->media_description_options) {
4594 options.transport_options.enable_ice_renomination =
4595 configuration_.enable_ice_renomination;
4596 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004597
4598 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004599 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004600 session_options->pooled_ice_credentials =
4601 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4602 RTC_FROM_HERE,
4603 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4604 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004605}
4606
Steve Antondcc3c022017-12-22 16:02:54 -08004607void PeerConnection::GetOptionsForPlanBAnswer(
4608 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004609 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004610 // Figure out transceiver directional preferences.
4611 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4612 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4613
4614 // By default, generate sendrecv/recvonly m= sections. The direction is also
4615 // restricted by the direction in the offer.
4616 bool recv_audio = true;
4617 bool recv_video = true;
4618
4619 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004620 if (offer_answer_options.offer_to_receive_audio !=
4621 RTCOfferAnswerOptions::kUndefined) {
4622 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004623 }
Steve Antondcc3c022017-12-22 16:02:54 -08004624 if (offer_answer_options.offer_to_receive_video !=
4625 RTCOfferAnswerOptions::kUndefined) {
4626 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004627 }
4628
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004629 absl::optional<size_t> audio_index;
4630 absl::optional<size_t> video_index;
4631 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004632
4633 // Generate m= sections that match those in the offer.
4634 // Note that mediasession.cc will handle intersection our preferred
4635 // direction with the offered direction.
4636 GenerateMediaDescriptionOptions(
4637 remote_description(),
4638 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4639 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4640 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004641
4642 cricket::MediaDescriptionOptions* audio_media_description_options =
4643 !audio_index ? nullptr
4644 : &session_options->media_description_options[*audio_index];
4645 cricket::MediaDescriptionOptions* video_media_description_options =
4646 !video_index ? nullptr
4647 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004648
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004649 AddPlanBRtpSenderOptions(GetSendersInternal(),
4650 audio_media_description_options,
4651 video_media_description_options,
4652 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004653}
zhihuangaf388472016-11-02 16:49:48 -07004654
Steve Antondcc3c022017-12-22 16:02:54 -08004655void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4656 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4657 cricket::MediaSessionOptions* session_options) {
4658 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4659 // Answers) and 5.3.2 (Subsequent Answers).
4660 RTC_DCHECK(remote_description());
4661 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4662 for (const ContentInfo& content :
4663 remote_description()->description()->contents()) {
4664 cricket::MediaType media_type = content.media_description()->type();
4665 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4666 media_type == cricket::MEDIA_TYPE_VIDEO) {
4667 auto transceiver = GetAssociatedTransceiver(content.name);
4668 RTC_CHECK(transceiver);
4669 session_options->media_description_options.push_back(
4670 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4671 } else {
4672 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004673 // Reject all data sections if data channels are disabled.
4674 // Reject a data section if it has already been rejected.
4675 // Reject all data sections except for the first one.
4676 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4677 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004678 session_options->media_description_options.push_back(
4679 GetMediaDescriptionOptionsForRejectedData(content.name));
4680 } else {
4681 session_options->media_description_options.push_back(
4682 GetMediaDescriptionOptionsForActiveData(content.name));
4683 }
Steve Antondcc3c022017-12-22 16:02:54 -08004684 }
4685 }
htaa2a49d92016-03-04 02:51:39 -08004686}
4687
zhihuang1c378ed2017-08-17 14:10:50 -07004688void PeerConnection::GenerateMediaDescriptionOptions(
4689 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004690 RtpTransceiverDirection audio_direction,
4691 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004692 absl::optional<size_t>* audio_index,
4693 absl::optional<size_t>* video_index,
4694 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004695 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004696 for (const cricket::ContentInfo& content :
4697 session_desc->description()->contents()) {
4698 if (IsAudioContent(&content)) {
4699 // If we already have an audio m= section, reject this extra one.
4700 if (*audio_index) {
4701 session_options->media_description_options.push_back(
4702 cricket::MediaDescriptionOptions(
4703 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004704 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004705 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004706 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004707 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004708 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4709 content.name, audio_direction,
4710 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004711 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004712 }
4713 } else if (IsVideoContent(&content)) {
4714 // If we already have an video m= section, reject this extra one.
4715 if (*video_index) {
4716 session_options->media_description_options.push_back(
4717 cricket::MediaDescriptionOptions(
4718 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004719 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004720 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004721 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004722 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004723 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4724 content.name, video_direction,
4725 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004726 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004727 }
4728 } else {
4729 RTC_DCHECK(IsDataContent(&content));
4730 // If we already have an data m= section, reject this extra one.
4731 if (*data_index) {
4732 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004733 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004734 } else {
4735 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004736 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004737 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004738 }
4739 }
htaa2a49d92016-03-04 02:51:39 -08004740 }
deadbeefab9b2d12015-10-14 11:33:11 -07004741}
4742
Steve Antonfa2260d2017-12-28 16:38:23 -08004743cricket::MediaDescriptionOptions
4744PeerConnection::GetMediaDescriptionOptionsForActiveData(
4745 const std::string& mid) const {
4746 // Direction for data sections is meaningless, but legacy endpoints might
4747 // expect sendrecv.
4748 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4749 RtpTransceiverDirection::kSendRecv,
4750 /*stopped=*/false);
4751 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4752 return options;
4753}
4754
4755cricket::MediaDescriptionOptions
4756PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4757 const std::string& mid) const {
4758 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4759 RtpTransceiverDirection::kInactive,
4760 /*stopped=*/true);
4761 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4762 return options;
4763}
4764
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004765absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004766 switch (data_channel_type_) {
4767 case cricket::DCT_RTP:
4768 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004769 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004770 }
4771 return rtp_data_channel_->content_name();
4772 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004773 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004774 case cricket::DCT_MEDIA_TRANSPORT:
4775 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004776 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004777 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004778 }
4779}
4780
Steve Anton4171afb2017-11-20 10:20:22 -08004781void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4782 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4783 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004784 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004785}
4786
Steve Anton4171afb2017-11-20 10:20:22 -08004787void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004788 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004789 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004790 cricket::MediaType media_type,
4791 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004792 RTC_DCHECK(!IsUnifiedPlan());
4793
Steve Anton4171afb2017-11-20 10:20:22 -08004794 std::vector<RtpSenderInfo>* current_senders =
4795 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004796
Steve Anton4171afb2017-11-20 10:20:22 -08004797 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004798 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004799 for (auto sender_it = current_senders->begin();
4800 sender_it != current_senders->end();
4801 /* incremented manually */) {
4802 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004803 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004804 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004805 std::string params_stream_id;
4806 if (params) {
4807 params_stream_id =
4808 (!params->first_stream_id().empty() ? params->first_stream_id()
4809 : kDefaultStreamId);
4810 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004811 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004812 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004813 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004814 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004815 sender_exists) {
4816 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004817 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004818 OnRemoteSenderRemoved(info, media_type);
4819 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004820 }
4821 }
4822
Steve Anton4171afb2017-11-20 10:20:22 -08004823 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004824 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004825 if (!params.has_ssrcs()) {
4826 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4827 // sender, this means it is coming from a Unified Plan endpoint,so we just
4828 // create a default.
4829 default_sender_needed = true;
4830 break;
4831 }
4832
Seth Hampson845e8782018-03-02 11:34:10 -08004833 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004834 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004835 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4836 // not supported in Plan B, we just take the first here and create the
4837 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004838 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004839 (!params.first_stream_id().empty() ? params.first_stream_id()
4840 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004841 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004842 uint32_t ssrc = params.first_ssrc();
4843
4844 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004845 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004846 if (!stream) {
4847 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004848 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004849 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004850 remote_streams_->AddStream(stream);
4851 new_streams->AddStream(stream);
4852 }
4853
Steve Anton4171afb2017-11-20 10:20:22 -08004854 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004855 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004856 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004857 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004858 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004859 }
4860 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004861
Steve Anton4171afb2017-11-20 10:20:22 -08004862 // Add default sender if necessary.
4863 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004864 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004865 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004866 if (!default_stream) {
4867 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004868 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004869 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004870 remote_streams_->AddStream(default_stream);
4871 new_streams->AddStream(default_stream);
4872 }
Steve Anton4171afb2017-11-20 10:20:22 -08004873 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4874 ? kDefaultAudioSenderId
4875 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004876 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004877 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004878 if (!default_sender_info) {
4879 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004880 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004881 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004882 }
4883 }
deadbeefab9b2d12015-10-14 11:33:11 -07004884}
4885
Steve Anton4171afb2017-11-20 10:20:22 -08004886void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4887 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004888 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4889 << " receiver for track_id=" << sender_info.sender_id
4890 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004891
Steve Anton3d954a62018-04-02 11:27:23 -07004892 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004893 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004894 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004895 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004896 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004897 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004898 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004899 }
4900}
4901
Steve Anton4171afb2017-11-20 10:20:22 -08004902void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4903 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004904 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4905 << " receiver for track_id=" << sender_info.sender_id
4906 << " and stream_id=" << sender_info.stream_id;
4907
Seth Hampson845e8782018-03-02 11:34:10 -08004908 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004909
Henrik Boström933d8b02017-10-10 10:05:16 -07004910 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004911 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004912 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4913 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004914 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004915 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004916 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004917 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004918 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004919 }
4920 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004921 // Stopping or destroying a VideoRtpReceiver will end the
4922 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004923 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004924 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004925 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004926 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004927 // There's no guarantee the track is still available, e.g. the track may
4928 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004929 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004930 }
4931 } else {
nisseede5da42017-01-12 05:15:36 -08004932 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004933 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004934 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004935 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004936 }
deadbeefab9b2d12015-10-14 11:33:11 -07004937}
4938
4939void PeerConnection::UpdateEndedRemoteMediaStreams() {
4940 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4941 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4942 MediaStreamInterface* stream = remote_streams_->at(i);
4943 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4944 streams_to_remove.push_back(stream);
4945 }
4946 }
4947
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004948 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004949 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004950 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004951 }
4952}
4953
Steve Anton4171afb2017-11-20 10:20:22 -08004954void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004955 const std::vector<cricket::StreamParams>& streams,
4956 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004957 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004958
Seth Hampson845e8782018-03-02 11:34:10 -08004959 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004960 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004961 for (auto sender_it = current_senders->begin();
4962 sender_it != current_senders->end();
4963 /* incremented manually */) {
4964 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004965 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004966 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4967 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004968 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004969 OnLocalSenderRemoved(info, media_type);
4970 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004971 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004972 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004973 }
4974 }
4975
Steve Anton4171afb2017-11-20 10:20:22 -08004976 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004977 for (const cricket::StreamParams& params : streams) {
4978 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004979 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004980 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004981 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004982 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004983 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004984 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004985 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004986 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004987 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004988 }
4989 }
4990}
4991
Steve Anton4171afb2017-11-20 10:20:22 -08004992void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4993 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004994 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004995 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004996 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004997 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4998 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004999 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005000 return;
5001 }
5002
deadbeeffac06552015-11-25 11:26:01 -08005003 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005004 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005005 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005006 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005007 }
deadbeeffac06552015-11-25 11:26:01 -08005008
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005009 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005010 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005011}
5012
Steve Anton4171afb2017-11-20 10:20:22 -08005013void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5014 cricket::MediaType media_type) {
5015 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005016 if (!sender) {
5017 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005018 // SessionDescriptions has been renegotiated.
5019 return;
5020 }
deadbeeffac06552015-11-25 11:26:01 -08005021
5022 // A sender has been removed from the SessionDescription but it's still
5023 // associated with the PeerConnection. This only occurs if the SDP doesn't
5024 // match with the calls to CreateSender, AddStream and RemoveStream.
5025 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005026 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005027 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005028 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005029 }
deadbeeffac06552015-11-25 11:26:01 -08005030
Steve Anton4171afb2017-11-20 10:20:22 -08005031 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005032}
5033
5034void PeerConnection::UpdateLocalRtpDataChannels(
5035 const cricket::StreamParamsVec& streams) {
5036 std::vector<std::string> existing_channels;
5037
5038 // Find new and active data channels.
5039 for (const cricket::StreamParams& params : streams) {
5040 // |it->sync_label| is actually the data channel label. The reason is that
5041 // we use the same naming of data channels as we do for
5042 // MediaStreams and Tracks.
5043 // For MediaStreams, the sync_label is the MediaStream label and the
5044 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005045 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005046 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005047 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005048 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005049 continue;
5050 }
5051 // Set the SSRC the data channel should use for sending.
5052 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5053 existing_channels.push_back(data_channel_it->first);
5054 }
5055
5056 UpdateClosingRtpDataChannels(existing_channels, true);
5057}
5058
5059void PeerConnection::UpdateRemoteRtpDataChannels(
5060 const cricket::StreamParamsVec& streams) {
5061 std::vector<std::string> existing_channels;
5062
5063 // Find new and active data channels.
5064 for (const cricket::StreamParams& params : streams) {
5065 // The data channel label is either the mslabel or the SSRC if the mslabel
5066 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005067 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005068 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005069 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005070 auto data_channel_it = rtp_data_channels_.find(label);
5071 if (data_channel_it == rtp_data_channels_.end()) {
5072 // This is a new data channel.
5073 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5074 } else {
5075 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5076 }
5077 existing_channels.push_back(label);
5078 }
5079
5080 UpdateClosingRtpDataChannels(existing_channels, false);
5081}
5082
5083void PeerConnection::UpdateClosingRtpDataChannels(
5084 const std::vector<std::string>& active_channels,
5085 bool is_local_update) {
5086 auto it = rtp_data_channels_.begin();
5087 while (it != rtp_data_channels_.end()) {
5088 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005089 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005090 ++it;
5091 continue;
5092 }
5093
5094 if (is_local_update) {
5095 data_channel->SetSendSsrc(0);
5096 } else {
5097 data_channel->RemotePeerRequestClose();
5098 }
5099
5100 if (data_channel->state() == DataChannel::kClosed) {
5101 rtp_data_channels_.erase(it);
5102 it = rtp_data_channels_.begin();
5103 } else {
5104 ++it;
5105 }
5106 }
5107}
5108
5109void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5110 uint32_t remote_ssrc) {
5111 rtc::scoped_refptr<DataChannel> channel(
5112 InternalCreateDataChannel(label, nullptr));
5113 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005114 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005115 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005116 return;
5117 }
5118 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005119 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5120 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005121 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005122}
5123
5124rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5125 const std::string& label,
5126 const InternalDataChannelInit* config) {
5127 if (IsClosed()) {
5128 return nullptr;
5129 }
Steve Anton75737c02017-11-06 10:37:17 -08005130 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005132 << "InternalCreateDataChannel: Data is not supported in this call.";
5133 return nullptr;
5134 }
5135 InternalDataChannelInit new_config =
5136 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005137 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005138 if (new_config.id < 0) {
5139 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005140 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005141 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005142 RTC_LOG(LS_ERROR)
5143 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005144 return nullptr;
5145 }
5146 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005147 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005148 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005149 return nullptr;
5150 }
5151 }
5152
Steve Anton75737c02017-11-06 10:37:17 -08005153 rtc::scoped_refptr<DataChannel> channel(
5154 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005155 if (!channel) {
5156 sid_allocator_.ReleaseSid(new_config.id);
5157 return nullptr;
5158 }
5159
5160 if (channel->data_channel_type() == cricket::DCT_RTP) {
5161 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005162 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5163 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005164 return nullptr;
5165 }
5166 rtp_data_channels_[channel->label()] = channel;
5167 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005168 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005169 sctp_data_channels_.push_back(channel);
5170 channel->SignalClosed.connect(this,
5171 &PeerConnection::OnSctpDataChannelClosed);
5172 }
5173
Steve Anton2d8609c2018-01-23 16:38:46 -08005174 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005175 return channel;
5176}
5177
5178bool PeerConnection::HasDataChannels() const {
5179 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5180}
5181
5182void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005183 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005184 for (const auto& channel : sctp_data_channels_) {
5185 if (channel->id() < 0) {
5186 int sid;
5187 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005188 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5189 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005190 continue;
5191 }
5192 channel->SetSctpSid(sid);
5193 }
5194 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005195 // Since closing modifies the list of channels, we have to do the actual
5196 // closing outside the loop.
5197 for (const auto& channel : channels_to_close) {
5198 channel->CloseAbruptly();
5199 }
deadbeefab9b2d12015-10-14 11:33:11 -07005200}
5201
5202void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005203 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005204 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5205 ++it) {
5206 if (it->get() == channel) {
5207 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005208 // After the closing procedure is done, it's safe to use this ID for
5209 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005210 sid_allocator_.ReleaseSid(channel->id());
5211 }
deadbeefbd292462015-12-14 18:15:29 -08005212 // Since this method is triggered by a signal from the DataChannel,
5213 // we can't free it directly here; we need to free it asynchronously.
5214 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005215 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005216 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5217 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005218 return;
5219 }
5220 }
5221}
5222
deadbeefab9b2d12015-10-14 11:33:11 -07005223void PeerConnection::OnDataChannelDestroyed() {
5224 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5225 // DataChannel may callback to us and try to modify the list.
5226 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5227 temp_rtp_dcs.swap(rtp_data_channels_);
5228 for (const auto& kv : temp_rtp_dcs) {
5229 kv.second->OnTransportChannelDestroyed();
5230 }
5231
5232 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5233 temp_sctp_dcs.swap(sctp_data_channels_);
5234 for (const auto& channel : temp_sctp_dcs) {
5235 channel->OnTransportChannelDestroyed();
5236 }
5237}
5238
5239void PeerConnection::OnDataChannelOpenMessage(
5240 const std::string& label,
5241 const InternalDataChannelInit& config) {
5242 rtc::scoped_refptr<DataChannel> channel(
5243 InternalCreateDataChannel(label, &config));
5244 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005245 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005246 return;
5247 }
5248
deadbeefa601f5c2016-06-06 14:27:39 -07005249 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5250 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005251 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005252 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005253}
5254
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005255bool PeerConnection::HandleOpenMessage_s(
5256 const cricket::ReceiveDataParams& params,
5257 const rtc::CopyOnWriteBuffer& buffer) {
5258 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5259 // Received OPEN message; parse and signal that a new data channel should
5260 // be created.
5261 std::string label;
5262 InternalDataChannelInit config;
5263 config.id = params.ssrc;
5264 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5265 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5266 << params.ssrc;
5267 return true;
5268 }
5269 config.open_handshake_role = InternalDataChannelInit::kAcker;
5270 OnDataChannelOpenMessage(label, config);
5271 return true;
5272 }
5273 return false;
5274}
5275
Steve Anton4171afb2017-11-20 10:20:22 -08005276rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5277PeerConnection::GetAudioTransceiver() const {
5278 // This method only works with Plan B SDP, where there is a single
5279 // audio/video transceiver.
5280 RTC_DCHECK(!IsUnifiedPlan());
5281 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005282 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005283 return transceiver;
5284 }
5285 }
5286 RTC_NOTREACHED();
5287 return nullptr;
5288}
5289
5290rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5291PeerConnection::GetVideoTransceiver() const {
5292 // This method only works with Plan B SDP, where there is a single
5293 // audio/video transceiver.
5294 RTC_DCHECK(!IsUnifiedPlan());
5295 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005296 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005297 return transceiver;
5298 }
5299 }
5300 RTC_NOTREACHED();
5301 return nullptr;
5302}
5303
5304// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5305// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005306bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005307 switch (type) {
5308 case cricket::MEDIA_TYPE_AUDIO:
5309 return !GetAudioTransceiver()->internal()->senders().empty();
5310 case cricket::MEDIA_TYPE_VIDEO:
5311 return !GetVideoTransceiver()->internal()->senders().empty();
5312 case cricket::MEDIA_TYPE_DATA:
5313 return false;
5314 }
5315 RTC_NOTREACHED();
5316 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005317}
5318
Steve Anton4171afb2017-11-20 10:20:22 -08005319rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5320PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005321 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005322 for (auto sender : transceiver->internal()->senders()) {
5323 if (sender->track() == track) {
5324 return sender;
5325 }
5326 }
5327 }
5328 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005329}
5330
Steve Anton4171afb2017-11-20 10:20:22 -08005331rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5332PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005333 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005334 for (auto sender : transceiver->internal()->senders()) {
5335 if (sender->id() == sender_id) {
5336 return sender;
5337 }
5338 }
5339 }
5340 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005341}
5342
Steve Anton4171afb2017-11-20 10:20:22 -08005343rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5344PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005345 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005346 for (auto receiver : transceiver->internal()->receivers()) {
5347 if (receiver->id() == receiver_id) {
5348 return receiver;
5349 }
5350 }
5351 }
5352 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005353}
5354
Steve Anton4171afb2017-11-20 10:20:22 -08005355std::vector<PeerConnection::RtpSenderInfo>*
5356PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5357 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5358 media_type == cricket::MEDIA_TYPE_VIDEO);
5359 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5360 ? &remote_audio_sender_infos_
5361 : &remote_video_sender_infos_;
5362}
5363
5364std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005365 cricket::MediaType media_type) {
5366 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5367 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005368 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5369 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005370}
5371
Steve Anton4171afb2017-11-20 10:20:22 -08005372const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5373 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005374 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005375 const std::string sender_id) const {
5376 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005377 if (sender_info.stream_id == stream_id &&
5378 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005379 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005380 }
5381 }
5382 return nullptr;
5383}
5384
5385DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5386 for (const auto& channel : sctp_data_channels_) {
5387 if (channel->id() == sid) {
5388 return channel;
5389 }
5390 }
5391 return nullptr;
5392}
5393
Karl Wibergfb3be392019-03-22 14:13:22 +01005394PeerConnection::InitializePortAllocatorResult
5395PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005396 const cricket::ServerAddresses& stun_servers,
5397 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005398 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005399 RTC_DCHECK_RUN_ON(network_thread());
5400
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005401 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005402 // To handle both internal and externally created port allocator, we will
5403 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005404 int port_allocator_flags = port_allocator_->flags();
5405 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5406 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5407 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005408 // If the disable-IPv6 flag was specified, we'll not override it
5409 // by experiment.
5410 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005411 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005412 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5413 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005414 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005415 }
5416
zhihuangb09b3f92017-03-07 14:40:51 -08005417 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005418 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005419 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005420 }
5421
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005422 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005423 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005424 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005425 }
5426
honghaiz60347052016-05-31 18:29:12 -07005427 if (configuration.candidate_network_policy ==
5428 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005429 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005430 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005431 }
5432
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005433 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005434 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005435 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5436 }
5437
Karl Wibergfb3be392019-03-22 14:13:22 +01005438 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005439 // No step delay is used while allocating ports.
5440 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005441 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005442 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005443 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005444
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005445 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005446 for (auto& turn_server : turn_servers_copy) {
5447 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005448 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005449 // Call this last since it may create pooled allocator sessions using the
5450 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005451 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005452 stun_servers, std::move(turn_servers_copy),
5453 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5454 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005455 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005456
5457 InitializePortAllocatorResult res;
5458 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5459 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005460}
5461
deadbeef91dd5672016-05-18 16:55:30 -07005462bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005463 const cricket::ServerAddresses& stun_servers,
5464 const std::vector<cricket::RelayServerConfig>& turn_servers,
5465 IceTransportsType type,
5466 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005467 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005468 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005469 absl::optional<int> stun_candidate_keepalive_interval,
5470 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005471 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005472 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005473 // According to JSEP, after setLocalDescription, changing the candidate pool
5474 // size is not allowed, and changing the set of ICE servers will not result
5475 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005476 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005477 port_allocator_->FreezeCandidatePool();
5478 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005479 // Add the custom tls turn servers if they exist.
5480 auto turn_servers_copy = turn_servers;
5481 for (auto& turn_server : turn_servers_copy) {
5482 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5483 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005484 // Call this last since it may create pooled allocator sessions using the
5485 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005486 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005487 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5488 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005489}
5490
Steve Antonba818672017-11-06 10:21:57 -08005491cricket::ChannelManager* PeerConnection::channel_manager() const {
5492 return factory_->channel_manager();
5493}
5494
Elad Alon99c3fe52017-10-13 16:29:40 +02005495bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005496 std::unique_ptr<RtcEventLogOutput> output,
5497 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005498 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005499 if (!event_log_) {
5500 return false;
5501 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005502 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005503}
5504
5505void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005506 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005507 if (event_log_) {
5508 event_log_->StopLogging();
5509 }
ivoc14d5dbe2016-07-04 07:06:55 -07005510}
nisseeaabdf62017-05-05 02:23:02 -07005511
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005512cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005513 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005514 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005515 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005516 if (channel && channel->content_name() == content_name) {
5517 return channel;
5518 }
Steve Anton75737c02017-11-06 10:37:17 -08005519 }
5520 if (rtp_data_channel() &&
5521 rtp_data_channel()->content_name() == content_name) {
5522 return rtp_data_channel();
5523 }
5524 return nullptr;
5525}
5526
5527bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005528 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005529 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005530 RTC_LOG(LS_INFO)
5531 << "Local and Remote descriptions must be applied 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 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005535 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005536 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005537 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005538 return false;
5539 }
5540
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005541 absl::optional<rtc::SSLRole> dtls_role;
5542 if (sctp_mid_) {
5543 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5544 } else if (is_caller_) {
5545 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5546 }
Zhi Huange830e682018-03-30 10:48:35 -07005547 if (dtls_role) {
5548 *role = *dtls_role;
5549 return true;
5550 }
5551 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005552}
5553
5554bool PeerConnection::GetSslRole(const std::string& content_name,
5555 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005556 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005557 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005558 RTC_LOG(LS_INFO)
5559 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005560 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005561 return false;
5562 }
5563
Zhi Huange830e682018-03-30 10:48:35 -07005564 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5565 if (dtls_role) {
5566 *role = *dtls_role;
5567 return true;
5568 }
5569 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005570}
5571
Steve Antonf8470812017-12-04 10:46:21 -08005572void PeerConnection::SetSessionError(SessionError error,
5573 const std::string& error_desc) {
5574 RTC_DCHECK_RUN_ON(signaling_thread());
5575 if (error != session_error_) {
5576 session_error_ = error;
5577 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005578 }
5579}
5580
Zhi Huange830e682018-03-30 10:48:35 -07005581RTCError PeerConnection::UpdateSessionState(
5582 SdpType type,
5583 cricket::ContentSource source,
5584 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005585 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005586
5587 // If there's already a pending error then no state transition should happen.
5588 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005589 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005590
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005591 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005592 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005593 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005594 }
5595
5596 // Update the signaling state according to the specified state machine (see
5597 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005598 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005599 ChangeSignalingState(source == cricket::CS_LOCAL
5600 ? PeerConnectionInterface::kHaveLocalOffer
5601 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005602 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005603 ChangeSignalingState(source == cricket::CS_LOCAL
5604 ? PeerConnectionInterface::kHaveLocalPrAnswer
5605 : PeerConnectionInterface::kHaveRemotePrAnswer);
5606 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005607 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005608 ChangeSignalingState(PeerConnectionInterface::kStable);
5609 }
5610
5611 // Update internal objects according to the session description's media
5612 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005613 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005614 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005615 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005616 }
5617
Steve Anton8a006912017-12-04 15:25:56 -08005618 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005619}
5620
Steve Anton8a006912017-12-04 15:25:56 -08005621RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005622 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005623 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005624 const SessionDescriptionInterface* sdesc =
5625 (source == cricket::CS_LOCAL ? local_description()
5626 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005627 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005628
5629 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005630 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005631 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005632 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005633 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005634 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005635 continue;
5636 }
5637 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005638 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005639 if (!content_desc) {
5640 continue;
5641 }
5642 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005643 bool success = (source == cricket::CS_LOCAL)
5644 ? channel->SetLocalContent(content_desc, type, &error)
5645 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005646 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005648 }
5649 }
5650
5651 // If using the RtpDataChannel, push down the new SDP section for it too.
5652 if (rtp_data_channel_) {
5653 const ContentInfo* data_content =
5654 cricket::GetFirstDataContent(sdesc->description());
5655 if (data_content && !data_content->rejected) {
5656 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005657 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005658 if (data_desc) {
5659 std::string error;
5660 bool success =
5661 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005662 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005663 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005664 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005665 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005666 }
Steve Anton75737c02017-11-06 10:37:17 -08005667 }
5668 }
5669 }
Steve Antoned10bd92017-12-05 10:52:59 -08005670
Steve Anton75737c02017-11-06 10:37:17 -08005671 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5672 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005673 if (sctp_transport_ && local_description() && remote_description()) {
5674 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5675 local_description()->description());
5676 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5677 remote_description()->description());
5678 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005679 int max_message_size;
5680 // A remote max message size of zero means "any size supported".
5681 // We configure the connection with our own max message size.
5682 if (remote_sctp_description->max_message_size() == 0) {
5683 max_message_size = local_sctp_description->max_message_size();
5684 } else {
5685 max_message_size =
5686 std::min(local_sctp_description->max_message_size(),
5687 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005688 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005689 sctp_transport_->Start(local_sctp_description->port(),
5690 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005691 }
Steve Anton75737c02017-11-06 10:37:17 -08005692 }
Steve Antoned10bd92017-12-05 10:52:59 -08005693
Steve Anton8a006912017-12-04 15:25:56 -08005694 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005695}
5696
Steve Anton8a006912017-12-04 15:25:56 -08005697RTCError PeerConnection::PushdownTransportDescription(
5698 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005699 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005700 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005701
Zhi Huange830e682018-03-30 10:48:35 -07005702 if (source == cricket::CS_LOCAL) {
5703 const SessionDescriptionInterface* sdesc = local_description();
5704 RTC_DCHECK(sdesc);
5705 return transport_controller_->SetLocalDescription(type,
5706 sdesc->description());
5707 } else {
5708 const SessionDescriptionInterface* sdesc = remote_description();
5709 RTC_DCHECK(sdesc);
5710 return transport_controller_->SetRemoteDescription(type,
5711 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005712 }
Steve Anton75737c02017-11-06 10:37:17 -08005713}
5714
5715bool PeerConnection::GetTransportDescription(
5716 const SessionDescription* description,
5717 const std::string& content_name,
5718 cricket::TransportDescription* tdesc) {
5719 if (!description || !tdesc) {
5720 return false;
5721 }
5722 const TransportInfo* transport_info =
5723 description->GetTransportInfoByName(content_name);
5724 if (!transport_info) {
5725 return false;
5726 }
5727 *tdesc = transport_info->description;
5728 return true;
5729}
5730
Steve Anton75737c02017-11-06 10:37:17 -08005731cricket::IceConfig PeerConnection::ParseIceConfig(
5732 const PeerConnectionInterface::RTCConfiguration& config) const {
5733 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005734 switch (config.continual_gathering_policy) {
5735 case PeerConnectionInterface::GATHER_ONCE:
5736 gathering_policy = cricket::GATHER_ONCE;
5737 break;
5738 case PeerConnectionInterface::GATHER_CONTINUALLY:
5739 gathering_policy = cricket::GATHER_CONTINUALLY;
5740 break;
5741 default:
5742 RTC_NOTREACHED();
5743 gathering_policy = cricket::GATHER_ONCE;
5744 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005745
Steve Anton75737c02017-11-06 10:37:17 -08005746 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005747 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5748 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005749 ice_config.prioritize_most_likely_candidate_pairs =
5750 config.prioritize_most_likely_ice_candidate_pairs;
5751 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005752 RTCConfigurationToIceConfigOptionalInt(
5753 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005754 ice_config.continual_gathering_policy = gathering_policy;
5755 ice_config.presume_writable_when_fully_relayed =
5756 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005757 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5758 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005759 ice_config.ice_check_interval_strong_connectivity =
5760 config.ice_check_interval_strong_connectivity;
5761 ice_config.ice_check_interval_weak_connectivity =
5762 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005763 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005764 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5765 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005766 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005767 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005768 ice_config.regather_all_networks_interval_range =
5769 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005770 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005771 return ice_config;
5772}
5773
Steve Anton75737c02017-11-06 10:37:17 -08005774bool PeerConnection::SendData(const cricket::SendDataParams& params,
5775 const rtc::CopyOnWriteBuffer& payload,
5776 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005777 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005778 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5779 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5780 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005781 return false;
5782 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005783 if (media_transport_) {
5784 SendDataParams send_params;
5785 send_params.type = ToWebrtcDataMessageType(params.type);
5786 send_params.ordered = params.ordered;
5787 if (params.max_rtx_count >= 0) {
5788 send_params.max_rtx_count = params.max_rtx_count;
5789 } else if (params.max_rtx_ms >= 0) {
5790 send_params.max_rtx_ms = params.max_rtx_ms;
5791 }
5792 return media_transport_->SendData(params.sid, send_params, payload).ok();
5793 }
Steve Anton75737c02017-11-06 10:37:17 -08005794 return rtp_data_channel_
5795 ? rtp_data_channel_->SendData(params, payload, result)
5796 : network_thread()->Invoke<bool>(
5797 RTC_FROM_HERE,
5798 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005799 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005800}
5801
5802bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005803 RTC_DCHECK_RUN_ON(signaling_thread());
5804 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005805 // Don't log an error here, because DataChannels are expected to call
5806 // ConnectDataChannel in this state. It's the only way to initially tell
5807 // whether or not the underlying transport is ready.
5808 return false;
5809 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005810 if (media_transport_) {
5811 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5812 &DataChannel::OnChannelReady);
5813 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5814 &DataChannel::OnDataReceived);
5815 SignalMediaTransportChannelClosing_s.connect(
5816 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5817 SignalMediaTransportChannelClosed_s.connect(
5818 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5819 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005820 rtp_data_channel_->SignalReadyToSendData.connect(
5821 webrtc_data_channel, &DataChannel::OnChannelReady);
5822 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5823 &DataChannel::OnDataReceived);
5824 } else {
5825 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5826 &DataChannel::OnChannelReady);
5827 SignalSctpDataReceived.connect(webrtc_data_channel,
5828 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005829 SignalSctpClosingProcedureStartedRemotely.connect(
5830 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5831 SignalSctpClosingProcedureComplete.connect(
5832 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005833 }
5834 return true;
5835}
5836
5837void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005838 RTC_DCHECK_RUN_ON(signaling_thread());
5839 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005840 RTC_LOG(LS_ERROR)
5841 << "DisconnectDataChannel called when rtp_data_channel_ and "
5842 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005843 return;
5844 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005845 if (media_transport_) {
5846 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5847 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5848 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5849 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5850 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5852 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5853 } else {
5854 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5855 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005856 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5857 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005858 }
5859}
5860
5861void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005862 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005863 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005864 return;
5865 }
Steve Anton75737c02017-11-06 10:37:17 -08005866 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005867 RTC_LOG(LS_ERROR)
5868 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005869 return;
5870 }
5871 network_thread()->Invoke<void>(
5872 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005873 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005874}
5875
5876void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005877 if (media_transport_) {
5878 media_transport_->CloseChannel(sid);
5879 return;
5880 }
Steve Anton75737c02017-11-06 10:37:17 -08005881 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005882 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005883 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005884 return;
5885 }
5886 network_thread()->Invoke<void>(
5887 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005888 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005889}
5890
5891bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005892 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005893 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005894 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005895 sctp_ready_to_send_data_;
5896}
5897
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005898void PeerConnection::OnDataReceived(int channel_id,
5899 DataMessageType type,
5900 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005901 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005902 cricket::ReceiveDataParams params;
5903 params.sid = channel_id;
5904 params.type = ToCricketDataMessageType(type);
5905 media_transport_invoker_->AsyncInvoke<void>(
5906 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5907 RTC_DCHECK_RUN_ON(signaling_thread());
5908 if (!HandleOpenMessage_s(params, buffer)) {
5909 SignalMediaTransportReceivedData_s(params, buffer);
5910 }
5911 });
5912}
5913
5914void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005915 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005916 media_transport_invoker_->AsyncInvoke<void>(
5917 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5918 RTC_DCHECK_RUN_ON(signaling_thread());
5919 SignalMediaTransportChannelClosing_s(channel_id);
5920 });
5921}
5922
5923void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005924 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005925 media_transport_invoker_->AsyncInvoke<void>(
5926 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5927 RTC_DCHECK_RUN_ON(signaling_thread());
5928 SignalMediaTransportChannelClosed_s(channel_id);
5929 });
5930}
5931
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005932absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005933 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005934 if (sctp_mid_ && transport_controller_) {
5935 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5936 if (dtls_transport) {
5937 return dtls_transport->transport_name();
5938 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005939 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005940 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005941 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005942}
5943
Qingsi Wang72a43a12018-02-20 16:03:18 -08005944cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5945 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005946 network_thread()->Invoke<void>(
5947 RTC_FROM_HERE,
5948 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5949 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005950 return candidate_states_list;
5951}
5952
Steve Anton5dfde182018-02-06 10:34:40 -08005953std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5954 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005955 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005956 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005957 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005958 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005959 if (channel) {
5960 transport_names_by_mid[channel->content_name()] =
5961 channel->transport_name();
5962 }
Steve Anton75737c02017-11-06 10:37:17 -08005963 }
Steve Anton5dfde182018-02-06 10:34:40 -08005964 if (rtp_data_channel_) {
5965 transport_names_by_mid[rtp_data_channel_->content_name()] =
5966 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005967 }
5968 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005969 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005970 RTC_DCHECK(transport_name);
5971 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005972 }
Steve Anton5dfde182018-02-06 10:34:40 -08005973 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005974}
5975
Steve Anton5dfde182018-02-06 10:34:40 -08005976std::map<std::string, cricket::TransportStats>
5977PeerConnection::GetTransportStatsByNames(
5978 const std::set<std::string>& transport_names) {
5979 if (!network_thread()->IsCurrent()) {
5980 return network_thread()
5981 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5982 RTC_FROM_HERE,
5983 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005984 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005985 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005986 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5987 for (const std::string& transport_name : transport_names) {
5988 cricket::TransportStats transport_stats;
5989 bool success =
5990 transport_controller_->GetStats(transport_name, &transport_stats);
5991 if (success) {
5992 transport_stats_by_name[transport_name] = std::move(transport_stats);
5993 } else {
5994 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5995 << transport_name;
5996 }
5997 }
5998 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005999}
6000
6001bool PeerConnection::GetLocalCertificate(
6002 const std::string& transport_name,
6003 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006004 if (!certificate) {
6005 return false;
6006 }
6007 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6008 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006009}
6010
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006011std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006012 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006013 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006014}
6015
6016cricket::DataChannelType PeerConnection::data_channel_type() const {
6017 return data_channel_type_;
6018}
6019
6020bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006021 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006022 return pending_ice_restarts_.find(content_name) !=
6023 pending_ice_restarts_.end();
6024}
6025
Steve Anton75737c02017-11-06 10:37:17 -08006026bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6027 return transport_controller_->NeedsIceRestart(content_name);
6028}
6029
6030void PeerConnection::OnCertificateReady(
6031 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6032 transport_controller_->SetLocalCertificate(certificate);
6033}
6034
6035void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006036 SetSessionError(SessionError::kTransport,
6037 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006038}
6039
Alex Loiko9289eda2018-11-23 16:18:59 +00006040void PeerConnection::OnTransportControllerConnectionState(
6041 cricket::IceConnectionState state) {
6042 switch (state) {
6043 case cricket::kIceConnectionConnecting:
6044 // If the current state is Connected or Completed, then there were
6045 // writable channels but now there are not, so the next state must
6046 // be Disconnected.
6047 // kIceConnectionConnecting is currently used as the default,
6048 // un-connected state by the TransportController, so its only use is
6049 // detecting disconnections.
6050 if (ice_connection_state_ ==
6051 PeerConnectionInterface::kIceConnectionConnected ||
6052 ice_connection_state_ ==
6053 PeerConnectionInterface::kIceConnectionCompleted) {
6054 SetIceConnectionState(
6055 PeerConnectionInterface::kIceConnectionDisconnected);
6056 }
6057 break;
6058 case cricket::kIceConnectionFailed:
6059 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6060 break;
6061 case cricket::kIceConnectionConnected:
6062 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6063 "all transports are writable.";
6064 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6065 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6066 break;
6067 case cricket::kIceConnectionCompleted:
6068 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6069 "all transports are complete.";
6070 if (ice_connection_state_ !=
6071 PeerConnectionInterface::kIceConnectionConnected) {
6072 // If jumping directly from "checking" to "connected",
6073 // signal "connected" first.
6074 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6075 }
6076 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6077 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6078 ReportTransportStats();
6079 break;
6080 default:
6081 RTC_NOTREACHED();
6082 }
6083}
6084
Steve Anton75737c02017-11-06 10:37:17 -08006085void PeerConnection::OnTransportControllerCandidatesGathered(
6086 const std::string& transport_name,
6087 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006088 int sdp_mline_index;
6089 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006090 RTC_LOG(LS_ERROR)
6091 << "OnTransportControllerCandidatesGathered: content name "
6092 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006093 return;
6094 }
6095
6096 for (cricket::Candidates::const_iterator citer = candidates.begin();
6097 citer != candidates.end(); ++citer) {
6098 // Use transport_name as the candidate media id.
6099 std::unique_ptr<JsepIceCandidate> candidate(
6100 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6101 if (local_description()) {
6102 mutable_local_description()->AddCandidate(candidate.get());
6103 }
6104 OnIceCandidate(std::move(candidate));
6105 }
6106}
6107
6108void PeerConnection::OnTransportControllerCandidatesRemoved(
6109 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006110 // Sanity check.
6111 for (const cricket::Candidate& candidate : candidates) {
6112 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006113 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006114 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006115 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006116 return;
6117 }
6118 }
6119
6120 if (local_description()) {
6121 mutable_local_description()->RemoveCandidates(candidates);
6122 }
6123 OnIceCandidatesRemoved(candidates);
6124}
6125
6126void PeerConnection::OnTransportControllerDtlsHandshakeError(
6127 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006128 RTC_HISTOGRAM_ENUMERATION(
6129 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6130 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006131}
6132
Steve Antoned10bd92017-12-05 10:52:59 -08006133void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006134 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006135 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006136 if (channel && !channel->enabled()) {
6137 channel->Enable(true);
6138 }
Steve Anton75737c02017-11-06 10:37:17 -08006139 }
6140
Steve Anton4171afb2017-11-20 10:20:22 -08006141 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006142 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006143 }
Steve Anton75737c02017-11-06 10:37:17 -08006144}
6145
6146// Returns the media index for a local ice candidate given the content name.
6147bool PeerConnection::GetLocalCandidateMediaIndex(
6148 const std::string& content_name,
6149 int* sdp_mline_index) {
6150 if (!local_description() || !sdp_mline_index) {
6151 return false;
6152 }
6153
6154 bool content_found = false;
6155 const ContentInfos& contents = local_description()->description()->contents();
6156 for (size_t index = 0; index < contents.size(); ++index) {
6157 if (contents[index].name == content_name) {
6158 *sdp_mline_index = static_cast<int>(index);
6159 content_found = true;
6160 break;
6161 }
6162 }
6163 return content_found;
6164}
6165
6166bool PeerConnection::UseCandidatesInSessionDescription(
6167 const SessionDescriptionInterface* remote_desc) {
6168 if (!remote_desc) {
6169 return true;
6170 }
6171 bool ret = true;
6172
6173 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6174 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6175 for (size_t n = 0; n < candidates->count(); ++n) {
6176 const IceCandidateInterface* candidate = candidates->at(n);
6177 bool valid = false;
6178 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6179 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006180 RTC_LOG(LS_INFO)
6181 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006182 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006183 }
6184 continue;
6185 }
6186 ret = UseCandidate(candidate);
6187 if (!ret) {
6188 break;
6189 }
6190 }
6191 }
6192 return ret;
6193}
6194
6195bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006196 RTCErrorOr<const cricket::ContentInfo*> result =
6197 FindContentInfo(remote_description(), candidate);
6198 if (!result.ok()) {
6199 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6200 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006201 return false;
6202 }
Steve Anton75737c02017-11-06 10:37:17 -08006203 std::vector<cricket::Candidate> candidates;
6204 candidates.push_back(candidate->candidate());
6205 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006206 RTCError error = transport_controller_->AddRemoteCandidates(
6207 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006208 if (error.ok()) {
6209 // Candidates successfully submitted for checking.
6210 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6211 ice_connection_state_ ==
6212 PeerConnectionInterface::kIceConnectionDisconnected) {
6213 // If state is New, then the session has just gotten its first remote ICE
6214 // candidates, so go to Checking.
6215 // If state is Disconnected, the session is re-using old candidates or
6216 // receiving additional ones, so go to Checking.
6217 // If state is Connected, stay Connected.
6218 // TODO(bemasc): If state is Connected, and the new candidates are for a
6219 // newly added transport, then the state actually _should_ move to
6220 // checking. Add a way to distinguish that case.
6221 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6222 }
6223 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006224 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006225 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006226 }
6227 return true;
6228}
6229
Guido Urdaneta41633172019-05-23 20:12:29 +02006230RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6231 const SessionDescriptionInterface* description,
6232 const IceCandidateInterface* candidate) {
6233 if (candidate->sdp_mline_index() >= 0) {
6234 size_t mediacontent_index =
6235 static_cast<size_t>(candidate->sdp_mline_index());
6236 size_t content_size = description->description()->contents().size();
6237 if (mediacontent_index < content_size) {
6238 return &description->description()->contents()[mediacontent_index];
6239 } else {
6240 return RTCError(RTCErrorType::INVALID_RANGE,
6241 "Media line index (" +
6242 rtc::ToString(candidate->sdp_mline_index()) +
6243 ") out of range (number of mlines: " +
6244 rtc::ToString(content_size) + ").");
6245 }
6246 } else if (!candidate->sdp_mid().empty()) {
6247 auto& contents = description->description()->contents();
6248 auto it = absl::c_find_if(
6249 contents, [candidate](const cricket::ContentInfo& content_info) {
6250 return content_info.mid() == candidate->sdp_mid();
6251 });
6252 if (it == contents.end()) {
6253 return RTCError(
6254 RTCErrorType::INVALID_PARAMETER,
6255 "Mid " + candidate->sdp_mid() +
6256 " specified but no media section with that mid found.");
6257 } else {
6258 return &*it;
6259 }
6260 }
6261
6262 return RTCError(RTCErrorType::INVALID_PARAMETER,
6263 "Neither sdp_mline_index nor sdp_mid specified.");
6264}
6265
Steve Anton75737c02017-11-06 10:37:17 -08006266void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006267 // Destroy video channel first since it may have a pointer to the
6268 // voice channel.
6269 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006270 if (!video_info || video_info->rejected) {
6271 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006272 }
6273
Steve Anton6fec8802017-12-04 10:37:29 -08006274 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6275 if (!audio_info || audio_info->rejected) {
6276 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006277 }
6278
6279 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6280 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006281 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006282 }
6283}
6284
Steve Antondcc3c022017-12-22 16:02:54 -08006285RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6286 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006287 const cricket::ContentGroup* bundle_group = nullptr;
6288 if (configuration_.bundle_policy ==
6289 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006290 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006291 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006292 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6293 "max-bundle configured but session description "
6294 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006295 }
6296 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006297 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006298}
6299
6300RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006301 // Creating the media channels. Transports should already have been created
6302 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006303 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006304 if (voice && !voice->rejected &&
6305 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006306 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006307 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006308 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6309 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006310 }
6311 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6312 }
6313
Steve Antondcc3c022017-12-22 16:02:54 -08006314 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006315 if (video && !video->rejected &&
6316 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006317 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006318 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006319 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6320 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006321 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006322 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006323 }
6324
Steve Antondcc3c022017-12-22 16:02:54 -08006325 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006326 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006327 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006328 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006329 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6330 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006331 }
6332 }
6333
Steve Anton8a006912017-12-04 15:25:56 -08006334 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006335}
6336
Steve Anton4171afb2017-11-20 10:20:22 -08006337// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006338cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006339 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006340 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006341 MediaTransportConfig media_transport_config =
6342 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006343
Steve Anton75737c02017-11-06 10:37:17 -08006344 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006345 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006346 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6347 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006348 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006349 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006350 }
Steve Anton75737c02017-11-06 10:37:17 -08006351 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6352 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006353 voice_channel->SignalSentPacket.connect(this,
6354 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006355 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006356
Steve Antoneda6ccd2017-12-04 10:21:55 -08006357 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006358}
6359
Steve Anton4171afb2017-11-20 10:20:22 -08006360// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006361cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006362 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006363 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006364 MediaTransportConfig media_transport_config =
6365 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006366
Steve Anton75737c02017-11-06 10:37:17 -08006367 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006368 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006369 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6370 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006371 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006372 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006373 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006374 }
Steve Anton75737c02017-11-06 10:37:17 -08006375 video_channel->SignalDtlsSrtpSetupFailure.connect(
6376 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006377 video_channel->SignalSentPacket.connect(this,
6378 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006379 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006380
Steve Antoneda6ccd2017-12-04 10:21:55 -08006381 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006382}
6383
Zhi Huange830e682018-03-30 10:48:35 -07006384bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006385 switch (data_channel_type_) {
6386 case cricket::DCT_MEDIA_TRANSPORT:
6387 if (network_thread()->Invoke<bool>(
6388 RTC_FROM_HERE,
6389 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6390 this, mid))) {
6391 for (const auto& channel : sctp_data_channels_) {
6392 channel->OnTransportChannelCreated();
6393 }
6394 return true;
6395 }
Steve Anton75737c02017-11-06 10:37:17 -08006396 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006397 case cricket::DCT_SCTP:
6398 if (!sctp_factory_) {
6399 RTC_LOG(LS_ERROR)
6400 << "Trying to create SCTP transport, but didn't compile with "
6401 "SCTP support (HAVE_SCTP)";
6402 return false;
6403 }
6404 if (!network_thread()->Invoke<bool>(
6405 RTC_FROM_HERE,
6406 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6407 return false;
6408 }
6409 for (const auto& channel : sctp_data_channels_) {
6410 channel->OnTransportChannelCreated();
6411 }
6412 return true;
6413 case cricket::DCT_RTP:
6414 default:
6415 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6416 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6417 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006418 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006419 if (!rtp_data_channel_) {
6420 return false;
6421 }
6422 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6423 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6424 rtp_data_channel_->SignalSentPacket.connect(
6425 this, &PeerConnection::OnSentPacket_w);
6426 rtp_data_channel_->SetRtpTransport(rtp_transport);
6427 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006428 }
6429
Steve Anton75737c02017-11-06 10:37:17 -08006430 return true;
6431}
6432
6433Call::Stats PeerConnection::GetCallStats() {
6434 if (!worker_thread()->IsCurrent()) {
6435 return worker_thread()->Invoke<Call::Stats>(
6436 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6437 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006438 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006439 if (call_) {
6440 return call_->GetStats();
6441 } else {
6442 return Call::Stats();
6443 }
6444}
6445
Zhi Huange830e682018-03-30 10:48:35 -07006446bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006447 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006448 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006449 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6450 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006451 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006452 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006453 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006454 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6455 sctp_factory_->CreateSctpTransport(dtls_transport);
6456 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006457 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006458 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006459 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006460 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006461 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006462 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6463 // another thread. Would be nice if there was a helper class similar to
6464 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6465 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006466 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006467 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006468 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006469 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006470 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006471 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6472 std::move(cricket_sctp_transport));
6473 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006474 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006475}
6476
6477void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006478 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006479 sctp_transport_->Clear();
6480 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006481 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006482 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006483}
6484
6485void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006486 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006487 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006488 // Note: Cannot use rtc::Bind here because it will grab a reference to
6489 // PeerConnection and potentially cause PeerConnection to live longer than
6490 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6491 // be destroyed before PeerConnection is destroyed, and at that point all
6492 // pending tasks will be cleared.
6493 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6494 OnSctpTransportReadyToSendData_s(true);
6495 });
6496}
6497
6498void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006499 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006500 sctp_ready_to_send_data_ = ready;
6501 SignalSctpReadyToSendData(ready);
6502}
6503
6504void PeerConnection::OnSctpTransportDataReceived_n(
6505 const cricket::ReceiveDataParams& params,
6506 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006507 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006508 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006509 // Note: Cannot use rtc::Bind here because it will grab a reference to
6510 // PeerConnection and potentially cause PeerConnection to live longer than
6511 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6512 // be destroyed before PeerConnection is destroyed, and at that point all
6513 // pending tasks will be cleared.
6514 sctp_invoker_->AsyncInvoke<void>(
6515 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6516 OnSctpTransportDataReceived_s(params, payload);
6517 });
6518}
6519
6520void PeerConnection::OnSctpTransportDataReceived_s(
6521 const cricket::ReceiveDataParams& params,
6522 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006523 RTC_DCHECK_RUN_ON(signaling_thread());
6524 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006525 SignalSctpDataReceived(params, payload);
6526 }
6527}
6528
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006529void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006530 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006531 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006532 sctp_invoker_->AsyncInvoke<void>(
6533 RTC_FROM_HERE, signaling_thread(),
6534 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006535 &SignalSctpClosingProcedureStartedRemotely, sid));
6536}
6537
6538void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006539 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006540 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006541 sctp_invoker_->AsyncInvoke<void>(
6542 RTC_FROM_HERE, signaling_thread(),
6543 rtc::Bind(&sigslot::signal1<int>::operator(),
6544 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006545}
6546
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006547bool PeerConnection::SetupMediaTransportForDataChannels_n(
6548 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006549 media_transport_ =
6550 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006551 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006552 RTC_LOG(LS_ERROR)
6553 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006554 return false;
6555 }
6556
6557 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6558 media_transport_->SetDataSink(this);
6559 media_transport_data_mid_ = mid;
6560 transport_controller_->SignalMediaTransportStateChanged.connect(
6561 this, &PeerConnection::OnMediaTransportStateChanged_n);
6562 // Check the initial state right away, in case transport is already writable.
6563 OnMediaTransportStateChanged_n();
6564 return true;
6565}
6566
6567void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6568 if (!media_transport_) {
6569 return;
6570 }
6571 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6572 media_transport_data_mid_.reset();
6573 media_transport_->SetDataSink(nullptr);
6574 media_transport_invoker_ = nullptr;
6575 media_transport_ = nullptr;
6576}
6577
6578void PeerConnection::OnMediaTransportStateChanged_n() {
6579 if (!media_transport_data_mid_ ||
6580 transport_controller_->GetMediaTransportState(
6581 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6582 return;
6583 }
6584 media_transport_invoker_->AsyncInvoke<void>(
6585 RTC_FROM_HERE, signaling_thread(), [this] {
6586 RTC_DCHECK_RUN_ON(signaling_thread());
6587 media_transport_ready_to_send_data_ = true;
6588 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6589 });
6590}
6591
Steve Anton75737c02017-11-06 10:37:17 -08006592// Returns false if bundle is enabled and rtcp_mux is disabled.
6593bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6594 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6595 if (!bundle_enabled)
6596 return true;
6597
6598 const cricket::ContentGroup* bundle_group =
6599 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6600 RTC_DCHECK(bundle_group != NULL);
6601
6602 const cricket::ContentInfos& contents = desc->contents();
6603 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6604 citer != contents.end(); ++citer) {
6605 const cricket::ContentInfo* content = (&*citer);
6606 RTC_DCHECK(content != NULL);
6607 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006608 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006609 if (!HasRtcpMuxEnabled(content))
6610 return false;
6611 }
6612 }
6613 // RTCP-MUX is enabled in all the contents.
6614 return true;
6615}
6616
6617bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006618 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006619}
6620
Steve Anton06817cd2018-12-18 15:55:30 -08006621static RTCError ValidateMids(const cricket::SessionDescription& description) {
6622 std::set<std::string> mids;
6623 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006624 if (content.name.empty()) {
6625 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6626 "A media section is missing a MID attribute.");
6627 }
Steve Anton06817cd2018-12-18 15:55:30 -08006628 if (!mids.insert(content.name).second) {
6629 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6630 "Duplicate a=mid value '" + content.name + "'.");
6631 }
6632 }
6633 return RTCError::OK();
6634}
6635
Steve Anton8a006912017-12-04 15:25:56 -08006636RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006637 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006638 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006639 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006640 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006641 }
6642
6643 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006644 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006645 }
6646
Steve Anton3828c062017-12-06 10:34:51 -08006647 SdpType type = sdesc->GetType();
6648 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6649 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006650 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006651 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006652 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006653 }
6654
Steve Anton06817cd2018-12-18 15:55:30 -08006655 RTCError error = ValidateMids(*sdesc->description());
6656 if (!error.ok()) {
6657 return error;
6658 }
6659
Steve Anton75737c02017-11-06 10:37:17 -08006660 // Verify crypto settings.
6661 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006662 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6663 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006664 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006665 if (!crypto_error.ok()) {
6666 return crypto_error;
6667 }
Steve Anton75737c02017-11-06 10:37:17 -08006668 }
6669
6670 // Verify ice-ufrag and ice-pwd.
6671 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006672 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6673 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006674 }
6675
6676 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006677 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6678 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006679 }
6680
6681 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6682 // m-lines that do not rtcp-mux enabled.
6683
6684 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006685 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006686 // With an answer we want to compare the new answer session description with
6687 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006688 const cricket::SessionDescription* offer_desc =
6689 (source == cricket::CS_LOCAL) ? remote_description()->description()
6690 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006691 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6692 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6693 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006694 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6695 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006696 }
6697 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006698 // The re-offers should respect the order of m= sections in current
6699 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006700 // With a re-offer, either the current local or current remote descriptions
6701 // could be the most up to date, so we would like to check against both of
6702 // them if they exist. It could be the case that one of them has a 0 port
6703 // for a media section, but the other does not. This is important to check
6704 // against in the case that we are recycling an m= section.
6705 const cricket::SessionDescription* current_desc = nullptr;
6706 const cricket::SessionDescription* secondary_current_desc = nullptr;
6707 if (local_description()) {
6708 current_desc = local_description()->description();
6709 if (remote_description()) {
6710 secondary_current_desc = remote_description()->description();
6711 }
6712 } else if (remote_description()) {
6713 current_desc = remote_description()->description();
6714 }
Steve Anton75737c02017-11-06 10:37:17 -08006715 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006716 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6717 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006718 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6719 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006720 }
6721 }
6722
Steve Antonba42e992018-04-09 14:10:01 -07006723 if (IsUnifiedPlan()) {
6724 // Ensure that each audio and video media section has at most one
6725 // "StreamParams". This will return an error if receiving a session
6726 // description from a "Plan B" endpoint which adds multiple tracks of the
6727 // same type. With Unified Plan, there can only be at most one track per
6728 // media section.
6729 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006730 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006731 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6732 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6733 desc.streams().size() > 1u) {
6734 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6735 "Media section has more than one track specified "
6736 "with a=ssrc lines which is not supported with "
6737 "Unified Plan.");
6738 }
6739 }
6740 }
6741
Steve Anton8a006912017-12-04 15:25:56 -08006742 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006743}
6744
Steve Anton3828c062017-12-06 10:34:51 -08006745bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006746 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006747 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006748 return (state == PeerConnectionInterface::kStable) ||
6749 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006750 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006751 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006752 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6753 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6754 }
6755}
6756
Steve Anton3828c062017-12-06 10:34:51 -08006757bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006758 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006759 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006760 return (state == PeerConnectionInterface::kStable) ||
6761 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006762 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006763 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006764 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6765 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6766 }
6767}
6768
Steve Antonf8470812017-12-04 10:46:21 -08006769const char* PeerConnection::SessionErrorToString(SessionError error) const {
6770 switch (error) {
6771 case SessionError::kNone:
6772 return "ERROR_NONE";
6773 case SessionError::kContent:
6774 return "ERROR_CONTENT";
6775 case SessionError::kTransport:
6776 return "ERROR_TRANSPORT";
6777 }
6778 RTC_NOTREACHED();
6779 return "";
6780}
6781
Steve Anton75737c02017-11-06 10:37:17 -08006782std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006783 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006784 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6785 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006786 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006787}
6788
Steve Anton8e20f172018-03-06 10:55:04 -08006789void PeerConnection::ReportSdpFormatReceived(
6790 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006791 int num_audio_mlines = 0;
6792 int num_video_mlines = 0;
6793 int num_audio_tracks = 0;
6794 int num_video_tracks = 0;
6795 for (const ContentInfo& content : remote_offer.description()->contents()) {
6796 cricket::MediaType media_type = content.media_description()->type();
6797 int num_tracks = std::max(
6798 1, static_cast<int>(content.media_description()->streams().size()));
6799 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6800 num_audio_mlines += 1;
6801 num_audio_tracks += num_tracks;
6802 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6803 num_video_mlines += 1;
6804 num_video_tracks += num_tracks;
6805 }
6806 }
6807 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6808 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6809 format = kSdpFormatReceivedComplexUnifiedPlan;
6810 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6811 format = kSdpFormatReceivedComplexPlanB;
6812 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6813 format = kSdpFormatReceivedSimple;
6814 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006815 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6816 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006817}
6818
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006819void PeerConnection::NoteUsageEvent(UsageEvent event) {
6820 RTC_DCHECK_RUN_ON(signaling_thread());
6821 usage_event_accumulator_ |= static_cast<int>(event);
6822}
6823
6824void PeerConnection::ReportUsagePattern() const {
6825 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006826 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6827 usage_event_accumulator_,
6828 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006829 const int bad_bits =
6830 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6831 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6832 const int good_bits =
6833 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6834 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6835 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6836 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6837 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006838 // If called after close(), we can't report, because observer may have
6839 // been deallocated, and therefore pointer is null. Write to log instead.
6840 if (observer_) {
6841 Observer()->OnInterestingUsage(usage_event_accumulator_);
6842 } else {
6843 RTC_LOG(LS_INFO) << "Interesting usage signature "
6844 << usage_event_accumulator_
6845 << " observed after observer shutdown";
6846 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006847 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006848}
6849
Steve Anton0ffaaa22018-02-23 10:31:30 -08006850void PeerConnection::ReportNegotiatedSdpSemantics(
6851 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006852 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006853 switch (answer.description()->msid_signaling()) {
6854 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006855 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006856 break;
6857 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006858 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006859 break;
6860 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006861 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006862 break;
6863 case cricket::kMsidSignalingMediaSection |
6864 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006865 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006866 break;
6867 default:
6868 RTC_NOTREACHED();
6869 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006870 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6871 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006872}
6873
Steve Anton75737c02017-11-06 10:37:17 -08006874// We need to check the local/remote description for the Transport instead of
6875// the session, because a new Transport added during renegotiation may have
6876// them unset while the session has them set from the previous negotiation.
6877// Not doing so may trigger the auto generation of transport description and
6878// mess up DTLS identity information, ICE credential, etc.
6879bool PeerConnection::ReadyToUseRemoteCandidate(
6880 const IceCandidateInterface* candidate,
6881 const SessionDescriptionInterface* remote_desc,
6882 bool* valid) {
6883 *valid = true;
6884
6885 const SessionDescriptionInterface* current_remote_desc =
6886 remote_desc ? remote_desc : remote_description();
6887
6888 if (!current_remote_desc) {
6889 return false;
6890 }
6891
Guido Urdaneta41633172019-05-23 20:12:29 +02006892 RTCErrorOr<const cricket::ContentInfo*> result =
6893 FindContentInfo(current_remote_desc, candidate);
6894 if (!result.ok()) {
6895 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6896 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006897
6898 *valid = false;
6899 return false;
6900 }
6901
Guido Urdaneta41633172019-05-23 20:12:29 +02006902 std::string transport_name = GetTransportName(result.value()->name);
6903 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006904}
6905
6906bool PeerConnection::SrtpRequired() const {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006907 return !configuration_.use_datagram_transport &&
6908 (dtls_enabled_ ||
6909 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006910}
6911
6912void PeerConnection::OnTransportControllerGatheringState(
6913 cricket::IceGatheringState state) {
6914 RTC_DCHECK(signaling_thread()->IsCurrent());
6915 if (state == cricket::kIceGatheringGathering) {
6916 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6917 } else if (state == cricket::kIceGatheringComplete) {
6918 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6919 }
6920}
6921
6922void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006923 std::map<std::string, std::set<cricket::MediaType>>
6924 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006925 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006926 if (transceiver->internal()->channel()) {
6927 const std::string& transport_name =
6928 transceiver->internal()->channel()->transport_name();
6929 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006930 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006931 }
Steve Anton75737c02017-11-06 10:37:17 -08006932 }
6933 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006934 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6935 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006936 }
Zhi Huange830e682018-03-30 10:48:35 -07006937
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006938 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006939 if (transport_name) {
6940 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006941 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006942 }
Zhi Huange830e682018-03-30 10:48:35 -07006943
Steve Antonc7b964c2018-02-01 14:39:45 -08006944 for (const auto& entry : media_types_by_transport_name) {
6945 const std::string& transport_name = entry.first;
6946 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006947 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006948 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006949 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006950 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006951 }
6952 }
6953}
6954// Walk through the ConnectionInfos to gather best connection usage
6955// for IPv4 and IPv6.
6956void PeerConnection::ReportBestConnectionState(
6957 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006958 for (const cricket::TransportChannelStats& channel_stats :
6959 stats.channel_stats) {
6960 for (const cricket::ConnectionInfo& connection_info :
6961 channel_stats.connection_infos) {
6962 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006963 continue;
6964 }
6965
Steve Antonc7b964c2018-02-01 14:39:45 -08006966 const cricket::Candidate& local = connection_info.local_candidate;
6967 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006968
6969 // Increment the counter for IceCandidatePairType.
6970 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6971 (local.type() == RELAY_PORT_TYPE &&
6972 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006973 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6974 GetIceCandidatePairCounter(local, remote),
6975 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006976 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006977 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6978 GetIceCandidatePairCounter(local, remote),
6979 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006980 } else {
6981 RTC_CHECK(0);
6982 }
Steve Anton75737c02017-11-06 10:37:17 -08006983
6984 // Increment the counter for IP type.
6985 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006986 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6987 kBestConnections_IPv4,
6988 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006989 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006990 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6991 kBestConnections_IPv6,
6992 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006993 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006994 RTC_CHECK(!local.address().hostname().empty() &&
6995 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006996 }
6997
6998 return;
6999 }
7000 }
7001}
7002
7003void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007004 const cricket::TransportStats& stats,
7005 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007006 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7007 return;
7008 }
7009
7010 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7011 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7012 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7013 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7014 return;
7015 }
7016
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007017 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7018 for (cricket::MediaType media_type : media_types) {
7019 switch (media_type) {
7020 case cricket::MEDIA_TYPE_AUDIO:
7021 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7022 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7023 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7024 break;
7025 case cricket::MEDIA_TYPE_VIDEO:
7026 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7027 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7028 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7029 break;
7030 case cricket::MEDIA_TYPE_DATA:
7031 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7032 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7033 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7034 break;
7035 default:
7036 RTC_NOTREACHED();
7037 continue;
7038 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007039 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007040 }
7041
7042 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7043 for (cricket::MediaType media_type : media_types) {
7044 switch (media_type) {
7045 case cricket::MEDIA_TYPE_AUDIO:
7046 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7047 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7048 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7049 break;
7050 case cricket::MEDIA_TYPE_VIDEO:
7051 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7052 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7053 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7054 break;
7055 case cricket::MEDIA_TYPE_DATA:
7056 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7057 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7058 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7059 break;
7060 default:
7061 RTC_NOTREACHED();
7062 continue;
7063 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007064 }
Steve Anton75737c02017-11-06 10:37:17 -08007065 }
7066}
7067
7068void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007069 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007070 RTC_DCHECK(call_);
7071 call_->OnSentPacket(sent_packet);
7072}
7073
7074const std::string PeerConnection::GetTransportName(
7075 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007076 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007077 if (channel) {
7078 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007079 }
Steve Anton6fec8802017-12-04 10:37:29 -08007080 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007081 RTC_DCHECK(sctp_mid_);
7082 if (content_name == *sctp_mid_) {
7083 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007084 }
7085 }
7086 // Return an empty string if failed to retrieve the transport name.
7087 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007088}
7089
Steve Anton6fec8802017-12-04 10:37:29 -08007090void PeerConnection::DestroyTransceiverChannel(
7091 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7092 transceiver) {
7093 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007094
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007095 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007096 if (channel) {
7097 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007098 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007099 }
7100}
7101
7102void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007103 if (rtp_data_channel_) {
7104 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007105 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007106 rtp_data_channel_ = nullptr;
7107 }
7108
7109 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7110 // grab a reference to this PeerConnection. If this is called from the
7111 // PeerConnection destructor, the RefCountedObject vtable will have already
7112 // been destroyed (since it is a subclass of PeerConnection) and using
7113 // rtc::Bind will cause "Pure virtual function called" error to appear.
7114
7115 if (sctp_transport_) {
7116 OnDataChannelDestroyed();
7117 network_thread()->Invoke<void>(RTC_FROM_HERE,
7118 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007119 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007120 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007121
7122 if (media_transport_) {
7123 OnDataChannelDestroyed();
7124 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7125 RTC_DCHECK_RUN_ON(network_thread());
7126 TeardownMediaTransportForDataChannels_n();
7127 });
7128 }
Steve Anton6fec8802017-12-04 10:37:29 -08007129}
7130
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007131void PeerConnection::DestroyChannelInterface(
7132 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007133 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007134 switch (channel->media_type()) {
7135 case cricket::MEDIA_TYPE_AUDIO:
7136 channel_manager()->DestroyVoiceChannel(
7137 static_cast<cricket::VoiceChannel*>(channel));
7138 break;
7139 case cricket::MEDIA_TYPE_VIDEO:
7140 channel_manager()->DestroyVideoChannel(
7141 static_cast<cricket::VideoChannel*>(channel));
7142 break;
7143 case cricket::MEDIA_TYPE_DATA:
7144 channel_manager()->DestroyRtpDataChannel(
7145 static_cast<cricket::RtpDataChannel*>(channel));
7146 break;
7147 default:
7148 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7149 break;
7150 }
Zhi Huange830e682018-03-30 10:48:35 -07007151}
Steve Anton6fec8802017-12-04 10:37:29 -08007152
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007153bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007154 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007155 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007156 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007157 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007158 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007159 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007160 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007161 auto base_channel = GetChannel(mid);
7162 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007163 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007164 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007165 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007166 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007167 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007168
Karl Wiberg5966c502019-02-21 23:55:09 +01007169 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007170 // Only pass media transport to call object if media transport is used
7171 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007172 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007173 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007174
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007175 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007176}
7177
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007178void PeerConnection::OnSetStreams() {
7179 RTC_DCHECK_RUN_ON(signaling_thread());
7180 if (IsUnifiedPlan())
7181 UpdateNegotiationNeeded();
7182}
7183
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007184PeerConnectionObserver* PeerConnection::Observer() const {
7185 // In earlier production code, the pointer was not cleared on close,
7186 // which might have led to undefined behavior if the observer was not
7187 // deallocated, or strange crashes if it was.
7188 // We use CHECK in order to catch such behavior if it exists.
7189 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7190 RTC_CHECK(observer_);
7191 return observer_;
7192}
7193
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007194CryptoOptions PeerConnection::GetCryptoOptions() {
7195 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7196 // after it has been removed.
7197 return configuration_.crypto_options.has_value()
7198 ? *configuration_.crypto_options
7199 : factory_->options().crypto_options;
7200}
7201
Harald Alvestrand89061872018-01-02 14:08:34 +01007202void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007203 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007204 if (stats_collector_) {
7205 stats_collector_->ClearCachedStatsReport();
7206 }
7207}
7208
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007209void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007210 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7211 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007212}
7213
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007214void PeerConnection::UpdateNegotiationNeeded() {
7215 RTC_DCHECK_RUN_ON(signaling_thread());
7216 if (!IsUnifiedPlan()) {
7217 Observer()->OnRenegotiationNeeded();
7218 return;
7219 }
7220
7221 // If connection's [[IsClosed]] slot is true, abort these steps.
7222 if (IsClosed())
7223 return;
7224
7225 // If connection's signaling state is not "stable", abort these steps.
7226 if (signaling_state() != kStable)
7227 return;
7228
7229 // NOTE
7230 // The negotiation-needed flag will be updated once the state transitions to
7231 // "stable", as part of the steps for setting an RTCSessionDescription.
7232
7233 // If the result of checking if negotiation is needed is false, clear the
7234 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7235 // to false, and abort these steps.
7236 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7237 if (!is_negotiation_needed) {
7238 is_negotiation_needed_ = false;
7239 return;
7240 }
7241
7242 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7243 // steps.
7244 if (is_negotiation_needed_)
7245 return;
7246
7247 // Set connection's [[NegotiationNeeded]] slot to true.
7248 is_negotiation_needed_ = true;
7249
7250 // Queue a task that runs the following steps:
7251 // If connection's [[IsClosed]] slot is true, abort these steps.
7252 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7253 // Fire an event named negotiationneeded at connection.
7254 Observer()->OnRenegotiationNeeded();
7255}
7256
7257bool PeerConnection::CheckIfNegotiationIsNeeded() {
7258 RTC_DCHECK_RUN_ON(signaling_thread());
7259 // 1. If any implementation-specific negotiation is required, as described at
7260 // the start of this section, return true.
7261
7262 // 2. Let description be connection.[[CurrentLocalDescription]].
7263 const SessionDescriptionInterface* description = current_local_description();
7264 if (!description)
7265 return true;
7266
7267 // 3. If connection has created any RTCDataChannels, and no m= section in
7268 // description has been negotiated yet for data, return true.
7269 if (!sctp_data_channels_.empty()) {
7270 if (!cricket::GetFirstDataContent(description->description()->contents()))
7271 return true;
7272 }
7273
7274 // 4. For each transceiver in connection's set of transceivers, perform the
7275 // following checks:
7276 for (const auto& transceiver : transceivers_) {
7277 const ContentInfo* current_local_msection =
7278 FindTransceiverMSection(transceiver.get(), description);
7279
7280 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7281 transceiver.get(), current_remote_description());
7282
7283 // 4.3 If transceiver is stopped and is associated with an m= section,
7284 // but the associated m= section is not yet rejected in
7285 // connection.[[CurrentLocalDescription]] or
7286 // connection.[[CurrentRemoteDescription]], return true.
7287 if (transceiver->stopped()) {
7288 if (current_local_msection && !current_local_msection->rejected &&
7289 ((current_remote_msection && !current_remote_msection->rejected) ||
7290 !current_remote_msection)) {
7291 return true;
7292 }
7293 continue;
7294 }
7295
7296 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7297 // section in description, return true.
7298 if (!current_local_msection)
7299 return true;
7300
7301 const MediaContentDescription* current_local_media_description =
7302 current_local_msection->media_description();
7303 // 4.2 If transceiver isn't stopped and is associated with an m= section
7304 // in description then perform the following checks:
7305
7306 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7307 // associated m= section in description either doesn't contain a single
7308 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7309 // m= section, or the MSID values themselves, differ from what is in
7310 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7311 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7312 if (current_local_media_description->streams().size() == 0)
7313 return true;
7314
7315 std::vector<std::string> msection_msids;
7316 for (const auto& stream : current_local_media_description->streams()) {
7317 for (const std::string& msid : stream.stream_ids())
7318 msection_msids.push_back(msid);
7319 }
7320
7321 std::vector<std::string> transceiver_msids =
7322 transceiver->sender()->stream_ids();
7323 if (msection_msids.size() != transceiver_msids.size())
7324 return true;
7325
7326 absl::c_sort(transceiver_msids);
7327 absl::c_sort(msection_msids);
7328 if (transceiver_msids != msection_msids)
7329 return true;
7330 }
7331
7332 // 4.2.2 If description is of type "offer", and the direction of the
7333 // associated m= section in neither connection.[[CurrentLocalDescription]]
7334 // nor connection.[[CurrentRemoteDescription]] matches
7335 // transceiver.[[Direction]], return true.
7336 if (description->GetType() == SdpType::kOffer) {
7337 if (!current_remote_description())
7338 return true;
7339
7340 if (!current_remote_msection)
7341 return true;
7342
7343 RtpTransceiverDirection current_local_direction =
7344 current_local_media_description->direction();
7345 RtpTransceiverDirection current_remote_direction =
7346 current_remote_msection->media_description()->direction();
7347 if (transceiver->direction() != current_local_direction &&
7348 transceiver->direction() !=
7349 RtpTransceiverDirectionReversed(current_remote_direction)) {
7350 return true;
7351 }
7352 }
7353
7354 // 4.2.3 If description is of type "answer", and the direction of the
7355 // associated m= section in the description does not match
7356 // transceiver.[[Direction]] intersected with the offered direction (as
7357 // described in [JSEP] (section 5.3.1.)), return true.
7358 if (description->GetType() == SdpType::kAnswer) {
7359 if (!remote_description())
7360 return true;
7361
7362 const ContentInfo* offered_remote_msection =
7363 FindTransceiverMSection(transceiver.get(), remote_description());
7364
7365 RtpTransceiverDirection offered_direction =
7366 offered_remote_msection
7367 ? offered_remote_msection->media_description()->direction()
7368 : RtpTransceiverDirection::kInactive;
7369
7370 if (current_local_media_description->direction() !=
7371 (RtpTransceiverDirectionIntersection(
7372 transceiver->direction(),
7373 RtpTransceiverDirectionReversed(offered_direction)))) {
7374 return true;
7375 }
7376 }
7377 }
7378
7379 // If all the preceding checks were performed and true was not returned,
7380 // nothing remains to be negotiated; return false.
7381 return false;
7382}
7383
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007384} // namespace webrtc