blob: 0b7c9c8c63a0a53f1ead05032ae2b35bc0e482c8 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020028#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070029#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "logging/rtc_event_log/ice_logger.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070062#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080073using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080074using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080075using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080078using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070079using cricket::RELAY_PORT_TYPE;
80using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080081
Steve Antonba818672017-11-06 10:21:57 -080082namespace webrtc {
83
Steve Anton75737c02017-11-06 10:37:17 -080084// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080088const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080096const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
Steve Anton75737c02017-11-06 10:37:17 -0800108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800110// UMA metric names.
111const char kSimulcastVersionApplyLocalDescription[] =
112 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
113const char kSimulcastVersionApplyRemoteDescription[] =
114 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
115const char kSimulcastNumberOfEncodings[] =
116 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
117const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
118
Seth Hampson845e8782018-03-02 11:34:10 -0800119static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800120static const char kDefaultAudioSenderId[] = "defaulta0";
121static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700122
zhihuang8f65cdf2016-05-06 18:40:30 -0700123// The length of RTCP CNAMEs.
124static const int kRtcpCnameLength = 16;
125
Steve Antonad182762018-09-05 20:22:40 +0000126enum {
127 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
128 MSG_SET_SESSIONDESCRIPTION_FAILED,
129 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
130 MSG_GETSTATS,
131 MSG_FREE_DATACHANNELS,
132 MSG_REPORT_USAGE_PATTERN,
133};
134
Harald Alvestrand19793842018-06-25 12:03:50 +0200135static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
136
Steve Antonad182762018-09-05 20:22:40 +0000137struct SetSessionDescriptionMsg : public rtc::MessageData {
138 explicit SetSessionDescriptionMsg(
139 webrtc::SetSessionDescriptionObserver* observer)
140 : observer(observer) {}
141
142 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
143 RTCError error;
144};
145
146struct CreateSessionDescriptionMsg : public rtc::MessageData {
147 explicit CreateSessionDescriptionMsg(
148 webrtc::CreateSessionDescriptionObserver* observer)
149 : observer(observer) {}
150
151 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
152 RTCError error;
153};
154
155struct GetStatsMsg : public rtc::MessageData {
156 GetStatsMsg(webrtc::StatsObserver* observer,
157 webrtc::MediaStreamTrackInterface* track)
158 : observer(observer), track(track) {}
159 rtc::scoped_refptr<webrtc::StatsObserver> observer;
160 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
161};
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163// Check if we can send |new_stream| on a PeerConnection.
164bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
165 webrtc::MediaStreamInterface* new_stream) {
166 if (!new_stream || !current_streams) {
167 return false;
168 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700169 if (current_streams->find(new_stream->id()) != nullptr) {
170 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100171 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700172 return false;
173 }
174 return true;
175}
176
deadbeef5e97fb52015-10-15 12:49:08 -0700177// If the direction is "recvonly" or "inactive", treat the description
178// as containing no streams.
179// See: https://code.google.com/p/webrtc/issues/detail?id=5054
180std::vector<cricket::StreamParams> GetActiveStreams(
181 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800182 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700183 ? desc->streams()
184 : std::vector<cricket::StreamParams>();
185}
186
deadbeefab9b2d12015-10-14 11:33:11 -0700187bool IsValidOfferToReceiveMedia(int value) {
188 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
189 return (value >= Options::kUndefined) &&
190 (value <= Options::kMaxOfferToReceiveMedia);
191}
192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800194void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700195 const std::vector<rtc::scoped_refptr<
196 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700197 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200198 cricket::MediaDescriptionOptions* video_media_description_options,
199 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700200 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700201 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
202 if (audio_media_description_options) {
203 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700204 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700205 }
206 } else {
207 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
208 if (video_media_description_options) {
209 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800210 sender->id(), sender->internal()->stream_ids(), {},
211 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700212 }
213 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700214 }
zhihuang1c378ed2017-08-17 14:10:50 -0700215}
olka3c747662017-08-17 06:50:32 -0700216
zhihuang1c378ed2017-08-17 14:10:50 -0700217// Add options to |session_options| from |rtp_data_channels|.
218void AddRtpDataChannelOptions(
219 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
220 rtp_data_channels,
221 cricket::MediaDescriptionOptions* data_media_description_options) {
222 if (!data_media_description_options) {
223 return;
224 }
deadbeefab9b2d12015-10-14 11:33:11 -0700225 // Check for data channels.
226 for (const auto& kv : rtp_data_channels) {
227 const DataChannel* channel = kv.second;
228 if (channel->state() == DataChannel::kConnecting ||
229 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700230 // Legacy RTP data channels are signaled with the track/stream ID set to
231 // the data channel's label.
232 data_media_description_options->AddRtpDataChannel(channel->label(),
233 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700234 }
235 }
236}
237
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238uint32_t ConvertIceTransportTypeToCandidateFilter(
239 PeerConnectionInterface::IceTransportsType type) {
240 switch (type) {
241 case PeerConnectionInterface::kNone:
242 return cricket::CF_NONE;
243 case PeerConnectionInterface::kRelay:
244 return cricket::CF_RELAY;
245 case PeerConnectionInterface::kNoHost:
246 return (cricket::CF_ALL & ~cricket::CF_HOST);
247 case PeerConnectionInterface::kAll:
248 return cricket::CF_ALL;
249 default:
nissec80e7412017-01-11 05:56:46 -0800250 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700251 }
252 return cricket::CF_NONE;
253}
254
deadbeef293e9262017-01-11 12:28:30 -0800255// Helper to set an error and return from a method.
256bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
257 if (error) {
258 error->set_type(type);
259 }
260 return type == webrtc::RTCErrorType::NONE;
261}
262
Steve Anton038834f2017-07-14 15:59:59 -0700263bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700264 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700265 if (error_out) {
266 *error_out = std::move(error);
267 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700269}
270
Steve Antonba818672017-11-06 10:21:57 -0800271std::string GetSignalingStateString(
272 PeerConnectionInterface::SignalingState state) {
273 switch (state) {
274 case PeerConnectionInterface::kStable:
275 return "kStable";
276 case PeerConnectionInterface::kHaveLocalOffer:
277 return "kHaveLocalOffer";
278 case PeerConnectionInterface::kHaveLocalPrAnswer:
279 return "kHavePrAnswer";
280 case PeerConnectionInterface::kHaveRemoteOffer:
281 return "kHaveRemoteOffer";
282 case PeerConnectionInterface::kHaveRemotePrAnswer:
283 return "kHaveRemotePrAnswer";
284 case PeerConnectionInterface::kClosed:
285 return "kClosed";
286 }
287 RTC_NOTREACHED();
288 return "";
289}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290
Steve Anton75737c02017-11-06 10:37:17 -0800291IceCandidatePairType GetIceCandidatePairCounter(
292 const cricket::Candidate& local,
293 const cricket::Candidate& remote) {
294 const auto& l = local.type();
295 const auto& r = remote.type();
296 const auto& host = LOCAL_PORT_TYPE;
297 const auto& srflx = STUN_PORT_TYPE;
298 const auto& relay = RELAY_PORT_TYPE;
299 const auto& prflx = PRFLX_PORT_TYPE;
300 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800301 bool local_hostname =
302 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
303 bool remote_hostname = !remote.address().hostname().empty() &&
304 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800305 bool local_private = IPIsPrivate(local.address().ipaddr());
306 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800307 if (local_hostname) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostNameHostName;
310 } else if (remote_private) {
311 return kIceCandidatePairHostNameHostPrivate;
312 } else {
313 return kIceCandidatePairHostNameHostPublic;
314 }
315 } else if (local_private) {
316 if (remote_hostname) {
317 return kIceCandidatePairHostPrivateHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPrivateHostPrivate;
320 } else {
321 return kIceCandidatePairHostPrivateHostPublic;
322 }
323 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800324 if (remote_hostname) {
325 return kIceCandidatePairHostPublicHostName;
326 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800327 return kIceCandidatePairHostPublicHostPrivate;
328 } else {
329 return kIceCandidatePairHostPublicHostPublic;
330 }
331 }
332 }
333 if (l == host && r == srflx)
334 return kIceCandidatePairHostSrflx;
335 if (l == host && r == relay)
336 return kIceCandidatePairHostRelay;
337 if (l == host && r == prflx)
338 return kIceCandidatePairHostPrflx;
339 if (l == srflx && r == host)
340 return kIceCandidatePairSrflxHost;
341 if (l == srflx && r == srflx)
342 return kIceCandidatePairSrflxSrflx;
343 if (l == srflx && r == relay)
344 return kIceCandidatePairSrflxRelay;
345 if (l == srflx && r == prflx)
346 return kIceCandidatePairSrflxPrflx;
347 if (l == relay && r == host)
348 return kIceCandidatePairRelayHost;
349 if (l == relay && r == srflx)
350 return kIceCandidatePairRelaySrflx;
351 if (l == relay && r == relay)
352 return kIceCandidatePairRelayRelay;
353 if (l == relay && r == prflx)
354 return kIceCandidatePairRelayPrflx;
355 if (l == prflx && r == host)
356 return kIceCandidatePairPrflxHost;
357 if (l == prflx && r == srflx)
358 return kIceCandidatePairPrflxSrflx;
359 if (l == prflx && r == relay)
360 return kIceCandidatePairPrflxRelay;
361 return kIceCandidatePairMax;
362}
363
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800364// Logic to decide if an m= section can be recycled. This means that the new
365// m= section is not rejected, but the old local or remote m= section is
366// rejected. |old_content_one| and |old_content_two| refer to the m= section
367// of the old remote and old local descriptions in no particular order.
368// We need to check both the old local and remote because either
369// could be the most current from the latest negotation.
370bool IsMediaSectionBeingRecycled(SdpType type,
371 const ContentInfo& content,
372 const ContentInfo* old_content_one,
373 const ContentInfo* old_content_two) {
374 return type == SdpType::kOffer && !content.rejected &&
375 ((old_content_one && old_content_one->rejected) ||
376 (old_content_two && old_content_two->rejected));
377}
378
Steve Anton75737c02017-11-06 10:37:17 -0800379// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380// |current_desc|. The number of m= sections in |new_desc| should be no
381// less than |current_desc|. In the case of checking an answer's
382// |new_desc|, the |current_desc| is the last offer that was set as the
383// local or remote. In the case of checking an offer's |new_desc| we
384// check against the local and remote descriptions stored from the last
385// negotiation, because either of these could be the most up to date for
386// possible rejected m sections. These are the |current_desc| and
387// |secondary_current_desc|.
388bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
389 const SessionDescription* secondary_current_desc,
390 const SessionDescription& new_desc,
391 const SdpType type) {
392 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800393 return false;
394 }
395
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
397 const cricket::ContentInfo* secondary_content_info = nullptr;
398 if (secondary_current_desc &&
399 i < secondary_current_desc->contents().size()) {
400 secondary_content_info = &secondary_current_desc->contents()[i];
401 }
402 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
403 &current_desc.contents()[i],
404 secondary_content_info)) {
405 // For new offer descriptions, if the media section can be recycled, it's
406 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800407 continue;
408 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800409 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800410 return false;
411 }
412 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 new_desc.contents()[i].media_description();
414 const MediaContentDescription* current_desc_mdesc =
415 current_desc.contents()[i].media_description();
416 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800417 return false;
418 }
419 }
420 return true;
421}
422
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800423bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
424 const SessionDescription& desc2) {
425 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800426}
427
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700428void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
429 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200430 // Array of structs needed to map {KeyExchangeProtocolType,
431 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
432 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
433 static constexpr struct {
434 KeyExchangeProtocolType protocol_type;
435 cricket::MediaType media_type;
436 KeyExchangeProtocolMedia protocol_media;
437 } kEnumCounterKeyProtocolMediaMap[] = {
438 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
439 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
440 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
441 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
443 kEnumCounterKeyProtocolMediaTypeDtlsData},
444 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
445 kEnumCounterKeyProtocolMediaTypeSdesAudio},
446 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
447 kEnumCounterKeyProtocolMediaTypeSdesVideo},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
449 kEnumCounterKeyProtocolMediaTypeSdesData},
450 };
451
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
453 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100454
Mirko Bonadeiab499822018-09-11 10:43:20 +0200455 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
456 if (i.protocol_type == protocol_type && i.media_type == media_type) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
458 i.protocol_media,
459 kEnumCounterKeyProtocolMediaTypeMax);
460 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100461 }
462}
463
Harald Alvestrand76829d72018-07-18 23:24:36 +0200464void NoteAddIceCandidateResult(int result) {
465 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
466 kAddIceCandidateMax);
467}
468
Steve Anton75737c02017-11-06 10:37:17 -0800469// Checks that each non-rejected content has SDES crypto keys or a DTLS
470// fingerprint, unless it's in a BUNDLE group, in which case only the
471// BUNDLE-tag section (first media section/description in the BUNDLE group)
472// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
473// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
474// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700475RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100482 // Note what media is used with each crypto protocol, for all sections.
483 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
484 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700485 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800486 const std::string& mid = content_info.name;
487 if (bundle && bundle->HasContentName(mid) &&
488 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800489 // This isn't the first media section in the BUNDLE group, so it's not
490 // required to have crypto attributes, since only the crypto attributes
491 // from the first section actually get used.
492 continue;
493 }
494
495 // If the content isn't rejected or bundled into another m= section, crypto
496 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800498 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800499 if (!media || !tinfo) {
500 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 if (dtls_enabled) {
504 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
506 << "Session description must have DTLS fingerprint if "
507 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800508 return RTCError(RTCErrorType::INVALID_PARAMETER,
509 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800510 }
511 } else {
512 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100513 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800514 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800515 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800516 }
517 }
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800520}
521
522// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
523// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
524// media section/description in the BUNDLE group) needs a ufrag and pwd.
525bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
526 const cricket::ContentGroup* bundle =
527 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800528 for (const cricket::ContentInfo& content_info : desc->contents()) {
529 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800530 continue;
531 }
Steve Anton8a006912017-12-04 15:25:56 -0800532 const std::string& mid = content_info.name;
533 if (bundle && bundle->HasContentName(mid) &&
534 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800535 // This isn't the first media section in the BUNDLE group, so it's not
536 // required to have ufrag/password, since only the ufrag/password from
537 // the first section actually get used.
538 continue;
539 }
540
541 // If the content isn't rejected or bundled into another m= section,
542 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800543 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800544 if (!tinfo) {
545 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800547 return false;
548 }
549 if (tinfo->description.ice_ufrag.empty() ||
550 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100551 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800552 return false;
553 }
554 }
555 return true;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
559bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
560 const SessionDescriptionInterface* new_desc,
561 const std::string& content_name) {
562 if (!old_desc) {
563 return false;
564 }
565 const SessionDescription* new_sd = new_desc->description();
566 const SessionDescription* old_sd = old_desc->description();
567 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
568 if (!cinfo || cinfo->rejected) {
569 return false;
570 }
571 // If the content isn't rejected, check if ufrag and password has changed.
572 const cricket::TransportDescription* new_transport_desc =
573 new_sd->GetTransportDescriptionByName(content_name);
574 const cricket::TransportDescription* old_transport_desc =
575 old_sd->GetTransportDescriptionByName(content_name);
576 if (!new_transport_desc || !old_transport_desc) {
577 // No transport description exists. This is not an ICE restart.
578 return false;
579 }
580 if (cricket::IceCredentialsChanged(
581 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
582 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-16 17:08:42 -0800590// Generates a string error message for SetLocalDescription/SetRemoteDescription
591// from an RTCError.
592std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
593 SdpType type,
594 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200595 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800596 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
597 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200598 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800599}
600
Seth Hampson5b4f0752018-04-02 16:31:36 -0700601std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
602 std::string output = "streams=[";
603 const char* separator = "";
604 for (const auto& stream_id : stream_ids) {
605 output.append(separator).append(stream_id);
606 separator = ", ";
607 }
608 output.append("]");
609 return output;
610}
611
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 }
618 return rtc_configuration_parameter;
619}
620
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800621cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
622 switch (type) {
623 case DataMessageType::kText:
624 return cricket::DMT_TEXT;
625 case DataMessageType::kBinary:
626 return cricket::DMT_BINARY;
627 case DataMessageType::kControl:
628 return cricket::DMT_CONTROL;
629 default:
630 return cricket::DMT_NONE;
631 }
632 return cricket::DMT_NONE;
633}
634
635DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
636 switch (type) {
637 case cricket::DMT_TEXT:
638 return DataMessageType::kText;
639 case cricket::DMT_BINARY:
640 return DataMessageType::kBinary;
641 case cricket::DMT_CONTROL:
642 return DataMessageType::kControl;
643 case cricket::DMT_NONE:
644 default:
645 RTC_NOTREACHED();
646 }
647 return DataMessageType::kControl;
648}
649
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800650void ReportSimulcastApiVersion(const char* name,
651 const SessionDescription& session) {
652 bool has_legacy = false;
653 bool has_spec_compliant = false;
654 for (const ContentInfo& content : session.contents()) {
655 if (!content.description) {
656 continue;
657 }
658 has_spec_compliant |= content.description->HasSimulcast();
659 for (const StreamParams& sp : content.description->streams()) {
660 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
661 }
662 }
663
664 if (has_legacy) {
665 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
666 kSimulcastApiVersionMax);
667 }
668 if (has_spec_compliant) {
669 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
670 kSimulcastApiVersionMax);
671 }
672 if (!has_legacy && !has_spec_compliant) {
673 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
674 kSimulcastApiVersionMax);
675 }
676}
677
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200678const ContentInfo* FindTransceiverMSection(
679 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
680 const SessionDescriptionInterface* session_description) {
681 return transceiver->mid()
682 ? session_description->description()->GetContentByName(
683 *transceiver->mid())
684 : nullptr;
685}
686
Steve Anton75737c02017-11-06 10:37:17 -0800687} // namespace
688
Henrik Boström31638672017-11-23 17:48:32 +0100689// Upon completion, posts a task to execute the callback of the
690// SetSessionDescriptionObserver asynchronously on the same thread. At this
691// point, the state of the peer connection might no longer reflect the effects
692// of the SetRemoteDescription operation, as the peer connection could have been
693// modified during the post.
694// TODO(hbos): Remove this class once we remove the version of
695// PeerConnectionInterface::SetRemoteDescription() that takes a
696// SetSessionDescriptionObserver as an argument.
697class PeerConnection::SetRemoteDescriptionObserverAdapter
698 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
699 public:
700 SetRemoteDescriptionObserverAdapter(
701 rtc::scoped_refptr<PeerConnection> pc,
702 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
703 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
704
705 // SetRemoteDescriptionObserverInterface implementation.
706 void OnSetRemoteDescriptionComplete(RTCError error) override {
707 if (error.ok())
708 pc_->PostSetSessionDescriptionSuccess(wrapper_);
709 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100710 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100711 }
712
713 private:
714 rtc::scoped_refptr<PeerConnection> pc_;
715 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
716};
717
deadbeef293e9262017-01-11 12:28:30 -0800718bool PeerConnectionInterface::RTCConfiguration::operator==(
719 const PeerConnectionInterface::RTCConfiguration& o) const {
720 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700721 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800722 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000723 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700724 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800725 BundlePolicy bundle_policy;
726 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700727 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
728 int ice_candidate_pool_size;
729 bool disable_ipv6;
730 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700731 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100732 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200734 absl::optional<int> screencast_min_bitrate;
735 absl::optional<bool> combined_audio_video_bwe;
736 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800737 TcpCandidatePolicy tcp_candidate_policy;
738 CandidateNetworkPolicy candidate_network_policy;
739 int audio_jitter_buffer_max_packets;
740 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100741 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100742 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800743 int ice_connection_receiving_timeout;
744 int ice_backup_candidate_pair_ping_interval;
745 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800746 bool prioritize_most_likely_ice_candidate_pairs;
747 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800748 bool prune_turn_ports;
749 bool presume_writable_when_fully_relayed;
750 bool enable_ice_renomination;
751 bool redetermine_role_on_ice_restart;
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);
Steve Anton06817cd2018-12-18 15:55:30 -08002438 const cricket::ContentInfos& local_contents =
2439 (local_description() ? local_description()->description()->contents()
2440 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002441 const cricket::ContentInfos& remote_contents =
2442 (remote_description() ? remote_description()->description()->contents()
2443 : cricket::ContentInfos());
2444 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2445 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002446 if (!content.name.empty()) {
2447 continue;
2448 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002449 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002450 absl::string_view source_explanation;
2451 if (IsUnifiedPlan()) {
2452 if (i < local_contents.size()) {
2453 new_mid = local_contents[i].name;
2454 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002455 } else if (i < remote_contents.size()) {
2456 new_mid = remote_contents[i].name;
2457 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002458 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002459 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002460 source_explanation = "generated just now";
2461 }
2462 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002463 new_mid = std::string(
2464 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002465 source_explanation = "to match pre-existing behavior";
2466 }
Steve Antond7180cc2019-02-07 10:44:53 -08002467 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002468 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002469 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002470 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2471 << " is missing an a=mid line. Filling in the value '"
2472 << new_mid << "' " << source_explanation << ".";
2473 }
2474}
2475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002476void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002477 SetSessionDescriptionObserver* observer,
2478 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002479 SetRemoteDescription(
2480 std::unique_ptr<SessionDescriptionInterface>(desc),
2481 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2482 new SetRemoteDescriptionObserverAdapter(this, observer)));
2483}
2484
2485void PeerConnection::SetRemoteDescription(
2486 std::unique_ptr<SessionDescriptionInterface> desc,
2487 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002488 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002489 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002490
nisse7ce109a2017-01-31 00:57:56 -08002491 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002492 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 return;
2494 }
Steve Anton8a006912017-12-04 15:25:56 -08002495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002496 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002497 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002498 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002499 return;
2500 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002501
Steve Anton80dd7b52018-02-16 17:08:42 -08002502 // If a session error has occurred the PeerConnection is in a possibly
2503 // inconsistent state so fail right away.
2504 if (session_error() != SessionError::kNone) {
2505 std::string error_message = GetSessionErrorMsg();
2506 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2507 observer->OnSetRemoteDescriptionComplete(
2508 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2509 return;
2510 }
Steve Anton71439a62018-02-15 11:53:06 -08002511
Steve Antonba42e992018-04-09 14:10:01 -07002512 if (desc->GetType() == SdpType::kOffer) {
2513 // Report to UMA the format of the received offer.
2514 ReportSdpFormatReceived(*desc);
2515 }
2516
Steve Anton06817cd2018-12-18 15:55:30 -08002517 // Handle remote descriptions missing a=mid lines for interop with legacy end
2518 // points.
2519 FillInMissingRemoteMids(desc->description());
2520
Steve Anton80dd7b52018-02-16 17:08:42 -08002521 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002522 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002523 std::string error_message = GetSetDescriptionErrorMessage(
2524 cricket::CS_REMOTE, desc->GetType(), error);
2525 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002526 observer->OnSetRemoteDescriptionComplete(
2527 RTCError(error.type(), std::move(error_message)));
2528 return;
2529 }
Steve Anton71439a62018-02-15 11:53:06 -08002530
Steve Anton80dd7b52018-02-16 17:08:42 -08002531 // Grab the description type before moving ownership to
2532 // ApplyRemoteDescription, which may destroy it before returning.
2533 const SdpType type = desc->GetType();
2534
2535 error = ApplyRemoteDescription(std::move(desc));
2536 // |desc| may be destroyed at this point.
2537
2538 if (!error.ok()) {
2539 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2540 // inconsistent state, so act conservatively here and set the session error
2541 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2542 SetSessionError(SessionError::kContent, error.message());
2543 std::string error_message =
2544 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2545 RTC_LOG(LS_ERROR) << error_message;
2546 observer->OnSetRemoteDescriptionComplete(
2547 RTCError(error.type(), std::move(error_message)));
2548 return;
2549 }
2550 RTC_DCHECK(remote_description());
2551
2552 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002553 // TODO(deadbeef): We already had to hop to the network thread for
2554 // MaybeStartGathering...
2555 network_thread()->Invoke<void>(
2556 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2557 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002558 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002559 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002560 }
2561
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002562 if (IsUnifiedPlan()) {
2563 bool was_negotiation_needed = is_negotiation_needed_;
2564 UpdateNegotiationNeeded();
2565 if (signaling_state() == kStable && was_negotiation_needed &&
2566 is_negotiation_needed_) {
2567 Observer()->OnRenegotiationNeeded();
2568 }
2569 }
2570
Steve Anton8a006912017-12-04 15:25:56 -08002571 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002572 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002573}
2574
2575RTCError PeerConnection::ApplyRemoteDescription(
2576 std::unique_ptr<SessionDescriptionInterface> desc) {
2577 RTC_DCHECK_RUN_ON(signaling_thread());
2578 RTC_DCHECK(desc);
2579
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002580 // Update stats here so that we have the most recent stats for tracks and
2581 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002582 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002583
Steve Antondcc3c022017-12-22 16:02:54 -08002584 // Take a reference to the old remote description since it's used below to
2585 // compare against the new remote description. When setting the new remote
2586 // description, grab ownership of the replaced session description in case it
2587 // is the same as |old_remote_description|, to keep it alive for the duration
2588 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002589 const SessionDescriptionInterface* old_remote_description =
2590 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002591 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002592 SdpType type = desc->GetType();
2593 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002594 replaced_remote_description = pending_remote_description_
2595 ? std::move(pending_remote_description_)
2596 : std::move(current_remote_description_);
2597 current_remote_description_ = std::move(desc);
2598 pending_remote_description_ = nullptr;
2599 current_local_description_ = std::move(pending_local_description_);
2600 } else {
2601 replaced_remote_description = std::move(pending_remote_description_);
2602 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002603 }
Steve Anton8a006912017-12-04 15:25:56 -08002604 // The session description to apply now must be accessed by
2605 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002606 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002607
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002608 // Report statistics about any use of simulcast.
2609 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2610 *remote_description()->description());
2611
Zhi Huange830e682018-03-30 10:48:35 -07002612 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2613 if (!error.ok()) {
2614 return error;
2615 }
Steve Anton8a006912017-12-04 15:25:56 -08002616 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002617 if (IsUnifiedPlan()) {
2618 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002619 cricket::CS_REMOTE, *remote_description(), local_description(),
2620 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002621 if (!error.ok()) {
2622 return error;
2623 }
Steve Antondcc3c022017-12-22 16:02:54 -08002624 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002625 // Media channels will be created only when offer is set. These may use new
2626 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002627 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002628 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002629 // description is applied. Restore back to old description.
2630 RTCError error = CreateChannels(*remote_description()->description());
2631 if (!error.ok()) {
2632 return error;
2633 }
2634 }
Steve Antondcc3c022017-12-22 16:02:54 -08002635 // Remove unused channels if MediaContentDescription is rejected.
2636 RemoveUnusedChannels(remote_description()->description());
2637 }
Steve Anton8a006912017-12-04 15:25:56 -08002638
Zhi Huange830e682018-03-30 10:48:35 -07002639 // NOTE: Candidates allocation will be initiated only when
2640 // SetLocalDescription is called.
2641 error = UpdateSessionState(type, cricket::CS_REMOTE,
2642 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002643 if (!error.ok()) {
2644 return error;
2645 }
2646
2647 if (local_description() &&
2648 !UseCandidatesInSessionDescription(remote_description())) {
2649 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2650 }
2651
2652 if (old_remote_description) {
2653 for (const cricket::ContentInfo& content :
2654 old_remote_description->description()->contents()) {
2655 // Check if this new SessionDescription contains new ICE ufrag and
2656 // password that indicates the remote peer requests an ICE restart.
2657 // TODO(deadbeef): When we start storing both the current and pending
2658 // remote description, this should reset pending_ice_restarts and compare
2659 // against the current description.
2660 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2661 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002662 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002663 pending_ice_restarts_.insert(content.name);
2664 }
2665 } else {
2666 // We retain all received candidates only if ICE is not restarted.
2667 // When ICE is restarted, all previous candidates belong to an old
2668 // generation and should not be kept.
2669 // TODO(deadbeef): This goes against the W3C spec which says the remote
2670 // description should only contain candidates from the last set remote
2671 // description plus any candidates added since then. We should remove
2672 // this once we're sure it won't break anything.
2673 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2674 old_remote_description, content.name, mutable_remote_description());
2675 }
2676 }
2677 }
2678
2679 if (session_error() != SessionError::kNone) {
2680 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2681 }
2682
2683 // Set the the ICE connection state to connecting since the connection may
2684 // become writable with peer reflexive candidates before any remote candidate
2685 // is signaled.
2686 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2687 // is to have a new signal the indicates a change in checking state from the
2688 // transport and expose a new checking() member from transport that can be
2689 // read to determine the current checking state. The existing SignalConnecting
2690 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002691 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002692 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002693 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2694 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2695 }
2696
deadbeefab9b2d12015-10-14 11:33:11 -07002697 // If setting the description decided our SSL role, allocate any necessary
2698 // SCTP sids.
2699 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002700 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002701 AllocateSctpSids(role);
2702 }
2703
Steve Antondcc3c022017-12-22 16:02:54 -08002704 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002705 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002706 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002707 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002708 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002709 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002710 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002711 const ContentInfo* content =
2712 FindMediaSectionForTransceiver(transceiver, remote_description());
2713 if (!content) {
2714 continue;
2715 }
2716 const MediaContentDescription* media_desc = content->media_description();
2717 RtpTransceiverDirection local_direction =
2718 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002719 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2720 // RTCSessionDescription: Set the associated remote streams given
2721 // transceiver.[[Receiver]], msids, addList, and removeList".
2722 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2723 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2724 std::vector<std::string> stream_ids;
2725 if (!media_desc->streams().empty()) {
2726 // The remote description has signaled the stream IDs.
2727 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002728 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002729 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2730 << " (" << GetStreamIdsString(stream_ids) << ").";
2731 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2732 stream_ids, &added_streams,
2733 &removed_streams);
2734 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2735 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2736 // and transceiver's current direction is neither sendrecv nor recvonly,
2737 // process the addition of a remote track for the media description.
2738 if (!transceiver->fired_direction() ||
2739 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2740 RTC_LOG(LS_INFO)
2741 << "Processing the addition of a remote track for MID="
2742 << content->name << ".";
2743 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002744 }
Steve Antondcc3c022017-12-22 16:02:54 -08002745 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002746 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002747 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2748 // removal of a remote track for the media description, given transceiver,
2749 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002750 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002751 (transceiver->fired_direction() &&
2752 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2753 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2754 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002755 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002756 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002757 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002758 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002759 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002760 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002761 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002762 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002763 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002764 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2765 if (transceiver->mid()) {
2766 auto dtls_transport =
2767 LookupDtlsTransportByMidInternal(*transceiver->mid());
2768 transceiver->internal()->sender_internal()->set_transport(
2769 dtls_transport);
2770 transceiver->internal()->receiver_internal()->set_transport(
2771 dtls_transport);
2772 }
Steve Antondcc3c022017-12-22 16:02:54 -08002773 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002774 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002775 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002776 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002777 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2778 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002779 transceiver->Stop();
2780 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002781 if (!content->rejected &&
2782 RtpTransceiverDirectionHasRecv(local_direction)) {
2783 // Set ssrc to 0 in the case of an unsignalled ssrc.
2784 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002785 if (!media_desc->streams().empty() &&
2786 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002787 ssrc = media_desc->streams()[0].first_ssrc();
2788 }
2789 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002790 }
Steve Antondcc3c022017-12-22 16:02:54 -08002791 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002792 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002793 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002794 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002795 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002796 observer->OnTrack(transceiver);
2797 observer->OnAddTrack(transceiver->receiver(),
2798 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002799 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002800 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002801 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002802 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002803 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002804 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002805 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002806 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002807 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002808 }
Steve Antondcc3c022017-12-22 16:02:54 -08002809 }
2810
Henrik Boströmfdb92012017-11-09 19:55:44 +01002811 const cricket::ContentInfo* audio_content =
2812 GetFirstAudioContent(remote_description()->description());
2813 const cricket::ContentInfo* video_content =
2814 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002815 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002816 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002817 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002818 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002819 const cricket::RtpDataContentDescription* rtp_data_desc =
2820 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002821
2822 // Check if the descriptions include streams, just in case the peer supports
2823 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002824 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002825 (audio_desc && !audio_desc->streams().empty()) ||
2826 (video_desc && !video_desc->streams().empty())) {
2827 remote_peer_supports_msid_ = true;
2828 }
deadbeefab9b2d12015-10-14 11:33:11 -07002829
2830 // We wait to signal new streams until we finish processing the description,
2831 // since only at that point will new streams have all their tracks.
2832 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2833
Steve Antondcc3c022017-12-22 16:02:54 -08002834 if (!IsUnifiedPlan()) {
2835 // TODO(steveanton): When removing RTP senders/receivers in response to a
2836 // rejected media section, there is some cleanup logic that expects the
2837 // voice/ video channel to still be set. But in this method the voice/video
2838 // channel would have been destroyed by the SetRemoteDescription caller
2839 // above so the cleanup that relies on them fails to run. The RemoveSenders
2840 // calls should be moved to right before the DestroyChannel calls to fix
2841 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002842
Steve Antondcc3c022017-12-22 16:02:54 -08002843 // Find all audio rtp streams and create corresponding remote AudioTracks
2844 // and MediaStreams.
2845 if (audio_content) {
2846 if (audio_content->rejected) {
2847 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2848 } else {
2849 bool default_audio_track_needed =
2850 !remote_peer_supports_msid_ &&
2851 RtpTransceiverDirectionHasSend(audio_desc->direction());
2852 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2853 default_audio_track_needed, audio_desc->type(),
2854 new_streams);
2855 }
deadbeeffaac4972015-11-12 15:33:07 -08002856 }
deadbeefab9b2d12015-10-14 11:33:11 -07002857
Steve Antondcc3c022017-12-22 16:02:54 -08002858 // Find all video rtp streams and create corresponding remote VideoTracks
2859 // and MediaStreams.
2860 if (video_content) {
2861 if (video_content->rejected) {
2862 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2863 } else {
2864 bool default_video_track_needed =
2865 !remote_peer_supports_msid_ &&
2866 RtpTransceiverDirectionHasSend(video_desc->direction());
2867 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2868 default_video_track_needed, video_desc->type(),
2869 new_streams);
2870 }
deadbeeffaac4972015-11-12 15:33:07 -08002871 }
deadbeefab9b2d12015-10-14 11:33:11 -07002872
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002873 // If this is an RTP data transport, update the DataChannels with the
2874 // information from the remote peer.
2875 if (rtp_data_desc) {
2876 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002877 }
deadbeefab9b2d12015-10-14 11:33:11 -07002878
Steve Antondcc3c022017-12-22 16:02:54 -08002879 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002880 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002881 for (size_t i = 0; i < new_streams->count(); ++i) {
2882 MediaStreamInterface* new_stream = new_streams->at(i);
2883 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002884 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002885 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2886 }
deadbeefab9b2d12015-10-14 11:33:11 -07002887
Steve Antondcc3c022017-12-22 16:02:54 -08002888 UpdateEndedRemoteMediaStreams();
2889 }
deadbeefab9b2d12015-10-14 11:33:11 -07002890
Steve Anton8a006912017-12-04 15:25:56 -08002891 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002892}
2893
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002894void PeerConnection::SetAssociatedRemoteStreams(
2895 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2896 const std::vector<std::string>& stream_ids,
2897 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2898 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2899 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2900 for (const std::string& stream_id : stream_ids) {
2901 rtc::scoped_refptr<MediaStreamInterface> stream =
2902 remote_streams_->find(stream_id);
2903 if (!stream) {
2904 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2905 MediaStream::Create(stream_id));
2906 remote_streams_->AddStream(stream);
2907 added_streams->push_back(stream);
2908 }
2909 media_streams.push_back(stream);
2910 }
2911 // Special case: "a=msid" missing, use random stream ID.
2912 if (media_streams.empty() &&
2913 !(remote_description()->description()->msid_signaling() &
2914 cricket::kMsidSignalingMediaSection)) {
2915 if (!missing_msid_default_stream_) {
2916 missing_msid_default_stream_ = MediaStreamProxy::Create(
2917 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2918 added_streams->push_back(missing_msid_default_stream_);
2919 }
2920 media_streams.push_back(missing_msid_default_stream_);
2921 }
2922 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2923 receiver->streams();
2924 // SetStreams() will add/remove the receiver's track to/from the streams. This
2925 // differs from the spec - the spec uses an "addList" and "removeList" to
2926 // update the stream-track relationships in a later step. We do this earlier,
2927 // changing the order of things, but the end-result is the same.
2928 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2929 // instead. https://crbug.com/webrtc/9480
2930 receiver->SetStreams(media_streams);
2931 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2932}
2933
Steve Anton0f5400a2018-07-17 14:25:36 -07002934void PeerConnection::ProcessRemovalOfRemoteTrack(
2935 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2936 transceiver,
2937 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2938 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2939 RTC_DCHECK(transceiver->mid());
2940 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2941 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002942 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002943 transceiver->internal()->receiver_internal()->streams();
2944 // This will remove the remote track from the streams.
2945 transceiver->internal()->receiver_internal()->set_stream_ids({});
2946 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002947 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2948}
2949
2950void PeerConnection::RemoveRemoteStreamsIfEmpty(
2951 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2952 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2953 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2954 // streams, see if the stream was removed by checking if this was the last
2955 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002956 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002957 if (remote_stream->GetAudioTracks().empty() &&
2958 remote_stream->GetVideoTracks().empty()) {
2959 remote_streams_->RemoveStream(remote_stream);
2960 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002961 }
2962 }
2963}
2964
Steve Antondcc3c022017-12-22 16:02:54 -08002965RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2966 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002967 const SessionDescriptionInterface& new_session,
2968 const SessionDescriptionInterface* old_local_description,
2969 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002970 RTC_DCHECK(IsUnifiedPlan());
2971
Steve Anton7464fca2018-01-19 11:10:37 -08002972 const cricket::ContentGroup* bundle_group = nullptr;
2973 if (new_session.GetType() == SdpType::kOffer) {
2974 auto bundle_group_or_error =
2975 GetEarlyBundleGroup(*new_session.description());
2976 if (!bundle_group_or_error.ok()) {
2977 return bundle_group_or_error.MoveError();
2978 }
2979 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002980 }
Steve Antondcc3c022017-12-22 16:02:54 -08002981
Steve Antondcc3c022017-12-22 16:02:54 -08002982 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002983 for (size_t i = 0; i < new_contents.size(); ++i) {
2984 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002985 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002986 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002987 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2988 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002989 const cricket::ContentInfo* old_local_content = nullptr;
2990 if (old_local_description &&
2991 i < old_local_description->description()->contents().size()) {
2992 old_local_content =
2993 &old_local_description->description()->contents()[i];
2994 }
2995 const cricket::ContentInfo* old_remote_content = nullptr;
2996 if (old_remote_description &&
2997 i < old_remote_description->description()->contents().size()) {
2998 old_remote_content =
2999 &old_remote_description->description()->contents()[i];
3000 }
Steve Antondcc3c022017-12-22 16:02:54 -08003001 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003002 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3003 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003004 if (!transceiver_or_error.ok()) {
3005 return transceiver_or_error.MoveError();
3006 }
3007 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003008 RTCError error =
3009 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3010 if (!error.ok()) {
3011 return error;
3012 }
3013 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003014 if (GetDataMid() && new_content.name != *GetDataMid()) {
3015 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003016 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3017 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003018 continue;
3019 }
3020 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3021 if (!error.ok()) {
3022 return error;
3023 }
Steve Antondcc3c022017-12-22 16:02:54 -08003024 } else {
3025 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3026 "Unknown section type.");
3027 }
3028 }
3029
3030 return RTCError::OK();
3031}
3032
3033RTCError PeerConnection::UpdateTransceiverChannel(
3034 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3035 transceiver,
3036 const cricket::ContentInfo& content,
3037 const cricket::ContentGroup* bundle_group) {
3038 RTC_DCHECK(IsUnifiedPlan());
3039 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003040 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003041 if (content.rejected) {
3042 if (channel) {
3043 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003044 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003045 }
3046 } else {
3047 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003048 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003049 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003050 } else {
Steve Anton69470252018-02-09 11:43:08 -08003051 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003052 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003053 }
3054 if (!channel) {
3055 LOG_AND_RETURN_ERROR(
3056 RTCErrorType::INTERNAL_ERROR,
3057 "Failed to create channel for mid=" + content.name);
3058 }
3059 transceiver->internal()->SetChannel(channel);
3060 }
3061 }
3062 return RTCError::OK();
3063}
3064
Steve Antonfa2260d2017-12-28 16:38:23 -08003065RTCError PeerConnection::UpdateDataChannel(
3066 cricket::ContentSource source,
3067 const cricket::ContentInfo& content,
3068 const cricket::ContentGroup* bundle_group) {
3069 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003070 // If data channels are disabled, ignore this media section. CreateAnswer
3071 // will take care of rejecting it.
3072 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003073 }
3074 if (content.rejected) {
3075 DestroyDataChannel();
3076 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003077 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003078 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003079 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3080 "Failed to create data channel.");
3081 }
3082 }
3083 if (source == cricket::CS_REMOTE) {
3084 const MediaContentDescription* data_desc = content.media_description();
3085 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3086 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3087 }
3088 }
3089 }
3090 return RTCError::OK();
3091}
3092
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003093// This method will extract any send encodings that were sent by the remote
3094// connection. This is currently only relevant for Simulcast scenario (where
3095// the number of layers may be communicated by the server).
3096static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3097 const MediaContentDescription& desc) {
3098 if (!desc.HasSimulcast()) {
3099 return {};
3100 }
3101 std::vector<RtpEncodingParameters> result;
3102 const SimulcastDescription& simulcast = desc.simulcast_description();
3103
3104 // This is a remote description, the parameters we are after should appear
3105 // as receive streams.
3106 for (const auto& alternatives : simulcast.receive_layers()) {
3107 RTC_DCHECK(!alternatives.empty());
3108 // There is currently no way to specify or choose from alternatives.
3109 // We will always use the first alternative, which is the most preferred.
3110 const SimulcastLayer& layer = alternatives[0];
3111 RtpEncodingParameters parameters;
3112 parameters.rid = layer.rid;
3113 parameters.active = !layer.is_paused;
3114 result.push_back(parameters);
3115 }
3116
3117 return result;
3118}
3119
3120static RTCError UpdateSimulcastLayerStatusInSender(
3121 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003122 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003123 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003124 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003125 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003126
3127 // The simulcast envelope cannot be changed, only the status of the streams.
3128 // So we will iterate over the send encodings rather than the layers.
3129 for (RtpEncodingParameters& encoding : parameters.encodings) {
3130 auto iter = std::find_if(layers.begin(), layers.end(),
3131 [&encoding](const SimulcastLayer& layer) {
3132 return layer.rid == encoding.rid;
3133 });
3134 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003135 if (iter == layers.end()) {
3136 disabled_layers.push_back(encoding.rid);
3137 continue;
3138 }
3139
3140 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003141 }
3142
Amit Hilbuch619b2942019-02-26 15:55:19 -08003143 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003144 if (result.ok()) {
3145 result = sender->DisableEncodingLayers(disabled_layers);
3146 }
3147
3148 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003149}
3150
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003151static bool SimulcastIsRejected(
3152 const ContentInfo* local_content,
3153 const MediaContentDescription& answer_media_desc) {
3154 bool simulcast_offered = local_content &&
3155 local_content->media_description() &&
3156 local_content->media_description()->HasSimulcast();
3157 bool simulcast_answered = answer_media_desc.HasSimulcast();
3158 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3159 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3160 return simulcast_offered && (!simulcast_answered || !rids_supported);
3161}
3162
Amit Hilbuch2297d332019-02-19 12:49:22 -08003163static RTCError DisableSimulcastInSender(
3164 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003165 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003166 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003167 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003168 return RTCError::OK();
3169 }
3170
Amit Hilbuch2297d332019-02-19 12:49:22 -08003171 std::vector<std::string> disabled_layers;
3172 std::transform(
3173 parameters.encodings.begin() + 1, parameters.encodings.end(),
3174 std::back_inserter(disabled_layers),
3175 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3176 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003177}
3178
Steve Antondcc3c022017-12-22 16:02:54 -08003179RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3180PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003181 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003182 size_t mline_index,
3183 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003184 const ContentInfo* old_local_content,
3185 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003186 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003187 // If this is an offer then the m= section might be recycled. If the m=
3188 // section is being recycled (defined as: rejected in the current local or
3189 // remote description and not rejected in new description), dissociate the
3190 // currently associated RtpTransceiver by setting its mid property to null,
3191 // and discard the mapping between the transceiver and its m= section index.
3192 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3193 old_remote_content)) {
3194 // We want to dissociate the transceiver that has the rejected mid.
3195 const std::string& old_mid =
3196 (old_local_content && old_local_content->rejected)
3197 ? old_local_content->name
3198 : old_remote_content->name;
3199 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003200 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003201 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3202 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003203 old_transceiver->internal()->set_mid(absl::nullopt);
3204 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003205 }
3206 }
3207 const MediaContentDescription* media_desc = content.media_description();
3208 auto transceiver = GetAssociatedTransceiver(content.name);
3209 if (source == cricket::CS_LOCAL) {
3210 // Find the RtpTransceiver that corresponds to this m= section, using the
3211 // mapping between transceivers and m= section indices established when
3212 // creating the offer.
3213 if (!transceiver) {
3214 transceiver = GetTransceiverByMLineIndex(mline_index);
3215 }
3216 if (!transceiver) {
3217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3218 "Unknown transceiver");
3219 }
3220 } else {
3221 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3222 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3223 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003224 // When simulcast is requested, a transceiver cannot be associated because
3225 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003226 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003227 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3228 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003229 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3230 }
3231 // If no RtpTransceiver was found in the previous step, create one with a
3232 // recvonly direction.
3233 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003234 RTC_LOG(LS_INFO) << "Adding "
3235 << cricket::MediaTypeToString(media_desc->type())
3236 << " transceiver for MID=" << content.name
3237 << " at i=" << mline_index
3238 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003239 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003240 std::vector<RtpEncodingParameters> send_encodings =
3241 GetSendEncodingsFromRemoteDescription(*media_desc);
3242 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3243 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003244 std::string receiver_id;
3245 if (!media_desc->streams().empty()) {
3246 receiver_id = media_desc->streams()[0].id;
3247 } else {
3248 receiver_id = rtc::CreateRandomUuid();
3249 }
3250 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003251 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003252 transceiver->internal()->set_direction(
3253 RtpTransceiverDirection::kRecvOnly);
3254 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003255
3256 // Check if the offer indicated simulcast but the answer rejected it.
3257 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003258 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003259 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003260 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003261 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003262 if (!error.ok()) {
3263 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3264 return std::move(error);
3265 }
3266 }
Steve Antondcc3c022017-12-22 16:02:54 -08003267 }
3268 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003269 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003270 LOG_AND_RETURN_ERROR(
3271 RTCErrorType::INVALID_PARAMETER,
3272 "Transceiver type does not match media description type.");
3273 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003274 if (media_desc->HasSimulcast()) {
3275 std::vector<SimulcastLayer> layers =
3276 source == cricket::CS_LOCAL
3277 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3278 : media_desc->simulcast_description()
3279 .receive_layers()
3280 .GetAllLayers();
3281 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003282 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003283 if (!error.ok()) {
3284 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3285 return std::move(error);
3286 }
3287 }
Steve Antondcc3c022017-12-22 16:02:54 -08003288 // Associate the found or created RtpTransceiver with the m= section by
3289 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3290 // section, and establish a mapping between the transceiver and the index of
3291 // the m= section.
3292 transceiver->internal()->set_mid(content.name);
3293 transceiver->internal()->set_mline_index(mline_index);
3294 return std::move(transceiver);
3295}
3296
3297rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3298PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3299 RTC_DCHECK(IsUnifiedPlan());
3300 for (auto transceiver : transceivers_) {
3301 if (transceiver->mid() == mid) {
3302 return transceiver;
3303 }
3304 }
3305 return nullptr;
3306}
3307
3308rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3309PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3310 RTC_DCHECK(IsUnifiedPlan());
3311 for (auto transceiver : transceivers_) {
3312 if (transceiver->internal()->mline_index() == mline_index) {
3313 return transceiver;
3314 }
3315 }
3316 return nullptr;
3317}
3318
3319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3320PeerConnection::FindAvailableTransceiverToReceive(
3321 cricket::MediaType media_type) const {
3322 RTC_DCHECK(IsUnifiedPlan());
3323 // From JSEP section 5.10 (Applying a Remote Description):
3324 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3325 // the same type that were added to the PeerConnection by addTrack and are not
3326 // associated with any m= section and are not stopped, find the first such
3327 // RtpTransceiver.
3328 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003329 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003330 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3331 !transceiver->stopped()) {
3332 return transceiver;
3333 }
3334 }
3335 return nullptr;
3336}
3337
Steve Antoned10bd92017-12-05 10:52:59 -08003338const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3339 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3340 transceiver,
3341 const SessionDescriptionInterface* sdesc) const {
3342 RTC_DCHECK(transceiver);
3343 RTC_DCHECK(sdesc);
3344 if (IsUnifiedPlan()) {
3345 if (!transceiver->internal()->mid()) {
3346 // This transceiver is not associated with a media section yet.
3347 return nullptr;
3348 }
3349 return sdesc->description()->GetContentByName(
3350 *transceiver->internal()->mid());
3351 } else {
3352 // Plan B only allows at most one audio and one video section, so use the
3353 // first media section of that type.
3354 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003355 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003356 }
3357}
3358
deadbeef46c73892016-11-16 19:42:04 -08003359PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003360 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003361 return configuration_;
3362}
3363
deadbeef293e9262017-01-11 12:28:30 -08003364bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3365 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003366 RTC_DCHECK_RUN_ON(signaling_thread());
3367 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003368 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003369 if (IsClosed()) {
3370 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3371 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3372 }
3373
Qingsi Wanga2d60672018-04-11 16:57:45 -07003374 // According to JSEP, after setLocalDescription, changing the candidate pool
3375 // size is not allowed, and changing the set of ICE servers will not result
3376 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003377 if (local_description() && configuration.ice_candidate_pool_size !=
3378 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003379 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3380 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003381 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003382 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003383
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003384 if (local_description() &&
3385 configuration.use_media_transport != configuration_.use_media_transport) {
3386 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3387 "SetLocalDescription.";
3388 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3389 }
3390
3391 if (remote_description() &&
3392 configuration.use_media_transport != configuration_.use_media_transport) {
3393 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3394 "SetRemoteDescription.";
3395 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3396 }
3397
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003398 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003399 configuration.use_media_transport_for_data_channels !=
3400 configuration_.use_media_transport_for_data_channels) {
3401 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3402 "after calling SetLocalDescription.";
3403 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3404 }
3405
3406 if (remote_description() &&
3407 configuration.use_media_transport_for_data_channels !=
3408 configuration_.use_media_transport_for_data_channels) {
3409 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3410 "after calling SetRemoteDescription.";
3411 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3412 }
3413
3414 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003415 configuration.crypto_options != configuration_.crypto_options) {
3416 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3417 "SetLocalDescription.";
3418 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3419 }
3420
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003421 if (local_description() && configuration.use_datagram_transport !=
3422 configuration_.use_datagram_transport) {
3423 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3424 "after calling SetLocalDescription.";
3425 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3426 }
3427
3428 if (remote_description() && configuration.use_datagram_transport !=
3429 configuration_.use_datagram_transport) {
3430 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3431 "after calling SetRemoteDescription.";
3432 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3433 }
3434
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003435 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003436 configuration.use_media_transport ||
3437 configuration.use_datagram_transport) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003438 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3439 << "Media transport requires MaxBundle policy.";
3440 }
3441
deadbeef293e9262017-01-11 12:28:30 -08003442 // The simplest (and most future-compatible) way to tell if the config was
3443 // modified in an invalid way is to copy each property we do support
3444 // modifying, then use operator==. There are far more properties we don't
3445 // support modifying than those we do, and more could be added.
3446 RTCConfiguration modified_config = configuration_;
3447 modified_config.servers = configuration.servers;
3448 modified_config.type = configuration.type;
3449 modified_config.ice_candidate_pool_size =
3450 configuration.ice_candidate_pool_size;
3451 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003452 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003453 modified_config.ice_check_interval_strong_connectivity =
3454 configuration.ice_check_interval_strong_connectivity;
3455 modified_config.ice_check_interval_weak_connectivity =
3456 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003457 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3458 modified_config.ice_unwritable_min_checks =
3459 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003460 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003461 modified_config.stun_candidate_keepalive_interval =
3462 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003463 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003464 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003465 modified_config.active_reset_srtp_params =
3466 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003467 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003468 modified_config.use_media_transport_for_data_channels =
3469 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003470 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003471 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003472 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3473 }
3474
Steve Anton038834f2017-07-14 15:59:59 -07003475 // Validate the modified configuration.
3476 RTCError validate_error = ValidateConfiguration(modified_config);
3477 if (!validate_error.ok()) {
3478 return SafeSetError(std::move(validate_error), error);
3479 }
3480
deadbeef293e9262017-01-11 12:28:30 -08003481 // Note that this isn't possible through chromium, since it's an unsigned
3482 // short in WebIDL.
3483 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003484 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003485 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3486 }
3487
3488 // Parse ICE servers before hopping to network thread.
3489 cricket::ServerAddresses stun_servers;
3490 std::vector<cricket::RelayServerConfig> turn_servers;
3491 RTCErrorType parse_error =
3492 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3493 if (parse_error != RTCErrorType::NONE) {
3494 return SafeSetError(parse_error, error);
3495 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003496 // Note if STUN or TURN servers were supplied.
3497 if (!stun_servers.empty()) {
3498 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3499 }
3500 if (!turn_servers.empty()) {
3501 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3502 }
deadbeef293e9262017-01-11 12:28:30 -08003503
3504 // In theory this shouldn't fail.
3505 if (!network_thread()->Invoke<bool>(
3506 RTC_FROM_HERE,
3507 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3508 stun_servers, turn_servers, modified_config.type,
3509 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003510 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003511 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003512 modified_config.stun_candidate_keepalive_interval,
3513 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003514 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003515 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3516 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003517
deadbeefd1a38b52016-12-10 13:15:33 -08003518 // As described in JSEP, calling setConfiguration with new ICE servers or
3519 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3520 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003521 if (modified_config.servers != configuration_.servers ||
3522 modified_config.type != configuration_.type ||
3523 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003524 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003525 }
skvladd1f5fda2017-02-03 16:54:05 -08003526
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003527 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003528 transport_controller_->SetMediaTransportSettings(
3529 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003530 modified_config.use_media_transport_for_data_channels,
3531 modified_config.use_datagram_transport);
skvladd1f5fda2017-02-03 16:54:05 -08003532
Zhi Huangb57e1692018-06-12 11:41:11 -07003533 if (configuration_.active_reset_srtp_params !=
3534 modified_config.active_reset_srtp_params) {
3535 transport_controller_->SetActiveResetSrtpParams(
3536 modified_config.active_reset_srtp_params);
3537 }
3538
deadbeef293e9262017-01-11 12:28:30 -08003539 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003540 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003541 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003542}
3543
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003544bool PeerConnection::AddIceCandidate(
3545 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003546 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003547 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003548 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003549 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003550 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003551 return false;
3552 }
Steve Antond25da372017-11-06 14:50:29 -08003553
3554 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003555 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003556 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003557 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003558 return false;
3559 }
3560
3561 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003562 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003563 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003564 return false;
3565 }
3566
3567 bool valid = false;
3568 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3569 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003570 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003571 return false;
3572 }
3573
3574 // Add this candidate to the remote session description.
3575 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003576 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003577 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003578 return false;
3579 }
3580
3581 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003582 bool result = UseCandidate(ice_candidate);
3583 if (result) {
3584 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003585 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3586 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3587 }
3588 if (ice_candidate->candidate().address().IsPrivateIP()) {
3589 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3590 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003591 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3592 } else {
3593 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3594 }
3595 return result;
Steve Antond25da372017-11-06 14:50:29 -08003596 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003597 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003598 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003599 return true;
3600 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003601}
3602
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003603bool PeerConnection::RemoveIceCandidates(
3604 const std::vector<cricket::Candidate>& candidates) {
3605 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003606 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003607 if (IsClosed()) {
3608 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3609 return false;
3610 }
3611
Steve Antond25da372017-11-06 14:50:29 -08003612 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003613 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3614 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003615 return false;
3616 }
3617
3618 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003619 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003620 return false;
3621 }
3622
3623 size_t number_removed =
3624 mutable_remote_description()->RemoveCandidates(candidates);
3625 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003626 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003627 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003628 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003629 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003630 }
3631
3632 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003633 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3634 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003635 RTC_LOG(LS_ERROR)
3636 << "RemoveIceCandidates: Error when removing remote candidates: "
3637 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003638 }
3639 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003640}
3641
Niels Möller0c4f7be2018-05-07 14:01:37 +02003642RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003643 if (!worker_thread()->IsCurrent()) {
3644 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003645 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003646 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003647 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003648
Niels Möller0c4f7be2018-05-07 14:01:37 +02003649 const bool has_min = bitrate.min_bitrate_bps.has_value();
3650 const bool has_start = bitrate.start_bitrate_bps.has_value();
3651 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003652 if (has_min && *bitrate.min_bitrate_bps < 0) {
3653 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3654 "min_bitrate_bps <= 0");
3655 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003656 if (has_start) {
3657 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003658 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003659 "start_bitrate_bps < min_bitrate_bps");
3660 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003661 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3662 "curent_bitrate_bps < 0");
3663 }
3664 }
3665 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003666 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003667 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003668 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003669 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3671 "max_bitrate_bps < min_bitrate_bps");
3672 } else if (*bitrate.max_bitrate_bps < 0) {
3673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3674 "max_bitrate_bps < 0");
3675 }
3676 }
3677
zstein4b979802017-06-02 14:37:37 -07003678 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003679 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003680
3681 return RTCError::OK();
3682}
3683
Alex Narest78609d52017-10-20 10:37:47 +02003684void PeerConnection::SetBitrateAllocationStrategy(
3685 std::unique_ptr<rtc::BitrateAllocationStrategy>
3686 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003687 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003688 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3689 // move-capture values in lambdas.
3690 struct Task {
3691 PeerConnection* const pc;
3692 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3693 void operator()() {
3694 RTC_DCHECK_RUN_ON(pc->worker_thread());
3695 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3696 }
3697 };
3698 worker_thread()->Invoke<void>(
3699 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003700 return;
3701 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003702 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003703 RTC_DCHECK(call_.get());
3704 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3705}
3706
henrika5f6bf242017-11-01 11:06:56 +01003707void PeerConnection::SetAudioPlayout(bool playout) {
3708 if (!worker_thread()->IsCurrent()) {
3709 worker_thread()->Invoke<void>(
3710 RTC_FROM_HERE,
3711 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3712 return;
3713 }
3714 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003715 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003716 audio_state->SetPlayout(playout);
3717}
3718
3719void PeerConnection::SetAudioRecording(bool recording) {
3720 if (!worker_thread()->IsCurrent()) {
3721 worker_thread()->Invoke<void>(
3722 RTC_FROM_HERE,
3723 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3724 return;
3725 }
3726 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003727 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003728 audio_state->SetRecording(recording);
3729}
3730
Steve Anton8c0f7a72017-10-03 10:03:10 -07003731std::unique_ptr<rtc::SSLCertificate>
3732PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003733 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3734 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003735 return nullptr;
3736 }
Steve Antonf25303e2018-10-16 15:23:31 -07003737 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003738}
3739
Zhi Huang70b820f2018-01-27 14:16:15 -08003740std::unique_ptr<rtc::SSLCertChain>
3741PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003742 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003743 auto audio_transceiver = GetFirstAudioTransceiver();
3744 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003745 return nullptr;
3746 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003747 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003748 audio_transceiver->internal()->channel()->transport_name());
3749}
3750
3751rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3752PeerConnection::GetFirstAudioTransceiver() const {
3753 for (auto transceiver : transceivers_) {
3754 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3755 return transceiver;
3756 }
3757 }
3758 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003759}
3760
Bjorn Tereliusde939432017-11-20 17:38:14 +01003761bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3762 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003763 // TODO(eladalon): In C++14, this can be done with a lambda.
3764 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003765 bool operator()() {
3766 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3767 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003768 PeerConnection* const pc;
3769 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003770 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003771 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003772 return worker_thread()->Invoke<bool>(
3773 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003774}
3775
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003776bool PeerConnection::StartRtcEventLog(
3777 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003778 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3779 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3780 output_period_ms = 5000;
3781 }
3782 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003783}
3784
ivoc14d5dbe2016-07-04 07:06:55 -07003785void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003786 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003787 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3788}
3789
Harald Alvestrandad88c882018-11-28 16:47:46 +01003790rtc::scoped_refptr<DtlsTransportInterface>
3791PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003792 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003793 return transport_controller_->LookupDtlsTransportByMid(mid);
3794}
3795
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003796rtc::scoped_refptr<DtlsTransport>
3797PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003798 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003799 return transport_controller_->LookupDtlsTransportByMid(mid);
3800}
3801
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003802rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3803 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003804 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003805 return sctp_transport_;
3806}
3807
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003808const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003809 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003810 return pending_local_description_ ? pending_local_description_.get()
3811 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003812}
3813
3814const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003815 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003816 return pending_remote_description_ ? pending_remote_description_.get()
3817 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003818}
3819
deadbeeffe4a8a42016-12-20 17:56:17 -08003820const SessionDescriptionInterface* PeerConnection::current_local_description()
3821 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003822 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003823 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003824}
3825
3826const SessionDescriptionInterface* PeerConnection::current_remote_description()
3827 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003828 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003829 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003830}
3831
3832const SessionDescriptionInterface* PeerConnection::pending_local_description()
3833 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003834 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003835 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003836}
3837
3838const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3839 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003840 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003841 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003842}
3843
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003844void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003845 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003846 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003847 // Update stats here so that we have the most recent stats for tracks and
3848 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003849 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003850
Steve Anton75737c02017-11-06 10:37:17 -08003851 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003852 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003853
Mirko Bonadei739baf02019-01-27 17:29:42 +01003854 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003855 transceiver->Stop();
3856 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003857
3858 // Ensure that all asynchronous stats requests are completed before destroying
3859 // the transport controller below.
3860 if (stats_collector_) {
3861 stats_collector_->WaitForPendingRequest();
3862 }
3863
3864 // Don't destroy BaseChannels until after stats has been cleaned up so that
3865 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003866 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003867
Qingsi Wang93a84392018-01-30 17:13:09 -08003868 // The event log is used in the transport controller, which must be outlived
3869 // by the former. CreateOffer by the peer connection is implemented
3870 // asynchronously and if the peer connection is closed without resetting the
3871 // WebRTC session description factory, the session description factory would
3872 // call the transport controller.
3873 webrtc_session_desc_factory_.reset();
3874 transport_controller_.reset();
3875
deadbeef42a42632017-03-10 15:18:00 -08003876 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003877 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3878 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003879
Steve Anton978b8762017-09-29 12:15:02 -07003880 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003881 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003882 call_.reset();
3883 // The event log must outlive call (and any other object that uses it).
3884 event_log_.reset();
3885 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003886 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003887 // The .h file says that observer can be discarded after close() returns.
3888 // Make sure this is true.
3889 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003890}
3891
Steve Antonad182762018-09-05 20:22:40 +00003892void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003893 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003894 switch (msg->message_id) {
3895 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3896 SetSessionDescriptionMsg* param =
3897 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3898 param->observer->OnSuccess();
3899 delete param;
3900 break;
3901 }
3902 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3903 SetSessionDescriptionMsg* param =
3904 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3905 param->observer->OnFailure(std::move(param->error));
3906 delete param;
3907 break;
3908 }
3909 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3910 CreateSessionDescriptionMsg* param =
3911 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3912 param->observer->OnFailure(std::move(param->error));
3913 delete param;
3914 break;
3915 }
3916 case MSG_GETSTATS: {
3917 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3918 StatsReports reports;
3919 stats_->GetStats(param->track, &reports);
3920 param->observer->OnComplete(reports);
3921 delete param;
3922 break;
3923 }
3924 case MSG_FREE_DATACHANNELS: {
3925 sctp_data_channels_to_free_.clear();
3926 break;
3927 }
3928 case MSG_REPORT_USAGE_PATTERN: {
3929 ReportUsagePattern();
3930 break;
3931 }
3932 default:
3933 RTC_NOTREACHED() << "Not implemented";
3934 break;
3935 }
3936}
3937
Steve Antonafb0bb72018-02-20 11:35:37 -08003938cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3939 RTC_DCHECK(!IsUnifiedPlan());
3940 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3941 GetAudioTransceiver()->internal()->channel());
3942 if (voice_channel) {
3943 return voice_channel->media_channel();
3944 } else {
3945 return nullptr;
3946 }
3947}
3948
3949cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3950 RTC_DCHECK(!IsUnifiedPlan());
3951 auto* video_channel = static_cast<cricket::VideoChannel*>(
3952 GetVideoTransceiver()->internal()->channel());
3953 if (video_channel) {
3954 return video_channel->media_channel();
3955 } else {
3956 return nullptr;
3957 }
3958}
3959
Steve Anton4171afb2017-11-20 10:20:22 -08003960void PeerConnection::CreateAudioReceiver(
3961 MediaStreamInterface* stream,
3962 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003963 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3964 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003965 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3966 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003967 auto* audio_receiver = new AudioRtpReceiver(
3968 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003969 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003970 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3971 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3972 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003973 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003974 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003975 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003976}
3977
Steve Anton4171afb2017-11-20 10:20:22 -08003978void PeerConnection::CreateVideoReceiver(
3979 MediaStreamInterface* stream,
3980 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003981 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3982 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003983 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3984 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003985 auto* video_receiver = new VideoRtpReceiver(
3986 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003987 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003988 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3989 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3990 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003991 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003992 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003993 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003994}
3995
deadbeef70ab1a12015-09-28 16:53:55 -07003996// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3997// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003998rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003999 const RtpSenderInfo& remote_sender_info) {
4000 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4001 if (!receiver) {
4002 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4003 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004004 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004005 }
Steve Anton4171afb2017-11-20 10:20:22 -08004006 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4007 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4008 } else {
4009 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4010 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004011 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004012}
4013
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004014void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4015 MediaStreamInterface* stream) {
4016 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004017 RTC_DCHECK(track);
4018 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004019 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004020 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004021 // We already have a sender for this track, so just change the stream_id
4022 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004023 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004024 return;
4025 }
4026
4027 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004028 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004029 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004030 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004031 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004032 // If the sender has already been configured in SDP, we call SetSsrc,
4033 // which will connect the sender to the underlying transport. This can
4034 // occur if a local session description that contains the ID of the sender
4035 // is set before AddStream is called. It can also occur if the local
4036 // session description is not changed and RemoveStream is called, and
4037 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004038 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004039 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004040 if (sender_info) {
4041 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004042 }
4043}
4044
4045// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4046// indefinitely, when we have unified plan SDP.
4047void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4048 MediaStreamInterface* stream) {
4049 RTC_DCHECK(!IsClosed());
4050 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004051 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004052 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4053 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004054 return;
4055 }
Steve Anton4171afb2017-11-20 10:20:22 -08004056 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004057}
4058
4059void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4060 MediaStreamInterface* stream) {
4061 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004062 RTC_DCHECK(track);
4063 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004064 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004065 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004066 // We already have a sender for this track, so just change the stream_id
4067 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004068 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004069 return;
4070 }
4071
4072 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004073 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004074 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004075 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004076 GetVideoTransceiver()->internal()->AddSender(new_sender);
4077 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004078 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004079 if (sender_info) {
4080 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004081 }
4082}
4083
4084void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4085 MediaStreamInterface* stream) {
4086 RTC_DCHECK(!IsClosed());
4087 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004088 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004089 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4090 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004091 return;
4092 }
Steve Anton4171afb2017-11-20 10:20:22 -08004093 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004094}
4095
Steve Antonba818672017-11-06 10:21:57 -08004096void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004097 if (ice_connection_state_ == new_state) {
4098 return;
4099 }
4100
deadbeefcbecd352015-09-23 11:50:27 -07004101 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004102 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004103 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004104 return;
4105 }
Steve Antonba818672017-11-06 10:21:57 -08004106
Mirko Bonadei675513b2017-11-09 11:09:25 +01004107 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4108 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004109 RTC_DCHECK(ice_connection_state_ !=
4110 PeerConnectionInterface::kIceConnectionClosed);
4111
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004112 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004113 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004114}
4115
Alex Loiko9289eda2018-11-23 16:18:59 +00004116void PeerConnection::SetStandardizedIceConnectionState(
4117 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004118 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004119 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004120 }
4121
4122 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004123 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004124 }
4125
4126 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4127 << standardized_ice_connection_state_ << " => " << new_state;
4128
Alex Loiko9289eda2018-11-23 16:18:59 +00004129 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004130 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004131}
4132
Jonas Olsson635474e2018-10-18 15:58:17 +02004133void PeerConnection::SetConnectionState(
4134 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004135 if (connection_state_ == new_state)
4136 return;
4137 if (IsClosed())
4138 return;
4139 connection_state_ = new_state;
4140 Observer()->OnConnectionChange(new_state);
4141}
4142
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004143void PeerConnection::OnIceGatheringChange(
4144 PeerConnectionInterface::IceGatheringState new_state) {
4145 if (IsClosed()) {
4146 return;
4147 }
4148 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004149 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004150}
4151
jbauch81bf7b02017-03-25 08:31:12 -07004152void PeerConnection::OnIceCandidate(
4153 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004154 if (IsClosed()) {
4155 return;
4156 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004157 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004158 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4159 candidate->candidate().address().IsPrivateIP()) {
4160 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4161 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004162 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4163 candidate->candidate().address().IsUnresolvedIP()) {
4164 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4165 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004166 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004167}
4168
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004169void PeerConnection::OnIceCandidatesRemoved(
4170 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004171 if (IsClosed()) {
4172 return;
4173 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004174 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004175}
4176
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004177void PeerConnection::ChangeSignalingState(
4178 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004179 if (signaling_state_ == signaling_state) {
4180 return;
4181 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004182 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4183 << GetSignalingStateString(signaling_state_)
4184 << " New state: "
4185 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004186 signaling_state_ = signaling_state;
4187 if (signaling_state == kClosed) {
4188 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004189 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004190 standardized_ice_connection_state_ =
4191 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004192 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4193 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004194 if (ice_gathering_state_ != kIceGatheringComplete) {
4195 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004196 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004197 }
4198 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004199 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004200}
4201
deadbeefeb459812015-12-15 19:24:43 -08004202void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4203 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004204 if (IsClosed()) {
4205 return;
4206 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004207 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004208 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004209}
4210
deadbeefeb459812015-12-15 19:24:43 -08004211void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4212 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004213 if (IsClosed()) {
4214 return;
4215 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004216 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004217 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004218}
4219
4220void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4221 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004222 if (IsClosed()) {
4223 return;
4224 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004225 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004226 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004227}
4228
4229void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4230 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004231 if (IsClosed()) {
4232 return;
4233 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004234 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004235 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004236}
4237
Henrik Boström31638672017-11-23 17:48:32 +01004238void PeerConnection::PostSetSessionDescriptionSuccess(
4239 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004240 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4241 signaling_thread()->Post(RTC_FROM_HERE, this,
4242 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004243}
4244
deadbeefab9b2d12015-10-14 11:33:11 -07004245void PeerConnection::PostSetSessionDescriptionFailure(
4246 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004247 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004248 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004249 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4250 msg->error = std::move(error);
4251 signaling_thread()->Post(RTC_FROM_HERE, this,
4252 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004253}
4254
4255void PeerConnection::PostCreateSessionDescriptionFailure(
4256 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004257 RTCError error) {
4258 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004259 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4260 msg->error = std::move(error);
4261 signaling_thread()->Post(RTC_FROM_HERE, this,
4262 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004263}
4264
zhihuang1c378ed2017-08-17 14:10:50 -07004265void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004266 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004267 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004268 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004269
Steve Antondcc3c022017-12-22 16:02:54 -08004270 if (IsUnifiedPlan()) {
4271 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4272 } else {
4273 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4274 }
4275
Steve Antonfa2260d2017-12-28 16:38:23 -08004276 // Intentionally unset the data channel type for RTP data channel with the
4277 // second condition. Otherwise the RTP data channels would be successfully
4278 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4279 // when building with chromium. We want to leave RTP data channels broken, so
4280 // people won't try to use them.
4281 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4282 session_options->data_channel_type = data_channel_type();
4283 }
4284
Steve Antondcc3c022017-12-22 16:02:54 -08004285 // Apply ICE restart flag and renomination flag.
4286 for (auto& options : session_options->media_description_options) {
4287 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4288 options.transport_options.enable_ice_renomination =
4289 configuration_.enable_ice_renomination;
4290 }
4291
4292 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004293 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004294 session_options->pooled_ice_credentials =
4295 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4296 RTC_FROM_HERE,
4297 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4298 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004299 session_options->offer_extmap_allow_mixed =
4300 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004301
4302 if (configuration_.enable_dtls_srtp &&
4303 !configuration_.enable_dtls_srtp.value()) {
4304 session_options->media_transport_settings =
4305 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4306 }
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004307 // Allow fallback for using obsolete SCTP syntax.
4308 // Note that the default in |session_options| is true, while
4309 // the default in |options| is false.
4310 session_options->use_obsolete_sctp_sdp =
4311 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004312}
4313
4314void PeerConnection::GetOptionsForPlanBOffer(
4315 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4316 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004317 // Figure out transceiver directional preferences.
4318 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4319 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4320
4321 // By default, generate sendrecv/recvonly m= sections.
4322 bool recv_audio = true;
4323 bool recv_video = true;
4324
4325 // By default, only offer a new m= section if we have media to send with it.
4326 bool offer_new_audio_description = send_audio;
4327 bool offer_new_video_description = send_video;
4328 bool offer_new_data_description = HasDataChannels();
4329
4330 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004331 if (offer_answer_options.offer_to_receive_audio !=
4332 RTCOfferAnswerOptions::kUndefined) {
4333 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004334 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004335 offer_new_audio_description ||
4336 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004337 }
Steve Antondcc3c022017-12-22 16:02:54 -08004338 if (offer_answer_options.offer_to_receive_video !=
4339 RTCOfferAnswerOptions::kUndefined) {
4340 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004341 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004342 offer_new_video_description ||
4343 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004344 }
4345
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004346 absl::optional<size_t> audio_index;
4347 absl::optional<size_t> video_index;
4348 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004349 // If a current description exists, generate m= sections in the same order,
4350 // using the first audio/video/data section that appears and rejecting
4351 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004352 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004353 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004354 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004355 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4356 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4357 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004358 }
4359
zhihuang1c378ed2017-08-17 14:10:50 -07004360 // Add audio/video/data m= sections to the end if needed.
4361 if (!audio_index && offer_new_audio_description) {
4362 session_options->media_description_options.push_back(
4363 cricket::MediaDescriptionOptions(
4364 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004365 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4366 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004367 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004368 }
zhihuang1c378ed2017-08-17 14:10:50 -07004369 if (!video_index && offer_new_video_description) {
4370 session_options->media_description_options.push_back(
4371 cricket::MediaDescriptionOptions(
4372 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004373 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4374 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004375 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004376 }
zhihuang1c378ed2017-08-17 14:10:50 -07004377 if (!data_index && offer_new_data_description) {
4378 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004379 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004380 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004381 }
4382
4383 cricket::MediaDescriptionOptions* audio_media_description_options =
4384 !audio_index ? nullptr
4385 : &session_options->media_description_options[*audio_index];
4386 cricket::MediaDescriptionOptions* video_media_description_options =
4387 !video_index ? nullptr
4388 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004389
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004390 AddPlanBRtpSenderOptions(GetSendersInternal(),
4391 audio_media_description_options,
4392 video_media_description_options,
4393 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004394}
4395
Steve Antondcc3c022017-12-22 16:02:54 -08004396static cricket::MediaDescriptionOptions
4397GetMediaDescriptionOptionsForTransceiver(
4398 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4399 transceiver,
4400 const std::string& mid) {
4401 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004402 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004403 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004404 media_description_options.codec_preferences =
4405 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004406 // This behavior is specified in JSEP. The gist is that:
4407 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4408 // sendrecv.
4409 // 2. If the MSID is included, then it must be included in any subsequent
4410 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004411 if (transceiver->stopped() ||
4412 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4413 !transceiver->internal()->has_ever_been_used_to_send())) {
4414 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004415 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004416
4417 cricket::SenderOptions sender_options;
4418 sender_options.track_id = transceiver->sender()->id();
4419 sender_options.stream_ids = transceiver->sender()->stream_ids();
4420
4421 // The following sets up RIDs and Simulcast.
4422 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004423 RtpParameters send_parameters =
4424 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004425 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4426 send_parameters.encodings.end(),
4427 [](const RtpEncodingParameters& encoding) {
4428 return !encoding.rid.empty();
4429 });
4430
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004431 std::vector<RidDescription> send_rids;
4432 SimulcastLayerList send_layers;
4433 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4434 if (encoding.rid.empty()) {
4435 continue;
4436 }
4437 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4438 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4439 }
4440
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004441 if (has_rids) {
4442 sender_options.rids = send_rids;
4443 }
4444
4445 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004446 // When RIDs are configured, we must set num_sim_layers to 0 to.
4447 // Otherwise, num_sim_layers must be 1 because either there is no
4448 // simulcast, or simulcast is acheived by munging the SDP.
4449 sender_options.num_sim_layers = has_rids ? 0 : 1;
4450 media_description_options.sender_options.push_back(sender_options);
4451
Steve Antondcc3c022017-12-22 16:02:54 -08004452 return media_description_options;
4453}
4454
Steve Anton5c72e712018-12-10 14:25:30 -08004455// Returns the ContentInfo at mline index |i|, or null if none exists.
4456static const ContentInfo* GetContentByIndex(
4457 const SessionDescriptionInterface* sdesc,
4458 size_t i) {
4459 if (!sdesc) {
4460 return nullptr;
4461 }
4462 const ContentInfos& contents = sdesc->description()->contents();
4463 return (i < contents.size() ? &contents[i] : nullptr);
4464}
4465
Steve Antondcc3c022017-12-22 16:02:54 -08004466void PeerConnection::GetOptionsForUnifiedPlanOffer(
4467 const RTCOfferAnswerOptions& offer_answer_options,
4468 cricket::MediaSessionOptions* session_options) {
4469 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4470 // Offers) and 5.2.2 (Subsequent Offers).
4471 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4472 const ContentInfos& local_contents =
4473 (local_description() ? local_description()->description()->contents()
4474 : ContentInfos());
4475 const ContentInfos& remote_contents =
4476 (remote_description() ? remote_description()->description()->contents()
4477 : ContentInfos());
4478 // The mline indices that can be recycled. New transceivers should reuse these
4479 // slots first.
4480 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004481 // First, go through each media section that exists in either the local or
4482 // remote description and generate a media section in this offer for the
4483 // associated transceiver. If a media section can be recycled, generate a
4484 // default, rejected media section here that can be later overwritten.
4485 for (size_t i = 0;
4486 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4487 // Either |local_content| or |remote_content| is non-null.
4488 const ContentInfo* local_content =
4489 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004490 const ContentInfo* current_local_content =
4491 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004492 const ContentInfo* remote_content =
4493 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004494 const ContentInfo* current_remote_content =
4495 GetContentByIndex(current_remote_description(), i);
4496 bool had_been_rejected =
4497 (current_local_content && current_local_content->rejected) ||
4498 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004499 const std::string& mid =
4500 (local_content ? local_content->name : remote_content->name);
4501 cricket::MediaType media_type =
4502 (local_content ? local_content->media_description()->type()
4503 : remote_content->media_description()->type());
4504 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4505 media_type == cricket::MEDIA_TYPE_VIDEO) {
4506 auto transceiver = GetAssociatedTransceiver(mid);
4507 RTC_CHECK(transceiver);
4508 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004509 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004510 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004511 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004512 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4513 RtpTransceiverDirection::kInactive,
4514 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004515 recycleable_mline_indices.push(i);
4516 } else {
4517 session_options->media_description_options.push_back(
4518 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4519 // CreateOffer shouldn't really cause any state changes in
4520 // PeerConnection, but we need a way to match new transceivers to new
4521 // media sections in SetLocalDescription and JSEP specifies this is done
4522 // by recording the index of the media section generated for the
4523 // transceiver in the offer.
4524 transceiver->internal()->set_mline_index(i);
4525 }
4526 } else {
4527 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004528 RTC_CHECK(GetDataMid());
4529 if (had_been_rejected || mid != *GetDataMid()) {
4530 session_options->media_description_options.push_back(
4531 GetMediaDescriptionOptionsForRejectedData(mid));
4532 } else {
4533 session_options->media_description_options.push_back(
4534 GetMediaDescriptionOptionsForActiveData(mid));
4535 }
Steve Antondcc3c022017-12-22 16:02:54 -08004536 }
4537 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004538
Steve Antondcc3c022017-12-22 16:02:54 -08004539 // Next, look for transceivers that are newly added (that is, are not stopped
4540 // and not associated). Reuse media sections marked as recyclable first,
4541 // otherwise append to the end of the offer. New media sections should be
4542 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004543 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004544 if (transceiver->mid() || transceiver->stopped()) {
4545 continue;
4546 }
4547 size_t mline_index;
4548 if (!recycleable_mline_indices.empty()) {
4549 mline_index = recycleable_mline_indices.front();
4550 recycleable_mline_indices.pop();
4551 session_options->media_description_options[mline_index] =
4552 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004553 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004554 } else {
4555 mline_index = session_options->media_description_options.size();
4556 session_options->media_description_options.push_back(
4557 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004558 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004559 }
4560 // See comment above for why CreateOffer changes the transceiver's state.
4561 transceiver->internal()->set_mline_index(mline_index);
4562 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004563 // Lastly, add a m-section if we have local data channels and an m section
4564 // does not already exist.
4565 if (!GetDataMid() && HasDataChannels()) {
4566 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004567 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004568 }
Steve Antondcc3c022017-12-22 16:02:54 -08004569}
4570
4571void PeerConnection::GetOptionsForAnswer(
4572 const RTCOfferAnswerOptions& offer_answer_options,
4573 cricket::MediaSessionOptions* session_options) {
4574 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4575
4576 if (IsUnifiedPlan()) {
4577 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4578 } else {
4579 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4580 }
4581
Steve Antonfa2260d2017-12-28 16:38:23 -08004582 // Intentionally unset the data channel type for RTP data channel. Otherwise
4583 // the RTP data channels would be successfully negotiated by default and the
4584 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4585 // We want to leave RTP data channels broken, so people won't try to use them.
4586 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4587 session_options->data_channel_type = data_channel_type();
4588 }
4589
Steve Antondcc3c022017-12-22 16:02:54 -08004590 // Apply ICE renomination flag.
4591 for (auto& options : session_options->media_description_options) {
4592 options.transport_options.enable_ice_renomination =
4593 configuration_.enable_ice_renomination;
4594 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004595
4596 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004597 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004598 session_options->pooled_ice_credentials =
4599 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4600 RTC_FROM_HERE,
4601 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4602 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004603}
4604
Steve Antondcc3c022017-12-22 16:02:54 -08004605void PeerConnection::GetOptionsForPlanBAnswer(
4606 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004607 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004608 // Figure out transceiver directional preferences.
4609 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4610 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4611
4612 // By default, generate sendrecv/recvonly m= sections. The direction is also
4613 // restricted by the direction in the offer.
4614 bool recv_audio = true;
4615 bool recv_video = true;
4616
4617 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004618 if (offer_answer_options.offer_to_receive_audio !=
4619 RTCOfferAnswerOptions::kUndefined) {
4620 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004621 }
Steve Antondcc3c022017-12-22 16:02:54 -08004622 if (offer_answer_options.offer_to_receive_video !=
4623 RTCOfferAnswerOptions::kUndefined) {
4624 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004625 }
4626
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004627 absl::optional<size_t> audio_index;
4628 absl::optional<size_t> video_index;
4629 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004630
4631 // Generate m= sections that match those in the offer.
4632 // Note that mediasession.cc will handle intersection our preferred
4633 // direction with the offered direction.
4634 GenerateMediaDescriptionOptions(
4635 remote_description(),
4636 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4637 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4638 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004639
4640 cricket::MediaDescriptionOptions* audio_media_description_options =
4641 !audio_index ? nullptr
4642 : &session_options->media_description_options[*audio_index];
4643 cricket::MediaDescriptionOptions* video_media_description_options =
4644 !video_index ? nullptr
4645 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004646
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004647 AddPlanBRtpSenderOptions(GetSendersInternal(),
4648 audio_media_description_options,
4649 video_media_description_options,
4650 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004651}
zhihuangaf388472016-11-02 16:49:48 -07004652
Steve Antondcc3c022017-12-22 16:02:54 -08004653void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4654 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4655 cricket::MediaSessionOptions* session_options) {
4656 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4657 // Answers) and 5.3.2 (Subsequent Answers).
4658 RTC_DCHECK(remote_description());
4659 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4660 for (const ContentInfo& content :
4661 remote_description()->description()->contents()) {
4662 cricket::MediaType media_type = content.media_description()->type();
4663 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4664 media_type == cricket::MEDIA_TYPE_VIDEO) {
4665 auto transceiver = GetAssociatedTransceiver(content.name);
4666 RTC_CHECK(transceiver);
4667 session_options->media_description_options.push_back(
4668 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4669 } else {
4670 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004671 // Reject all data sections if data channels are disabled.
4672 // Reject a data section if it has already been rejected.
4673 // Reject all data sections except for the first one.
4674 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4675 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004676 session_options->media_description_options.push_back(
4677 GetMediaDescriptionOptionsForRejectedData(content.name));
4678 } else {
4679 session_options->media_description_options.push_back(
4680 GetMediaDescriptionOptionsForActiveData(content.name));
4681 }
Steve Antondcc3c022017-12-22 16:02:54 -08004682 }
4683 }
htaa2a49d92016-03-04 02:51:39 -08004684}
4685
zhihuang1c378ed2017-08-17 14:10:50 -07004686void PeerConnection::GenerateMediaDescriptionOptions(
4687 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004688 RtpTransceiverDirection audio_direction,
4689 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004690 absl::optional<size_t>* audio_index,
4691 absl::optional<size_t>* video_index,
4692 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004693 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004694 for (const cricket::ContentInfo& content :
4695 session_desc->description()->contents()) {
4696 if (IsAudioContent(&content)) {
4697 // If we already have an audio m= section, reject this extra one.
4698 if (*audio_index) {
4699 session_options->media_description_options.push_back(
4700 cricket::MediaDescriptionOptions(
4701 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004702 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004703 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004704 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004705 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004706 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4707 content.name, audio_direction,
4708 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004709 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004710 }
4711 } else if (IsVideoContent(&content)) {
4712 // If we already have an video m= section, reject this extra one.
4713 if (*video_index) {
4714 session_options->media_description_options.push_back(
4715 cricket::MediaDescriptionOptions(
4716 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004717 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004718 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004719 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004720 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004721 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4722 content.name, video_direction,
4723 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004724 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004725 }
4726 } else {
4727 RTC_DCHECK(IsDataContent(&content));
4728 // If we already have an data m= section, reject this extra one.
4729 if (*data_index) {
4730 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004731 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004732 } else {
4733 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004734 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004735 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004736 }
4737 }
htaa2a49d92016-03-04 02:51:39 -08004738 }
deadbeefab9b2d12015-10-14 11:33:11 -07004739}
4740
Steve Antonfa2260d2017-12-28 16:38:23 -08004741cricket::MediaDescriptionOptions
4742PeerConnection::GetMediaDescriptionOptionsForActiveData(
4743 const std::string& mid) const {
4744 // Direction for data sections is meaningless, but legacy endpoints might
4745 // expect sendrecv.
4746 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4747 RtpTransceiverDirection::kSendRecv,
4748 /*stopped=*/false);
4749 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4750 return options;
4751}
4752
4753cricket::MediaDescriptionOptions
4754PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4755 const std::string& mid) const {
4756 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4757 RtpTransceiverDirection::kInactive,
4758 /*stopped=*/true);
4759 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4760 return options;
4761}
4762
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004763absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004764 switch (data_channel_type_) {
4765 case cricket::DCT_RTP:
4766 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004767 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004768 }
4769 return rtp_data_channel_->content_name();
4770 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004771 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004772 case cricket::DCT_MEDIA_TRANSPORT:
4773 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004774 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004775 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004776 }
4777}
4778
Steve Anton4171afb2017-11-20 10:20:22 -08004779void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4780 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4781 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004782 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004783}
4784
Steve Anton4171afb2017-11-20 10:20:22 -08004785void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004786 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004787 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004788 cricket::MediaType media_type,
4789 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004790 RTC_DCHECK(!IsUnifiedPlan());
4791
Steve Anton4171afb2017-11-20 10:20:22 -08004792 std::vector<RtpSenderInfo>* current_senders =
4793 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004794
Steve Anton4171afb2017-11-20 10:20:22 -08004795 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004796 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004797 for (auto sender_it = current_senders->begin();
4798 sender_it != current_senders->end();
4799 /* incremented manually */) {
4800 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004801 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004802 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004803 std::string params_stream_id;
4804 if (params) {
4805 params_stream_id =
4806 (!params->first_stream_id().empty() ? params->first_stream_id()
4807 : kDefaultStreamId);
4808 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004809 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004810 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004811 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004812 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004813 sender_exists) {
4814 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004815 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004816 OnRemoteSenderRemoved(info, media_type);
4817 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004818 }
4819 }
4820
Steve Anton4171afb2017-11-20 10:20:22 -08004821 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004822 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004823 if (!params.has_ssrcs()) {
4824 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4825 // sender, this means it is coming from a Unified Plan endpoint,so we just
4826 // create a default.
4827 default_sender_needed = true;
4828 break;
4829 }
4830
Seth Hampson845e8782018-03-02 11:34:10 -08004831 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004832 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004833 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4834 // not supported in Plan B, we just take the first here and create the
4835 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004836 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004837 (!params.first_stream_id().empty() ? params.first_stream_id()
4838 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004839 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004840 uint32_t ssrc = params.first_ssrc();
4841
4842 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004843 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004844 if (!stream) {
4845 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004846 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004847 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004848 remote_streams_->AddStream(stream);
4849 new_streams->AddStream(stream);
4850 }
4851
Steve Anton4171afb2017-11-20 10:20:22 -08004852 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004853 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004854 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004855 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004856 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004857 }
4858 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004859
Steve Anton4171afb2017-11-20 10:20:22 -08004860 // Add default sender if necessary.
4861 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004862 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004863 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004864 if (!default_stream) {
4865 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004866 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004867 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004868 remote_streams_->AddStream(default_stream);
4869 new_streams->AddStream(default_stream);
4870 }
Steve Anton4171afb2017-11-20 10:20:22 -08004871 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4872 ? kDefaultAudioSenderId
4873 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004874 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004875 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004876 if (!default_sender_info) {
4877 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004878 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004879 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004880 }
4881 }
deadbeefab9b2d12015-10-14 11:33:11 -07004882}
4883
Steve Anton4171afb2017-11-20 10:20:22 -08004884void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4885 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004886 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4887 << " receiver for track_id=" << sender_info.sender_id
4888 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004889
Steve Anton3d954a62018-04-02 11:27:23 -07004890 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004891 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004892 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004893 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004894 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004895 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004896 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004897 }
4898}
4899
Steve Anton4171afb2017-11-20 10:20:22 -08004900void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4901 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004902 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4903 << " receiver for track_id=" << sender_info.sender_id
4904 << " and stream_id=" << sender_info.stream_id;
4905
Seth Hampson845e8782018-03-02 11:34:10 -08004906 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004907
Henrik Boström933d8b02017-10-10 10:05:16 -07004908 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004909 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004910 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4911 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004912 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004913 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004914 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004915 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004916 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004917 }
4918 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004919 // Stopping or destroying a VideoRtpReceiver will end the
4920 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004921 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004922 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004923 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004924 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004925 // There's no guarantee the track is still available, e.g. the track may
4926 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004927 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004928 }
4929 } else {
nisseede5da42017-01-12 05:15:36 -08004930 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004931 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004932 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004933 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004934 }
deadbeefab9b2d12015-10-14 11:33:11 -07004935}
4936
4937void PeerConnection::UpdateEndedRemoteMediaStreams() {
4938 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4939 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4940 MediaStreamInterface* stream = remote_streams_->at(i);
4941 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4942 streams_to_remove.push_back(stream);
4943 }
4944 }
4945
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004946 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004947 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004948 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004949 }
4950}
4951
Steve Anton4171afb2017-11-20 10:20:22 -08004952void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004953 const std::vector<cricket::StreamParams>& streams,
4954 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004955 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004956
Seth Hampson845e8782018-03-02 11:34:10 -08004957 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004958 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004959 for (auto sender_it = current_senders->begin();
4960 sender_it != current_senders->end();
4961 /* incremented manually */) {
4962 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004963 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004964 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4965 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004966 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004967 OnLocalSenderRemoved(info, media_type);
4968 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004969 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004970 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004971 }
4972 }
4973
Steve Anton4171afb2017-11-20 10:20:22 -08004974 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004975 for (const cricket::StreamParams& params : streams) {
4976 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004977 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004978 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004979 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004980 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004981 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004982 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004983 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004984 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004985 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004986 }
4987 }
4988}
4989
Steve Anton4171afb2017-11-20 10:20:22 -08004990void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4991 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004992 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004993 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004994 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004995 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4996 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004997 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004998 return;
4999 }
5000
deadbeeffac06552015-11-25 11:26:01 -08005001 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005002 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005003 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005004 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005005 }
deadbeeffac06552015-11-25 11:26:01 -08005006
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005007 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005008 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005009}
5010
Steve Anton4171afb2017-11-20 10:20:22 -08005011void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5012 cricket::MediaType media_type) {
5013 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005014 if (!sender) {
5015 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005016 // SessionDescriptions has been renegotiated.
5017 return;
5018 }
deadbeeffac06552015-11-25 11:26:01 -08005019
5020 // A sender has been removed from the SessionDescription but it's still
5021 // associated with the PeerConnection. This only occurs if the SDP doesn't
5022 // match with the calls to CreateSender, AddStream and RemoveStream.
5023 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005024 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005025 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005026 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005027 }
deadbeeffac06552015-11-25 11:26:01 -08005028
Steve Anton4171afb2017-11-20 10:20:22 -08005029 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005030}
5031
5032void PeerConnection::UpdateLocalRtpDataChannels(
5033 const cricket::StreamParamsVec& streams) {
5034 std::vector<std::string> existing_channels;
5035
5036 // Find new and active data channels.
5037 for (const cricket::StreamParams& params : streams) {
5038 // |it->sync_label| is actually the data channel label. The reason is that
5039 // we use the same naming of data channels as we do for
5040 // MediaStreams and Tracks.
5041 // For MediaStreams, the sync_label is the MediaStream label and the
5042 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005043 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005044 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005045 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005046 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005047 continue;
5048 }
5049 // Set the SSRC the data channel should use for sending.
5050 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5051 existing_channels.push_back(data_channel_it->first);
5052 }
5053
5054 UpdateClosingRtpDataChannels(existing_channels, true);
5055}
5056
5057void PeerConnection::UpdateRemoteRtpDataChannels(
5058 const cricket::StreamParamsVec& streams) {
5059 std::vector<std::string> existing_channels;
5060
5061 // Find new and active data channels.
5062 for (const cricket::StreamParams& params : streams) {
5063 // The data channel label is either the mslabel or the SSRC if the mslabel
5064 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005065 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005066 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005067 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005068 auto data_channel_it = rtp_data_channels_.find(label);
5069 if (data_channel_it == rtp_data_channels_.end()) {
5070 // This is a new data channel.
5071 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5072 } else {
5073 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5074 }
5075 existing_channels.push_back(label);
5076 }
5077
5078 UpdateClosingRtpDataChannels(existing_channels, false);
5079}
5080
5081void PeerConnection::UpdateClosingRtpDataChannels(
5082 const std::vector<std::string>& active_channels,
5083 bool is_local_update) {
5084 auto it = rtp_data_channels_.begin();
5085 while (it != rtp_data_channels_.end()) {
5086 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005087 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005088 ++it;
5089 continue;
5090 }
5091
5092 if (is_local_update) {
5093 data_channel->SetSendSsrc(0);
5094 } else {
5095 data_channel->RemotePeerRequestClose();
5096 }
5097
5098 if (data_channel->state() == DataChannel::kClosed) {
5099 rtp_data_channels_.erase(it);
5100 it = rtp_data_channels_.begin();
5101 } else {
5102 ++it;
5103 }
5104 }
5105}
5106
5107void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5108 uint32_t remote_ssrc) {
5109 rtc::scoped_refptr<DataChannel> channel(
5110 InternalCreateDataChannel(label, nullptr));
5111 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005112 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005113 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005114 return;
5115 }
5116 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005117 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5118 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005119 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005120}
5121
5122rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5123 const std::string& label,
5124 const InternalDataChannelInit* config) {
5125 if (IsClosed()) {
5126 return nullptr;
5127 }
Steve Anton75737c02017-11-06 10:37:17 -08005128 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005129 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005130 << "InternalCreateDataChannel: Data is not supported in this call.";
5131 return nullptr;
5132 }
5133 InternalDataChannelInit new_config =
5134 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005135 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005136 if (new_config.id < 0) {
5137 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005138 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005139 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005140 RTC_LOG(LS_ERROR)
5141 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005142 return nullptr;
5143 }
5144 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005145 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005146 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005147 return nullptr;
5148 }
5149 }
5150
Steve Anton75737c02017-11-06 10:37:17 -08005151 rtc::scoped_refptr<DataChannel> channel(
5152 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005153 if (!channel) {
5154 sid_allocator_.ReleaseSid(new_config.id);
5155 return nullptr;
5156 }
5157
5158 if (channel->data_channel_type() == cricket::DCT_RTP) {
5159 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5161 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005162 return nullptr;
5163 }
5164 rtp_data_channels_[channel->label()] = channel;
5165 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005166 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005167 sctp_data_channels_.push_back(channel);
5168 channel->SignalClosed.connect(this,
5169 &PeerConnection::OnSctpDataChannelClosed);
5170 }
5171
Steve Anton2d8609c2018-01-23 16:38:46 -08005172 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005173 return channel;
5174}
5175
5176bool PeerConnection::HasDataChannels() const {
5177 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5178}
5179
5180void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005181 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005182 for (const auto& channel : sctp_data_channels_) {
5183 if (channel->id() < 0) {
5184 int sid;
5185 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005186 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5187 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005188 continue;
5189 }
5190 channel->SetSctpSid(sid);
5191 }
5192 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005193 // Since closing modifies the list of channels, we have to do the actual
5194 // closing outside the loop.
5195 for (const auto& channel : channels_to_close) {
5196 channel->CloseAbruptly();
5197 }
deadbeefab9b2d12015-10-14 11:33:11 -07005198}
5199
5200void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005201 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005202 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5203 ++it) {
5204 if (it->get() == channel) {
5205 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005206 // After the closing procedure is done, it's safe to use this ID for
5207 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005208 sid_allocator_.ReleaseSid(channel->id());
5209 }
deadbeefbd292462015-12-14 18:15:29 -08005210 // Since this method is triggered by a signal from the DataChannel,
5211 // we can't free it directly here; we need to free it asynchronously.
5212 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005213 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005214 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5215 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005216 return;
5217 }
5218 }
5219}
5220
deadbeefab9b2d12015-10-14 11:33:11 -07005221void PeerConnection::OnDataChannelDestroyed() {
5222 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5223 // DataChannel may callback to us and try to modify the list.
5224 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5225 temp_rtp_dcs.swap(rtp_data_channels_);
5226 for (const auto& kv : temp_rtp_dcs) {
5227 kv.second->OnTransportChannelDestroyed();
5228 }
5229
5230 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5231 temp_sctp_dcs.swap(sctp_data_channels_);
5232 for (const auto& channel : temp_sctp_dcs) {
5233 channel->OnTransportChannelDestroyed();
5234 }
5235}
5236
5237void PeerConnection::OnDataChannelOpenMessage(
5238 const std::string& label,
5239 const InternalDataChannelInit& config) {
5240 rtc::scoped_refptr<DataChannel> channel(
5241 InternalCreateDataChannel(label, &config));
5242 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005243 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005244 return;
5245 }
5246
deadbeefa601f5c2016-06-06 14:27:39 -07005247 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5248 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005249 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005250 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005251}
5252
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005253bool PeerConnection::HandleOpenMessage_s(
5254 const cricket::ReceiveDataParams& params,
5255 const rtc::CopyOnWriteBuffer& buffer) {
5256 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5257 // Received OPEN message; parse and signal that a new data channel should
5258 // be created.
5259 std::string label;
5260 InternalDataChannelInit config;
5261 config.id = params.ssrc;
5262 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5263 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5264 << params.ssrc;
5265 return true;
5266 }
5267 config.open_handshake_role = InternalDataChannelInit::kAcker;
5268 OnDataChannelOpenMessage(label, config);
5269 return true;
5270 }
5271 return false;
5272}
5273
Steve Anton4171afb2017-11-20 10:20:22 -08005274rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5275PeerConnection::GetAudioTransceiver() const {
5276 // This method only works with Plan B SDP, where there is a single
5277 // audio/video transceiver.
5278 RTC_DCHECK(!IsUnifiedPlan());
5279 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005280 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005281 return transceiver;
5282 }
5283 }
5284 RTC_NOTREACHED();
5285 return nullptr;
5286}
5287
5288rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5289PeerConnection::GetVideoTransceiver() const {
5290 // This method only works with Plan B SDP, where there is a single
5291 // audio/video transceiver.
5292 RTC_DCHECK(!IsUnifiedPlan());
5293 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005294 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005295 return transceiver;
5296 }
5297 }
5298 RTC_NOTREACHED();
5299 return nullptr;
5300}
5301
5302// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5303// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005304bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005305 switch (type) {
5306 case cricket::MEDIA_TYPE_AUDIO:
5307 return !GetAudioTransceiver()->internal()->senders().empty();
5308 case cricket::MEDIA_TYPE_VIDEO:
5309 return !GetVideoTransceiver()->internal()->senders().empty();
5310 case cricket::MEDIA_TYPE_DATA:
5311 return false;
5312 }
5313 RTC_NOTREACHED();
5314 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005315}
5316
Steve Anton4171afb2017-11-20 10:20:22 -08005317rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5318PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005319 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005320 for (auto sender : transceiver->internal()->senders()) {
5321 if (sender->track() == track) {
5322 return sender;
5323 }
5324 }
5325 }
5326 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005327}
5328
Steve Anton4171afb2017-11-20 10:20:22 -08005329rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5330PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005331 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005332 for (auto sender : transceiver->internal()->senders()) {
5333 if (sender->id() == sender_id) {
5334 return sender;
5335 }
5336 }
5337 }
5338 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005339}
5340
Steve Anton4171afb2017-11-20 10:20:22 -08005341rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5342PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005343 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005344 for (auto receiver : transceiver->internal()->receivers()) {
5345 if (receiver->id() == receiver_id) {
5346 return receiver;
5347 }
5348 }
5349 }
5350 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005351}
5352
Steve Anton4171afb2017-11-20 10:20:22 -08005353std::vector<PeerConnection::RtpSenderInfo>*
5354PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5355 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5356 media_type == cricket::MEDIA_TYPE_VIDEO);
5357 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5358 ? &remote_audio_sender_infos_
5359 : &remote_video_sender_infos_;
5360}
5361
5362std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005363 cricket::MediaType media_type) {
5364 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5365 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005366 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5367 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005368}
5369
Steve Anton4171afb2017-11-20 10:20:22 -08005370const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5371 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005372 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005373 const std::string sender_id) const {
5374 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005375 if (sender_info.stream_id == stream_id &&
5376 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005377 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005378 }
5379 }
5380 return nullptr;
5381}
5382
5383DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5384 for (const auto& channel : sctp_data_channels_) {
5385 if (channel->id() == sid) {
5386 return channel;
5387 }
5388 }
5389 return nullptr;
5390}
5391
Karl Wibergfb3be392019-03-22 14:13:22 +01005392PeerConnection::InitializePortAllocatorResult
5393PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005394 const cricket::ServerAddresses& stun_servers,
5395 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005396 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005397 RTC_DCHECK_RUN_ON(network_thread());
5398
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005399 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005400 // To handle both internal and externally created port allocator, we will
5401 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005402 int port_allocator_flags = port_allocator_->flags();
5403 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5404 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5405 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005406 // If the disable-IPv6 flag was specified, we'll not override it
5407 // by experiment.
5408 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005409 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005410 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5411 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005412 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005413 }
5414
zhihuangb09b3f92017-03-07 14:40:51 -08005415 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005416 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005417 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005418 }
5419
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005420 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005421 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005422 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005423 }
5424
honghaiz60347052016-05-31 18:29:12 -07005425 if (configuration.candidate_network_policy ==
5426 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005427 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005428 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005429 }
5430
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005431 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005432 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005433 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5434 }
5435
Karl Wibergfb3be392019-03-22 14:13:22 +01005436 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005437 // No step delay is used while allocating ports.
5438 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005439 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005440 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005441 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005442
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005443 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005444 for (auto& turn_server : turn_servers_copy) {
5445 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005446 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005447 // Call this last since it may create pooled allocator sessions using the
5448 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005449 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005450 stun_servers, std::move(turn_servers_copy),
5451 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5452 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005453 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005454
5455 InitializePortAllocatorResult res;
5456 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5457 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005458}
5459
deadbeef91dd5672016-05-18 16:55:30 -07005460bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005461 const cricket::ServerAddresses& stun_servers,
5462 const std::vector<cricket::RelayServerConfig>& turn_servers,
5463 IceTransportsType type,
5464 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005465 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005466 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005467 absl::optional<int> stun_candidate_keepalive_interval,
5468 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005469 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005470 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005471 // According to JSEP, after setLocalDescription, changing the candidate pool
5472 // size is not allowed, and changing the set of ICE servers will not result
5473 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005474 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005475 port_allocator_->FreezeCandidatePool();
5476 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005477 // Add the custom tls turn servers if they exist.
5478 auto turn_servers_copy = turn_servers;
5479 for (auto& turn_server : turn_servers_copy) {
5480 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5481 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005482 // Call this last since it may create pooled allocator sessions using the
5483 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005484 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005485 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5486 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005487}
5488
Steve Antonba818672017-11-06 10:21:57 -08005489cricket::ChannelManager* PeerConnection::channel_manager() const {
5490 return factory_->channel_manager();
5491}
5492
Elad Alon99c3fe52017-10-13 16:29:40 +02005493bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005494 std::unique_ptr<RtcEventLogOutput> output,
5495 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005496 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005497 if (!event_log_) {
5498 return false;
5499 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005500 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005501}
5502
5503void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005504 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005505 if (event_log_) {
5506 event_log_->StopLogging();
5507 }
ivoc14d5dbe2016-07-04 07:06:55 -07005508}
nisseeaabdf62017-05-05 02:23:02 -07005509
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005510cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005511 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005512 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005513 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005514 if (channel && channel->content_name() == content_name) {
5515 return channel;
5516 }
Steve Anton75737c02017-11-06 10:37:17 -08005517 }
5518 if (rtp_data_channel() &&
5519 rtp_data_channel()->content_name() == content_name) {
5520 return rtp_data_channel();
5521 }
5522 return nullptr;
5523}
5524
5525bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005526 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005527 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005528 RTC_LOG(LS_INFO)
5529 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005530 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005531 return false;
5532 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005533 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005534 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005535 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005536 return false;
5537 }
5538
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005539 absl::optional<rtc::SSLRole> dtls_role;
5540 if (sctp_mid_) {
5541 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5542 } else if (is_caller_) {
5543 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5544 }
Zhi Huange830e682018-03-30 10:48:35 -07005545 if (dtls_role) {
5546 *role = *dtls_role;
5547 return true;
5548 }
5549 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005550}
5551
5552bool PeerConnection::GetSslRole(const std::string& content_name,
5553 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005554 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005555 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005556 RTC_LOG(LS_INFO)
5557 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005558 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005559 return false;
5560 }
5561
Zhi Huange830e682018-03-30 10:48:35 -07005562 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5563 if (dtls_role) {
5564 *role = *dtls_role;
5565 return true;
5566 }
5567 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005568}
5569
Steve Antonf8470812017-12-04 10:46:21 -08005570void PeerConnection::SetSessionError(SessionError error,
5571 const std::string& error_desc) {
5572 RTC_DCHECK_RUN_ON(signaling_thread());
5573 if (error != session_error_) {
5574 session_error_ = error;
5575 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005576 }
5577}
5578
Zhi Huange830e682018-03-30 10:48:35 -07005579RTCError PeerConnection::UpdateSessionState(
5580 SdpType type,
5581 cricket::ContentSource source,
5582 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005583 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005584
5585 // If there's already a pending error then no state transition should happen.
5586 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005587 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005588
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005589 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005590 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005591 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005592 }
5593
5594 // Update the signaling state according to the specified state machine (see
5595 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005596 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005597 ChangeSignalingState(source == cricket::CS_LOCAL
5598 ? PeerConnectionInterface::kHaveLocalOffer
5599 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005600 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005601 ChangeSignalingState(source == cricket::CS_LOCAL
5602 ? PeerConnectionInterface::kHaveLocalPrAnswer
5603 : PeerConnectionInterface::kHaveRemotePrAnswer);
5604 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005605 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005606 ChangeSignalingState(PeerConnectionInterface::kStable);
5607 }
5608
5609 // Update internal objects according to the session description's media
5610 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005611 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005612 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005613 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005614 }
5615
Steve Anton8a006912017-12-04 15:25:56 -08005616 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005617}
5618
Steve Anton8a006912017-12-04 15:25:56 -08005619RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005620 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005621 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005622 const SessionDescriptionInterface* sdesc =
5623 (source == cricket::CS_LOCAL ? local_description()
5624 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005625 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005626
5627 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005628 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005629 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005630 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005631 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005632 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005633 continue;
5634 }
5635 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005636 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005637 if (!content_desc) {
5638 continue;
5639 }
5640 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005641 bool success = (source == cricket::CS_LOCAL)
5642 ? channel->SetLocalContent(content_desc, type, &error)
5643 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005644 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005645 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005646 }
5647 }
5648
5649 // If using the RtpDataChannel, push down the new SDP section for it too.
5650 if (rtp_data_channel_) {
5651 const ContentInfo* data_content =
5652 cricket::GetFirstDataContent(sdesc->description());
5653 if (data_content && !data_content->rejected) {
5654 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005655 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005656 if (data_desc) {
5657 std::string error;
5658 bool success =
5659 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005660 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005661 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005662 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005663 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005664 }
Steve Anton75737c02017-11-06 10:37:17 -08005665 }
5666 }
5667 }
Steve Antoned10bd92017-12-05 10:52:59 -08005668
Steve Anton75737c02017-11-06 10:37:17 -08005669 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5670 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005671 if (sctp_transport_ && local_description() && remote_description()) {
5672 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5673 local_description()->description());
5674 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5675 remote_description()->description());
5676 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005677 int max_message_size;
5678 // A remote max message size of zero means "any size supported".
5679 // We configure the connection with our own max message size.
5680 if (remote_sctp_description->max_message_size() == 0) {
5681 max_message_size = local_sctp_description->max_message_size();
5682 } else {
5683 max_message_size =
5684 std::min(local_sctp_description->max_message_size(),
5685 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005686 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005687 sctp_transport_->Start(local_sctp_description->port(),
5688 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005689 }
Steve Anton75737c02017-11-06 10:37:17 -08005690 }
Steve Antoned10bd92017-12-05 10:52:59 -08005691
Steve Anton8a006912017-12-04 15:25:56 -08005692 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005693}
5694
Steve Anton8a006912017-12-04 15:25:56 -08005695RTCError PeerConnection::PushdownTransportDescription(
5696 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005697 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005698 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005699
Zhi Huange830e682018-03-30 10:48:35 -07005700 if (source == cricket::CS_LOCAL) {
5701 const SessionDescriptionInterface* sdesc = local_description();
5702 RTC_DCHECK(sdesc);
5703 return transport_controller_->SetLocalDescription(type,
5704 sdesc->description());
5705 } else {
5706 const SessionDescriptionInterface* sdesc = remote_description();
5707 RTC_DCHECK(sdesc);
5708 return transport_controller_->SetRemoteDescription(type,
5709 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005710 }
Steve Anton75737c02017-11-06 10:37:17 -08005711}
5712
5713bool PeerConnection::GetTransportDescription(
5714 const SessionDescription* description,
5715 const std::string& content_name,
5716 cricket::TransportDescription* tdesc) {
5717 if (!description || !tdesc) {
5718 return false;
5719 }
5720 const TransportInfo* transport_info =
5721 description->GetTransportInfoByName(content_name);
5722 if (!transport_info) {
5723 return false;
5724 }
5725 *tdesc = transport_info->description;
5726 return true;
5727}
5728
Steve Anton75737c02017-11-06 10:37:17 -08005729cricket::IceConfig PeerConnection::ParseIceConfig(
5730 const PeerConnectionInterface::RTCConfiguration& config) const {
5731 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005732 switch (config.continual_gathering_policy) {
5733 case PeerConnectionInterface::GATHER_ONCE:
5734 gathering_policy = cricket::GATHER_ONCE;
5735 break;
5736 case PeerConnectionInterface::GATHER_CONTINUALLY:
5737 gathering_policy = cricket::GATHER_CONTINUALLY;
5738 break;
5739 default:
5740 RTC_NOTREACHED();
5741 gathering_policy = cricket::GATHER_ONCE;
5742 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005743
Steve Anton75737c02017-11-06 10:37:17 -08005744 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005745 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5746 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005747 ice_config.prioritize_most_likely_candidate_pairs =
5748 config.prioritize_most_likely_ice_candidate_pairs;
5749 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005750 RTCConfigurationToIceConfigOptionalInt(
5751 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005752 ice_config.continual_gathering_policy = gathering_policy;
5753 ice_config.presume_writable_when_fully_relayed =
5754 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005755 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5756 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005757 ice_config.ice_check_interval_strong_connectivity =
5758 config.ice_check_interval_strong_connectivity;
5759 ice_config.ice_check_interval_weak_connectivity =
5760 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005761 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005762 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5763 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005764 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005765 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005766 ice_config.regather_all_networks_interval_range =
5767 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005768 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005769 return ice_config;
5770}
5771
Steve Anton75737c02017-11-06 10:37:17 -08005772bool PeerConnection::SendData(const cricket::SendDataParams& params,
5773 const rtc::CopyOnWriteBuffer& payload,
5774 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005775 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005776 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5777 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5778 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005779 return false;
5780 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005781 if (media_transport_) {
5782 SendDataParams send_params;
5783 send_params.type = ToWebrtcDataMessageType(params.type);
5784 send_params.ordered = params.ordered;
5785 if (params.max_rtx_count >= 0) {
5786 send_params.max_rtx_count = params.max_rtx_count;
5787 } else if (params.max_rtx_ms >= 0) {
5788 send_params.max_rtx_ms = params.max_rtx_ms;
5789 }
5790 return media_transport_->SendData(params.sid, send_params, payload).ok();
5791 }
Steve Anton75737c02017-11-06 10:37:17 -08005792 return rtp_data_channel_
5793 ? rtp_data_channel_->SendData(params, payload, result)
5794 : network_thread()->Invoke<bool>(
5795 RTC_FROM_HERE,
5796 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005797 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005798}
5799
5800bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005801 RTC_DCHECK_RUN_ON(signaling_thread());
5802 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005803 // Don't log an error here, because DataChannels are expected to call
5804 // ConnectDataChannel in this state. It's the only way to initially tell
5805 // whether or not the underlying transport is ready.
5806 return false;
5807 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005808 if (media_transport_) {
5809 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5810 &DataChannel::OnChannelReady);
5811 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5812 &DataChannel::OnDataReceived);
5813 SignalMediaTransportChannelClosing_s.connect(
5814 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5815 SignalMediaTransportChannelClosed_s.connect(
5816 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5817 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005818 rtp_data_channel_->SignalReadyToSendData.connect(
5819 webrtc_data_channel, &DataChannel::OnChannelReady);
5820 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5821 &DataChannel::OnDataReceived);
5822 } else {
5823 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5824 &DataChannel::OnChannelReady);
5825 SignalSctpDataReceived.connect(webrtc_data_channel,
5826 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005827 SignalSctpClosingProcedureStartedRemotely.connect(
5828 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5829 SignalSctpClosingProcedureComplete.connect(
5830 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005831 }
5832 return true;
5833}
5834
5835void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005836 RTC_DCHECK_RUN_ON(signaling_thread());
5837 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005838 RTC_LOG(LS_ERROR)
5839 << "DisconnectDataChannel called when rtp_data_channel_ and "
5840 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005841 return;
5842 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005843 if (media_transport_) {
5844 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5845 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5846 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5847 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5848 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005849 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5850 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5851 } else {
5852 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5853 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005854 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5855 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005856 }
5857}
5858
5859void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005860 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005861 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005862 return;
5863 }
Steve Anton75737c02017-11-06 10:37:17 -08005864 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005865 RTC_LOG(LS_ERROR)
5866 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005867 return;
5868 }
5869 network_thread()->Invoke<void>(
5870 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005871 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005872}
5873
5874void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005875 if (media_transport_) {
5876 media_transport_->CloseChannel(sid);
5877 return;
5878 }
Steve Anton75737c02017-11-06 10:37:17 -08005879 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005880 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005881 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005882 return;
5883 }
5884 network_thread()->Invoke<void>(
5885 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005886 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005887}
5888
5889bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005890 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005891 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005892 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005893 sctp_ready_to_send_data_;
5894}
5895
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005896void PeerConnection::OnDataReceived(int channel_id,
5897 DataMessageType type,
5898 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005899 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005900 cricket::ReceiveDataParams params;
5901 params.sid = channel_id;
5902 params.type = ToCricketDataMessageType(type);
5903 media_transport_invoker_->AsyncInvoke<void>(
5904 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5905 RTC_DCHECK_RUN_ON(signaling_thread());
5906 if (!HandleOpenMessage_s(params, buffer)) {
5907 SignalMediaTransportReceivedData_s(params, buffer);
5908 }
5909 });
5910}
5911
5912void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005913 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005914 media_transport_invoker_->AsyncInvoke<void>(
5915 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5916 RTC_DCHECK_RUN_ON(signaling_thread());
5917 SignalMediaTransportChannelClosing_s(channel_id);
5918 });
5919}
5920
5921void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005922 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005923 media_transport_invoker_->AsyncInvoke<void>(
5924 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5925 RTC_DCHECK_RUN_ON(signaling_thread());
5926 SignalMediaTransportChannelClosed_s(channel_id);
5927 });
5928}
5929
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005930absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005931 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005932 if (sctp_mid_ && transport_controller_) {
5933 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5934 if (dtls_transport) {
5935 return dtls_transport->transport_name();
5936 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005937 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005938 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005939 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005940}
5941
Qingsi Wang72a43a12018-02-20 16:03:18 -08005942cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5943 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005944 network_thread()->Invoke<void>(
5945 RTC_FROM_HERE,
5946 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5947 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005948 return candidate_states_list;
5949}
5950
Steve Anton5dfde182018-02-06 10:34:40 -08005951std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5952 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005953 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005954 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005955 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005956 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005957 if (channel) {
5958 transport_names_by_mid[channel->content_name()] =
5959 channel->transport_name();
5960 }
Steve Anton75737c02017-11-06 10:37:17 -08005961 }
Steve Anton5dfde182018-02-06 10:34:40 -08005962 if (rtp_data_channel_) {
5963 transport_names_by_mid[rtp_data_channel_->content_name()] =
5964 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005965 }
5966 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005967 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005968 RTC_DCHECK(transport_name);
5969 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005970 }
Steve Anton5dfde182018-02-06 10:34:40 -08005971 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005972}
5973
Steve Anton5dfde182018-02-06 10:34:40 -08005974std::map<std::string, cricket::TransportStats>
5975PeerConnection::GetTransportStatsByNames(
5976 const std::set<std::string>& transport_names) {
5977 if (!network_thread()->IsCurrent()) {
5978 return network_thread()
5979 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5980 RTC_FROM_HERE,
5981 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005982 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005983 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005984 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5985 for (const std::string& transport_name : transport_names) {
5986 cricket::TransportStats transport_stats;
5987 bool success =
5988 transport_controller_->GetStats(transport_name, &transport_stats);
5989 if (success) {
5990 transport_stats_by_name[transport_name] = std::move(transport_stats);
5991 } else {
5992 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5993 << transport_name;
5994 }
5995 }
5996 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005997}
5998
5999bool PeerConnection::GetLocalCertificate(
6000 const std::string& transport_name,
6001 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006002 if (!certificate) {
6003 return false;
6004 }
6005 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6006 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006007}
6008
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006009std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006010 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006011 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006012}
6013
6014cricket::DataChannelType PeerConnection::data_channel_type() const {
6015 return data_channel_type_;
6016}
6017
6018bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006019 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006020 return pending_ice_restarts_.find(content_name) !=
6021 pending_ice_restarts_.end();
6022}
6023
Steve Anton75737c02017-11-06 10:37:17 -08006024bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6025 return transport_controller_->NeedsIceRestart(content_name);
6026}
6027
6028void PeerConnection::OnCertificateReady(
6029 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6030 transport_controller_->SetLocalCertificate(certificate);
6031}
6032
6033void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006034 SetSessionError(SessionError::kTransport,
6035 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006036}
6037
Alex Loiko9289eda2018-11-23 16:18:59 +00006038void PeerConnection::OnTransportControllerConnectionState(
6039 cricket::IceConnectionState state) {
6040 switch (state) {
6041 case cricket::kIceConnectionConnecting:
6042 // If the current state is Connected or Completed, then there were
6043 // writable channels but now there are not, so the next state must
6044 // be Disconnected.
6045 // kIceConnectionConnecting is currently used as the default,
6046 // un-connected state by the TransportController, so its only use is
6047 // detecting disconnections.
6048 if (ice_connection_state_ ==
6049 PeerConnectionInterface::kIceConnectionConnected ||
6050 ice_connection_state_ ==
6051 PeerConnectionInterface::kIceConnectionCompleted) {
6052 SetIceConnectionState(
6053 PeerConnectionInterface::kIceConnectionDisconnected);
6054 }
6055 break;
6056 case cricket::kIceConnectionFailed:
6057 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6058 break;
6059 case cricket::kIceConnectionConnected:
6060 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6061 "all transports are writable.";
6062 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6063 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6064 break;
6065 case cricket::kIceConnectionCompleted:
6066 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6067 "all transports are complete.";
6068 if (ice_connection_state_ !=
6069 PeerConnectionInterface::kIceConnectionConnected) {
6070 // If jumping directly from "checking" to "connected",
6071 // signal "connected" first.
6072 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6073 }
6074 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6075 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6076 ReportTransportStats();
6077 break;
6078 default:
6079 RTC_NOTREACHED();
6080 }
6081}
6082
Steve Anton75737c02017-11-06 10:37:17 -08006083void PeerConnection::OnTransportControllerCandidatesGathered(
6084 const std::string& transport_name,
6085 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006086 int sdp_mline_index;
6087 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006088 RTC_LOG(LS_ERROR)
6089 << "OnTransportControllerCandidatesGathered: content name "
6090 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006091 return;
6092 }
6093
6094 for (cricket::Candidates::const_iterator citer = candidates.begin();
6095 citer != candidates.end(); ++citer) {
6096 // Use transport_name as the candidate media id.
6097 std::unique_ptr<JsepIceCandidate> candidate(
6098 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6099 if (local_description()) {
6100 mutable_local_description()->AddCandidate(candidate.get());
6101 }
6102 OnIceCandidate(std::move(candidate));
6103 }
6104}
6105
6106void PeerConnection::OnTransportControllerCandidatesRemoved(
6107 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006108 // Sanity check.
6109 for (const cricket::Candidate& candidate : candidates) {
6110 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006111 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006112 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006113 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006114 return;
6115 }
6116 }
6117
6118 if (local_description()) {
6119 mutable_local_description()->RemoveCandidates(candidates);
6120 }
6121 OnIceCandidatesRemoved(candidates);
6122}
6123
6124void PeerConnection::OnTransportControllerDtlsHandshakeError(
6125 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006126 RTC_HISTOGRAM_ENUMERATION(
6127 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6128 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006129}
6130
Steve Antoned10bd92017-12-05 10:52:59 -08006131void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006132 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006133 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006134 if (channel && !channel->enabled()) {
6135 channel->Enable(true);
6136 }
Steve Anton75737c02017-11-06 10:37:17 -08006137 }
6138
Steve Anton4171afb2017-11-20 10:20:22 -08006139 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006140 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006141 }
Steve Anton75737c02017-11-06 10:37:17 -08006142}
6143
6144// Returns the media index for a local ice candidate given the content name.
6145bool PeerConnection::GetLocalCandidateMediaIndex(
6146 const std::string& content_name,
6147 int* sdp_mline_index) {
6148 if (!local_description() || !sdp_mline_index) {
6149 return false;
6150 }
6151
6152 bool content_found = false;
6153 const ContentInfos& contents = local_description()->description()->contents();
6154 for (size_t index = 0; index < contents.size(); ++index) {
6155 if (contents[index].name == content_name) {
6156 *sdp_mline_index = static_cast<int>(index);
6157 content_found = true;
6158 break;
6159 }
6160 }
6161 return content_found;
6162}
6163
6164bool PeerConnection::UseCandidatesInSessionDescription(
6165 const SessionDescriptionInterface* remote_desc) {
6166 if (!remote_desc) {
6167 return true;
6168 }
6169 bool ret = true;
6170
6171 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6172 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6173 for (size_t n = 0; n < candidates->count(); ++n) {
6174 const IceCandidateInterface* candidate = candidates->at(n);
6175 bool valid = false;
6176 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6177 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006178 RTC_LOG(LS_INFO)
6179 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006180 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006181 }
6182 continue;
6183 }
6184 ret = UseCandidate(candidate);
6185 if (!ret) {
6186 break;
6187 }
6188 }
6189 }
6190 return ret;
6191}
6192
6193bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006194 RTCErrorOr<const cricket::ContentInfo*> result =
6195 FindContentInfo(remote_description(), candidate);
6196 if (!result.ok()) {
6197 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6198 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006199 return false;
6200 }
Steve Anton75737c02017-11-06 10:37:17 -08006201 std::vector<cricket::Candidate> candidates;
6202 candidates.push_back(candidate->candidate());
6203 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006204 RTCError error = transport_controller_->AddRemoteCandidates(
6205 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006206 if (error.ok()) {
6207 // Candidates successfully submitted for checking.
6208 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6209 ice_connection_state_ ==
6210 PeerConnectionInterface::kIceConnectionDisconnected) {
6211 // If state is New, then the session has just gotten its first remote ICE
6212 // candidates, so go to Checking.
6213 // If state is Disconnected, the session is re-using old candidates or
6214 // receiving additional ones, so go to Checking.
6215 // If state is Connected, stay Connected.
6216 // TODO(bemasc): If state is Connected, and the new candidates are for a
6217 // newly added transport, then the state actually _should_ move to
6218 // checking. Add a way to distinguish that case.
6219 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6220 }
6221 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006222 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006223 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006224 }
6225 return true;
6226}
6227
Guido Urdaneta41633172019-05-23 20:12:29 +02006228RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6229 const SessionDescriptionInterface* description,
6230 const IceCandidateInterface* candidate) {
6231 if (candidate->sdp_mline_index() >= 0) {
6232 size_t mediacontent_index =
6233 static_cast<size_t>(candidate->sdp_mline_index());
6234 size_t content_size = description->description()->contents().size();
6235 if (mediacontent_index < content_size) {
6236 return &description->description()->contents()[mediacontent_index];
6237 } else {
6238 return RTCError(RTCErrorType::INVALID_RANGE,
6239 "Media line index (" +
6240 rtc::ToString(candidate->sdp_mline_index()) +
6241 ") out of range (number of mlines: " +
6242 rtc::ToString(content_size) + ").");
6243 }
6244 } else if (!candidate->sdp_mid().empty()) {
6245 auto& contents = description->description()->contents();
6246 auto it = absl::c_find_if(
6247 contents, [candidate](const cricket::ContentInfo& content_info) {
6248 return content_info.mid() == candidate->sdp_mid();
6249 });
6250 if (it == contents.end()) {
6251 return RTCError(
6252 RTCErrorType::INVALID_PARAMETER,
6253 "Mid " + candidate->sdp_mid() +
6254 " specified but no media section with that mid found.");
6255 } else {
6256 return &*it;
6257 }
6258 }
6259
6260 return RTCError(RTCErrorType::INVALID_PARAMETER,
6261 "Neither sdp_mline_index nor sdp_mid specified.");
6262}
6263
Steve Anton75737c02017-11-06 10:37:17 -08006264void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006265 // Destroy video channel first since it may have a pointer to the
6266 // voice channel.
6267 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006268 if (!video_info || video_info->rejected) {
6269 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006270 }
6271
Steve Anton6fec8802017-12-04 10:37:29 -08006272 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6273 if (!audio_info || audio_info->rejected) {
6274 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006275 }
6276
6277 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6278 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006279 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006280 }
6281}
6282
Steve Antondcc3c022017-12-22 16:02:54 -08006283RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6284 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006285 const cricket::ContentGroup* bundle_group = nullptr;
6286 if (configuration_.bundle_policy ==
6287 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006288 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006289 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006290 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6291 "max-bundle configured but session description "
6292 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006293 }
6294 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006295 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006296}
6297
6298RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006299 // Creating the media channels. Transports should already have been created
6300 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006301 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006302 if (voice && !voice->rejected &&
6303 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006304 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006305 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006306 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6307 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006308 }
6309 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6310 }
6311
Steve Antondcc3c022017-12-22 16:02:54 -08006312 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006313 if (video && !video->rejected &&
6314 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006315 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006316 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006317 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6318 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006319 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006320 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006321 }
6322
Steve Antondcc3c022017-12-22 16:02:54 -08006323 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006324 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006325 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006326 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006327 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6328 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006329 }
6330 }
6331
Steve Anton8a006912017-12-04 15:25:56 -08006332 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006333}
6334
Steve Anton4171afb2017-11-20 10:20:22 -08006335// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006336cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006337 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006338 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006339 MediaTransportConfig media_transport_config =
6340 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006341
Steve Anton75737c02017-11-06 10:37:17 -08006342 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006343 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006344 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6345 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006346 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006347 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006348 }
Steve Anton75737c02017-11-06 10:37:17 -08006349 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6350 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006351 voice_channel->SignalSentPacket.connect(this,
6352 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006353 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006354
Steve Antoneda6ccd2017-12-04 10:21:55 -08006355 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006356}
6357
Steve Anton4171afb2017-11-20 10:20:22 -08006358// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006359cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006360 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006361 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006362 MediaTransportConfig media_transport_config =
6363 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006364
Steve Anton75737c02017-11-06 10:37:17 -08006365 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006366 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006367 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6368 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006369 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006370 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006371 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006372 }
Steve Anton75737c02017-11-06 10:37:17 -08006373 video_channel->SignalDtlsSrtpSetupFailure.connect(
6374 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006375 video_channel->SignalSentPacket.connect(this,
6376 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006377 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006378
Steve Antoneda6ccd2017-12-04 10:21:55 -08006379 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006380}
6381
Zhi Huange830e682018-03-30 10:48:35 -07006382bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006383 switch (data_channel_type_) {
6384 case cricket::DCT_MEDIA_TRANSPORT:
6385 if (network_thread()->Invoke<bool>(
6386 RTC_FROM_HERE,
6387 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6388 this, mid))) {
6389 for (const auto& channel : sctp_data_channels_) {
6390 channel->OnTransportChannelCreated();
6391 }
6392 return true;
6393 }
Steve Anton75737c02017-11-06 10:37:17 -08006394 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006395 case cricket::DCT_SCTP:
6396 if (!sctp_factory_) {
6397 RTC_LOG(LS_ERROR)
6398 << "Trying to create SCTP transport, but didn't compile with "
6399 "SCTP support (HAVE_SCTP)";
6400 return false;
6401 }
6402 if (!network_thread()->Invoke<bool>(
6403 RTC_FROM_HERE,
6404 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6405 return false;
6406 }
6407 for (const auto& channel : sctp_data_channels_) {
6408 channel->OnTransportChannelCreated();
6409 }
6410 return true;
6411 case cricket::DCT_RTP:
6412 default:
6413 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6414 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6415 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006416 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006417 if (!rtp_data_channel_) {
6418 return false;
6419 }
6420 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6421 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6422 rtp_data_channel_->SignalSentPacket.connect(
6423 this, &PeerConnection::OnSentPacket_w);
6424 rtp_data_channel_->SetRtpTransport(rtp_transport);
6425 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006426 }
6427
Steve Anton75737c02017-11-06 10:37:17 -08006428 return true;
6429}
6430
6431Call::Stats PeerConnection::GetCallStats() {
6432 if (!worker_thread()->IsCurrent()) {
6433 return worker_thread()->Invoke<Call::Stats>(
6434 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6435 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006436 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006437 if (call_) {
6438 return call_->GetStats();
6439 } else {
6440 return Call::Stats();
6441 }
6442}
6443
Zhi Huange830e682018-03-30 10:48:35 -07006444bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006445 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006446 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006447 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6448 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006449 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006450 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006451 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006452 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6453 sctp_factory_->CreateSctpTransport(dtls_transport);
6454 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006455 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006456 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006457 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006458 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006459 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006460 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6461 // another thread. Would be nice if there was a helper class similar to
6462 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6463 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006464 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006465 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006466 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006467 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006468 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006469 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6470 std::move(cricket_sctp_transport));
6471 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006472 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006473}
6474
6475void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006476 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006477 sctp_transport_->Clear();
6478 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006479 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006480 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006481}
6482
6483void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006484 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006485 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006486 // Note: Cannot use rtc::Bind here because it will grab a reference to
6487 // PeerConnection and potentially cause PeerConnection to live longer than
6488 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6489 // be destroyed before PeerConnection is destroyed, and at that point all
6490 // pending tasks will be cleared.
6491 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6492 OnSctpTransportReadyToSendData_s(true);
6493 });
6494}
6495
6496void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006497 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006498 sctp_ready_to_send_data_ = ready;
6499 SignalSctpReadyToSendData(ready);
6500}
6501
6502void PeerConnection::OnSctpTransportDataReceived_n(
6503 const cricket::ReceiveDataParams& params,
6504 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006505 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006506 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006507 // Note: Cannot use rtc::Bind here because it will grab a reference to
6508 // PeerConnection and potentially cause PeerConnection to live longer than
6509 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6510 // be destroyed before PeerConnection is destroyed, and at that point all
6511 // pending tasks will be cleared.
6512 sctp_invoker_->AsyncInvoke<void>(
6513 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6514 OnSctpTransportDataReceived_s(params, payload);
6515 });
6516}
6517
6518void PeerConnection::OnSctpTransportDataReceived_s(
6519 const cricket::ReceiveDataParams& params,
6520 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006521 RTC_DCHECK_RUN_ON(signaling_thread());
6522 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006523 SignalSctpDataReceived(params, payload);
6524 }
6525}
6526
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006527void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006528 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006529 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006530 sctp_invoker_->AsyncInvoke<void>(
6531 RTC_FROM_HERE, signaling_thread(),
6532 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006533 &SignalSctpClosingProcedureStartedRemotely, sid));
6534}
6535
6536void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006537 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006538 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006539 sctp_invoker_->AsyncInvoke<void>(
6540 RTC_FROM_HERE, signaling_thread(),
6541 rtc::Bind(&sigslot::signal1<int>::operator(),
6542 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006543}
6544
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006545bool PeerConnection::SetupMediaTransportForDataChannels_n(
6546 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006547 media_transport_ =
6548 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006549 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006550 RTC_LOG(LS_ERROR)
6551 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006552 return false;
6553 }
6554
6555 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6556 media_transport_->SetDataSink(this);
6557 media_transport_data_mid_ = mid;
6558 transport_controller_->SignalMediaTransportStateChanged.connect(
6559 this, &PeerConnection::OnMediaTransportStateChanged_n);
6560 // Check the initial state right away, in case transport is already writable.
6561 OnMediaTransportStateChanged_n();
6562 return true;
6563}
6564
6565void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6566 if (!media_transport_) {
6567 return;
6568 }
6569 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6570 media_transport_data_mid_.reset();
6571 media_transport_->SetDataSink(nullptr);
6572 media_transport_invoker_ = nullptr;
6573 media_transport_ = nullptr;
6574}
6575
6576void PeerConnection::OnMediaTransportStateChanged_n() {
6577 if (!media_transport_data_mid_ ||
6578 transport_controller_->GetMediaTransportState(
6579 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6580 return;
6581 }
6582 media_transport_invoker_->AsyncInvoke<void>(
6583 RTC_FROM_HERE, signaling_thread(), [this] {
6584 RTC_DCHECK_RUN_ON(signaling_thread());
6585 media_transport_ready_to_send_data_ = true;
6586 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6587 });
6588}
6589
Steve Anton75737c02017-11-06 10:37:17 -08006590// Returns false if bundle is enabled and rtcp_mux is disabled.
6591bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6592 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6593 if (!bundle_enabled)
6594 return true;
6595
6596 const cricket::ContentGroup* bundle_group =
6597 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6598 RTC_DCHECK(bundle_group != NULL);
6599
6600 const cricket::ContentInfos& contents = desc->contents();
6601 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6602 citer != contents.end(); ++citer) {
6603 const cricket::ContentInfo* content = (&*citer);
6604 RTC_DCHECK(content != NULL);
6605 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006606 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006607 if (!HasRtcpMuxEnabled(content))
6608 return false;
6609 }
6610 }
6611 // RTCP-MUX is enabled in all the contents.
6612 return true;
6613}
6614
6615bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006616 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006617}
6618
Steve Anton06817cd2018-12-18 15:55:30 -08006619static RTCError ValidateMids(const cricket::SessionDescription& description) {
6620 std::set<std::string> mids;
6621 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006622 if (content.name.empty()) {
6623 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6624 "A media section is missing a MID attribute.");
6625 }
Steve Anton06817cd2018-12-18 15:55:30 -08006626 if (!mids.insert(content.name).second) {
6627 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6628 "Duplicate a=mid value '" + content.name + "'.");
6629 }
6630 }
6631 return RTCError::OK();
6632}
6633
Steve Anton8a006912017-12-04 15:25:56 -08006634RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006635 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006636 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006637 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006638 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006639 }
6640
6641 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006642 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006643 }
6644
Steve Anton3828c062017-12-06 10:34:51 -08006645 SdpType type = sdesc->GetType();
6646 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6647 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006648 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006649 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006650 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
6652
Steve Anton06817cd2018-12-18 15:55:30 -08006653 RTCError error = ValidateMids(*sdesc->description());
6654 if (!error.ok()) {
6655 return error;
6656 }
6657
Steve Anton75737c02017-11-06 10:37:17 -08006658 // Verify crypto settings.
6659 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006660 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6661 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006662 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006663 if (!crypto_error.ok()) {
6664 return crypto_error;
6665 }
Steve Anton75737c02017-11-06 10:37:17 -08006666 }
6667
6668 // Verify ice-ufrag and ice-pwd.
6669 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6671 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006672 }
6673
6674 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6676 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006677 }
6678
6679 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6680 // m-lines that do not rtcp-mux enabled.
6681
6682 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006683 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006684 // With an answer we want to compare the new answer session description with
6685 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006686 const cricket::SessionDescription* offer_desc =
6687 (source == cricket::CS_LOCAL) ? remote_description()->description()
6688 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006689 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6690 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6691 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006692 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6693 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006694 }
6695 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006696 // The re-offers should respect the order of m= sections in current
6697 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006698 // With a re-offer, either the current local or current remote descriptions
6699 // could be the most up to date, so we would like to check against both of
6700 // them if they exist. It could be the case that one of them has a 0 port
6701 // for a media section, but the other does not. This is important to check
6702 // against in the case that we are recycling an m= section.
6703 const cricket::SessionDescription* current_desc = nullptr;
6704 const cricket::SessionDescription* secondary_current_desc = nullptr;
6705 if (local_description()) {
6706 current_desc = local_description()->description();
6707 if (remote_description()) {
6708 secondary_current_desc = remote_description()->description();
6709 }
6710 } else if (remote_description()) {
6711 current_desc = remote_description()->description();
6712 }
Steve Anton75737c02017-11-06 10:37:17 -08006713 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006714 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6715 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6717 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006718 }
6719 }
6720
Steve Antonba42e992018-04-09 14:10:01 -07006721 if (IsUnifiedPlan()) {
6722 // Ensure that each audio and video media section has at most one
6723 // "StreamParams". This will return an error if receiving a session
6724 // description from a "Plan B" endpoint which adds multiple tracks of the
6725 // same type. With Unified Plan, there can only be at most one track per
6726 // media section.
6727 for (const ContentInfo& content : sdesc->description()->contents()) {
6728 const MediaContentDescription& desc = *content.description;
6729 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6730 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6731 desc.streams().size() > 1u) {
6732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6733 "Media section has more than one track specified "
6734 "with a=ssrc lines which is not supported with "
6735 "Unified Plan.");
6736 }
6737 }
6738 }
6739
Steve Anton8a006912017-12-04 15:25:56 -08006740 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006741}
6742
Steve Anton3828c062017-12-06 10:34:51 -08006743bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006744 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006745 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006746 return (state == PeerConnectionInterface::kStable) ||
6747 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006748 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006749 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006750 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6751 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6752 }
6753}
6754
Steve Anton3828c062017-12-06 10:34:51 -08006755bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006756 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006757 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006758 return (state == PeerConnectionInterface::kStable) ||
6759 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006760 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006761 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006762 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6763 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6764 }
6765}
6766
Steve Antonf8470812017-12-04 10:46:21 -08006767const char* PeerConnection::SessionErrorToString(SessionError error) const {
6768 switch (error) {
6769 case SessionError::kNone:
6770 return "ERROR_NONE";
6771 case SessionError::kContent:
6772 return "ERROR_CONTENT";
6773 case SessionError::kTransport:
6774 return "ERROR_TRANSPORT";
6775 }
6776 RTC_NOTREACHED();
6777 return "";
6778}
6779
Steve Anton75737c02017-11-06 10:37:17 -08006780std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006781 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006782 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6783 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006784 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006785}
6786
Steve Anton8e20f172018-03-06 10:55:04 -08006787void PeerConnection::ReportSdpFormatReceived(
6788 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006789 int num_audio_mlines = 0;
6790 int num_video_mlines = 0;
6791 int num_audio_tracks = 0;
6792 int num_video_tracks = 0;
6793 for (const ContentInfo& content : remote_offer.description()->contents()) {
6794 cricket::MediaType media_type = content.media_description()->type();
6795 int num_tracks = std::max(
6796 1, static_cast<int>(content.media_description()->streams().size()));
6797 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6798 num_audio_mlines += 1;
6799 num_audio_tracks += num_tracks;
6800 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6801 num_video_mlines += 1;
6802 num_video_tracks += num_tracks;
6803 }
6804 }
6805 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6806 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6807 format = kSdpFormatReceivedComplexUnifiedPlan;
6808 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6809 format = kSdpFormatReceivedComplexPlanB;
6810 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6811 format = kSdpFormatReceivedSimple;
6812 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006813 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6814 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006815}
6816
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006817void PeerConnection::NoteUsageEvent(UsageEvent event) {
6818 RTC_DCHECK_RUN_ON(signaling_thread());
6819 usage_event_accumulator_ |= static_cast<int>(event);
6820}
6821
6822void PeerConnection::ReportUsagePattern() const {
6823 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006824 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6825 usage_event_accumulator_,
6826 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006827 const int bad_bits =
6828 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6829 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6830 const int good_bits =
6831 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6832 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6833 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6834 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6835 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006836 // If called after close(), we can't report, because observer may have
6837 // been deallocated, and therefore pointer is null. Write to log instead.
6838 if (observer_) {
6839 Observer()->OnInterestingUsage(usage_event_accumulator_);
6840 } else {
6841 RTC_LOG(LS_INFO) << "Interesting usage signature "
6842 << usage_event_accumulator_
6843 << " observed after observer shutdown";
6844 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006845 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006846}
6847
Steve Anton0ffaaa22018-02-23 10:31:30 -08006848void PeerConnection::ReportNegotiatedSdpSemantics(
6849 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006850 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006851 switch (answer.description()->msid_signaling()) {
6852 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006853 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006854 break;
6855 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006856 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006857 break;
6858 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006859 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006860 break;
6861 case cricket::kMsidSignalingMediaSection |
6862 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006863 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006864 break;
6865 default:
6866 RTC_NOTREACHED();
6867 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006868 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6869 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006870}
6871
Steve Anton75737c02017-11-06 10:37:17 -08006872// We need to check the local/remote description for the Transport instead of
6873// the session, because a new Transport added during renegotiation may have
6874// them unset while the session has them set from the previous negotiation.
6875// Not doing so may trigger the auto generation of transport description and
6876// mess up DTLS identity information, ICE credential, etc.
6877bool PeerConnection::ReadyToUseRemoteCandidate(
6878 const IceCandidateInterface* candidate,
6879 const SessionDescriptionInterface* remote_desc,
6880 bool* valid) {
6881 *valid = true;
6882
6883 const SessionDescriptionInterface* current_remote_desc =
6884 remote_desc ? remote_desc : remote_description();
6885
6886 if (!current_remote_desc) {
6887 return false;
6888 }
6889
Guido Urdaneta41633172019-05-23 20:12:29 +02006890 RTCErrorOr<const cricket::ContentInfo*> result =
6891 FindContentInfo(current_remote_desc, candidate);
6892 if (!result.ok()) {
6893 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6894 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006895
6896 *valid = false;
6897 return false;
6898 }
6899
Guido Urdaneta41633172019-05-23 20:12:29 +02006900 std::string transport_name = GetTransportName(result.value()->name);
6901 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006902}
6903
6904bool PeerConnection::SrtpRequired() const {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006905 return !configuration_.use_datagram_transport &&
6906 (dtls_enabled_ ||
6907 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006908}
6909
6910void PeerConnection::OnTransportControllerGatheringState(
6911 cricket::IceGatheringState state) {
6912 RTC_DCHECK(signaling_thread()->IsCurrent());
6913 if (state == cricket::kIceGatheringGathering) {
6914 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6915 } else if (state == cricket::kIceGatheringComplete) {
6916 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6917 }
6918}
6919
6920void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006921 std::map<std::string, std::set<cricket::MediaType>>
6922 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006923 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006924 if (transceiver->internal()->channel()) {
6925 const std::string& transport_name =
6926 transceiver->internal()->channel()->transport_name();
6927 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006928 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006929 }
Steve Anton75737c02017-11-06 10:37:17 -08006930 }
6931 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006932 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6933 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006934 }
Zhi Huange830e682018-03-30 10:48:35 -07006935
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006936 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006937 if (transport_name) {
6938 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006939 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006940 }
Zhi Huange830e682018-03-30 10:48:35 -07006941
Steve Antonc7b964c2018-02-01 14:39:45 -08006942 for (const auto& entry : media_types_by_transport_name) {
6943 const std::string& transport_name = entry.first;
6944 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006945 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006946 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006947 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006948 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006949 }
6950 }
6951}
6952// Walk through the ConnectionInfos to gather best connection usage
6953// for IPv4 and IPv6.
6954void PeerConnection::ReportBestConnectionState(
6955 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006956 for (const cricket::TransportChannelStats& channel_stats :
6957 stats.channel_stats) {
6958 for (const cricket::ConnectionInfo& connection_info :
6959 channel_stats.connection_infos) {
6960 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006961 continue;
6962 }
6963
Steve Antonc7b964c2018-02-01 14:39:45 -08006964 const cricket::Candidate& local = connection_info.local_candidate;
6965 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006966
6967 // Increment the counter for IceCandidatePairType.
6968 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6969 (local.type() == RELAY_PORT_TYPE &&
6970 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006971 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6972 GetIceCandidatePairCounter(local, remote),
6973 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006974 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006975 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6976 GetIceCandidatePairCounter(local, remote),
6977 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006978 } else {
6979 RTC_CHECK(0);
6980 }
Steve Anton75737c02017-11-06 10:37:17 -08006981
6982 // Increment the counter for IP type.
6983 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006984 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6985 kBestConnections_IPv4,
6986 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006987 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006988 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6989 kBestConnections_IPv6,
6990 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006991 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006992 RTC_CHECK(!local.address().hostname().empty() &&
6993 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006994 }
6995
6996 return;
6997 }
6998 }
6999}
7000
7001void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007002 const cricket::TransportStats& stats,
7003 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007004 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7005 return;
7006 }
7007
7008 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7009 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7010 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7011 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7012 return;
7013 }
7014
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007015 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7016 for (cricket::MediaType media_type : media_types) {
7017 switch (media_type) {
7018 case cricket::MEDIA_TYPE_AUDIO:
7019 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7020 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7021 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7022 break;
7023 case cricket::MEDIA_TYPE_VIDEO:
7024 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7025 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7026 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7027 break;
7028 case cricket::MEDIA_TYPE_DATA:
7029 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7030 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7031 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7032 break;
7033 default:
7034 RTC_NOTREACHED();
7035 continue;
7036 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007037 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007038 }
7039
7040 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7041 for (cricket::MediaType media_type : media_types) {
7042 switch (media_type) {
7043 case cricket::MEDIA_TYPE_AUDIO:
7044 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7045 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7046 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7047 break;
7048 case cricket::MEDIA_TYPE_VIDEO:
7049 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7050 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7051 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7052 break;
7053 case cricket::MEDIA_TYPE_DATA:
7054 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7055 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7056 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7057 break;
7058 default:
7059 RTC_NOTREACHED();
7060 continue;
7061 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007062 }
Steve Anton75737c02017-11-06 10:37:17 -08007063 }
7064}
7065
7066void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007067 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007068 RTC_DCHECK(call_);
7069 call_->OnSentPacket(sent_packet);
7070}
7071
7072const std::string PeerConnection::GetTransportName(
7073 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007074 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007075 if (channel) {
7076 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007077 }
Steve Anton6fec8802017-12-04 10:37:29 -08007078 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007079 RTC_DCHECK(sctp_mid_);
7080 if (content_name == *sctp_mid_) {
7081 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007082 }
7083 }
7084 // Return an empty string if failed to retrieve the transport name.
7085 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007086}
7087
Steve Anton6fec8802017-12-04 10:37:29 -08007088void PeerConnection::DestroyTransceiverChannel(
7089 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7090 transceiver) {
7091 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007092
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007093 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007094 if (channel) {
7095 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007096 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007097 }
7098}
7099
7100void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007101 if (rtp_data_channel_) {
7102 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007103 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007104 rtp_data_channel_ = nullptr;
7105 }
7106
7107 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7108 // grab a reference to this PeerConnection. If this is called from the
7109 // PeerConnection destructor, the RefCountedObject vtable will have already
7110 // been destroyed (since it is a subclass of PeerConnection) and using
7111 // rtc::Bind will cause "Pure virtual function called" error to appear.
7112
7113 if (sctp_transport_) {
7114 OnDataChannelDestroyed();
7115 network_thread()->Invoke<void>(RTC_FROM_HERE,
7116 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007117 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007118 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007119
7120 if (media_transport_) {
7121 OnDataChannelDestroyed();
7122 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7123 RTC_DCHECK_RUN_ON(network_thread());
7124 TeardownMediaTransportForDataChannels_n();
7125 });
7126 }
Steve Anton6fec8802017-12-04 10:37:29 -08007127}
7128
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007129void PeerConnection::DestroyChannelInterface(
7130 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007131 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007132 switch (channel->media_type()) {
7133 case cricket::MEDIA_TYPE_AUDIO:
7134 channel_manager()->DestroyVoiceChannel(
7135 static_cast<cricket::VoiceChannel*>(channel));
7136 break;
7137 case cricket::MEDIA_TYPE_VIDEO:
7138 channel_manager()->DestroyVideoChannel(
7139 static_cast<cricket::VideoChannel*>(channel));
7140 break;
7141 case cricket::MEDIA_TYPE_DATA:
7142 channel_manager()->DestroyRtpDataChannel(
7143 static_cast<cricket::RtpDataChannel*>(channel));
7144 break;
7145 default:
7146 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7147 break;
7148 }
Zhi Huange830e682018-03-30 10:48:35 -07007149}
Steve Anton6fec8802017-12-04 10:37:29 -08007150
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007151bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007152 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007153 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007154 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007155 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007156 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007157 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007158 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007159 auto base_channel = GetChannel(mid);
7160 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007161 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007162 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007163 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007164 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007165 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007166
Karl Wiberg5966c502019-02-21 23:55:09 +01007167 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007168 // Only pass media transport to call object if media transport is used
7169 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007170 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007171 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007172
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007173 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007174}
7175
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007176void PeerConnection::OnSetStreams() {
7177 RTC_DCHECK_RUN_ON(signaling_thread());
7178 if (IsUnifiedPlan())
7179 UpdateNegotiationNeeded();
7180}
7181
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007182PeerConnectionObserver* PeerConnection::Observer() const {
7183 // In earlier production code, the pointer was not cleared on close,
7184 // which might have led to undefined behavior if the observer was not
7185 // deallocated, or strange crashes if it was.
7186 // We use CHECK in order to catch such behavior if it exists.
7187 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7188 RTC_CHECK(observer_);
7189 return observer_;
7190}
7191
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007192CryptoOptions PeerConnection::GetCryptoOptions() {
7193 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7194 // after it has been removed.
7195 return configuration_.crypto_options.has_value()
7196 ? *configuration_.crypto_options
7197 : factory_->options().crypto_options;
7198}
7199
Harald Alvestrand89061872018-01-02 14:08:34 +01007200void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007201 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007202 if (stats_collector_) {
7203 stats_collector_->ClearCachedStatsReport();
7204 }
7205}
7206
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007207void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007208 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7209 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007210}
7211
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007212void PeerConnection::UpdateNegotiationNeeded() {
7213 RTC_DCHECK_RUN_ON(signaling_thread());
7214 if (!IsUnifiedPlan()) {
7215 Observer()->OnRenegotiationNeeded();
7216 return;
7217 }
7218
7219 // If connection's [[IsClosed]] slot is true, abort these steps.
7220 if (IsClosed())
7221 return;
7222
7223 // If connection's signaling state is not "stable", abort these steps.
7224 if (signaling_state() != kStable)
7225 return;
7226
7227 // NOTE
7228 // The negotiation-needed flag will be updated once the state transitions to
7229 // "stable", as part of the steps for setting an RTCSessionDescription.
7230
7231 // If the result of checking if negotiation is needed is false, clear the
7232 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7233 // to false, and abort these steps.
7234 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7235 if (!is_negotiation_needed) {
7236 is_negotiation_needed_ = false;
7237 return;
7238 }
7239
7240 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7241 // steps.
7242 if (is_negotiation_needed_)
7243 return;
7244
7245 // Set connection's [[NegotiationNeeded]] slot to true.
7246 is_negotiation_needed_ = true;
7247
7248 // Queue a task that runs the following steps:
7249 // If connection's [[IsClosed]] slot is true, abort these steps.
7250 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7251 // Fire an event named negotiationneeded at connection.
7252 Observer()->OnRenegotiationNeeded();
7253}
7254
7255bool PeerConnection::CheckIfNegotiationIsNeeded() {
7256 RTC_DCHECK_RUN_ON(signaling_thread());
7257 // 1. If any implementation-specific negotiation is required, as described at
7258 // the start of this section, return true.
7259
7260 // 2. Let description be connection.[[CurrentLocalDescription]].
7261 const SessionDescriptionInterface* description = current_local_description();
7262 if (!description)
7263 return true;
7264
7265 // 3. If connection has created any RTCDataChannels, and no m= section in
7266 // description has been negotiated yet for data, return true.
7267 if (!sctp_data_channels_.empty()) {
7268 if (!cricket::GetFirstDataContent(description->description()->contents()))
7269 return true;
7270 }
7271
7272 // 4. For each transceiver in connection's set of transceivers, perform the
7273 // following checks:
7274 for (const auto& transceiver : transceivers_) {
7275 const ContentInfo* current_local_msection =
7276 FindTransceiverMSection(transceiver.get(), description);
7277
7278 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7279 transceiver.get(), current_remote_description());
7280
7281 // 4.3 If transceiver is stopped and is associated with an m= section,
7282 // but the associated m= section is not yet rejected in
7283 // connection.[[CurrentLocalDescription]] or
7284 // connection.[[CurrentRemoteDescription]], return true.
7285 if (transceiver->stopped()) {
7286 if (current_local_msection && !current_local_msection->rejected &&
7287 ((current_remote_msection && !current_remote_msection->rejected) ||
7288 !current_remote_msection)) {
7289 return true;
7290 }
7291 continue;
7292 }
7293
7294 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7295 // section in description, return true.
7296 if (!current_local_msection)
7297 return true;
7298
7299 const MediaContentDescription* current_local_media_description =
7300 current_local_msection->media_description();
7301 // 4.2 If transceiver isn't stopped and is associated with an m= section
7302 // in description then perform the following checks:
7303
7304 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7305 // associated m= section in description either doesn't contain a single
7306 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7307 // m= section, or the MSID values themselves, differ from what is in
7308 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7309 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7310 if (current_local_media_description->streams().size() == 0)
7311 return true;
7312
7313 std::vector<std::string> msection_msids;
7314 for (const auto& stream : current_local_media_description->streams()) {
7315 for (const std::string& msid : stream.stream_ids())
7316 msection_msids.push_back(msid);
7317 }
7318
7319 std::vector<std::string> transceiver_msids =
7320 transceiver->sender()->stream_ids();
7321 if (msection_msids.size() != transceiver_msids.size())
7322 return true;
7323
7324 absl::c_sort(transceiver_msids);
7325 absl::c_sort(msection_msids);
7326 if (transceiver_msids != msection_msids)
7327 return true;
7328 }
7329
7330 // 4.2.2 If description is of type "offer", and the direction of the
7331 // associated m= section in neither connection.[[CurrentLocalDescription]]
7332 // nor connection.[[CurrentRemoteDescription]] matches
7333 // transceiver.[[Direction]], return true.
7334 if (description->GetType() == SdpType::kOffer) {
7335 if (!current_remote_description())
7336 return true;
7337
7338 if (!current_remote_msection)
7339 return true;
7340
7341 RtpTransceiverDirection current_local_direction =
7342 current_local_media_description->direction();
7343 RtpTransceiverDirection current_remote_direction =
7344 current_remote_msection->media_description()->direction();
7345 if (transceiver->direction() != current_local_direction &&
7346 transceiver->direction() !=
7347 RtpTransceiverDirectionReversed(current_remote_direction)) {
7348 return true;
7349 }
7350 }
7351
7352 // 4.2.3 If description is of type "answer", and the direction of the
7353 // associated m= section in the description does not match
7354 // transceiver.[[Direction]] intersected with the offered direction (as
7355 // described in [JSEP] (section 5.3.1.)), return true.
7356 if (description->GetType() == SdpType::kAnswer) {
7357 if (!remote_description())
7358 return true;
7359
7360 const ContentInfo* offered_remote_msection =
7361 FindTransceiverMSection(transceiver.get(), remote_description());
7362
7363 RtpTransceiverDirection offered_direction =
7364 offered_remote_msection
7365 ? offered_remote_msection->media_description()->direction()
7366 : RtpTransceiverDirection::kInactive;
7367
7368 if (current_local_media_description->direction() !=
7369 (RtpTransceiverDirectionIntersection(
7370 transceiver->direction(),
7371 RtpTransceiverDirectionReversed(offered_direction)))) {
7372 return true;
7373 }
7374 }
7375 }
7376
7377 // If all the preceding checks were performed and true was not returned,
7378 // nothing remains to be negotiated; return false.
7379 return false;
7380}
7381
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007382} // namespace webrtc