blob: c46dc80cea1d267d1ac2292a3f40c96d3b20a6b5 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020028#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070029#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "logging/rtc_event_log/ice_logger.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070062#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080073using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080074using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080075using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080078using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070079using cricket::RELAY_PORT_TYPE;
80using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080081
Steve Antonba818672017-11-06 10:21:57 -080082namespace webrtc {
83
Steve Anton75737c02017-11-06 10:37:17 -080084// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080088const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080096const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
Steve Anton75737c02017-11-06 10:37:17 -0800108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800110// UMA metric names.
111const char kSimulcastVersionApplyLocalDescription[] =
112 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
113const char kSimulcastVersionApplyRemoteDescription[] =
114 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
115const char kSimulcastNumberOfEncodings[] =
116 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
117const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
118
Seth Hampson845e8782018-03-02 11:34:10 -0800119static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800120static const char kDefaultAudioSenderId[] = "defaulta0";
121static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700122
zhihuang8f65cdf2016-05-06 18:40:30 -0700123// The length of RTCP CNAMEs.
124static const int kRtcpCnameLength = 16;
125
Steve Antonad182762018-09-05 20:22:40 +0000126enum {
127 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
128 MSG_SET_SESSIONDESCRIPTION_FAILED,
129 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
130 MSG_GETSTATS,
131 MSG_FREE_DATACHANNELS,
132 MSG_REPORT_USAGE_PATTERN,
133};
134
Harald Alvestrand19793842018-06-25 12:03:50 +0200135static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
136
Steve Antonad182762018-09-05 20:22:40 +0000137struct SetSessionDescriptionMsg : public rtc::MessageData {
138 explicit SetSessionDescriptionMsg(
139 webrtc::SetSessionDescriptionObserver* observer)
140 : observer(observer) {}
141
142 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
143 RTCError error;
144};
145
146struct CreateSessionDescriptionMsg : public rtc::MessageData {
147 explicit CreateSessionDescriptionMsg(
148 webrtc::CreateSessionDescriptionObserver* observer)
149 : observer(observer) {}
150
151 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
152 RTCError error;
153};
154
155struct GetStatsMsg : public rtc::MessageData {
156 GetStatsMsg(webrtc::StatsObserver* observer,
157 webrtc::MediaStreamTrackInterface* track)
158 : observer(observer), track(track) {}
159 rtc::scoped_refptr<webrtc::StatsObserver> observer;
160 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
161};
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163// Check if we can send |new_stream| on a PeerConnection.
164bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
165 webrtc::MediaStreamInterface* new_stream) {
166 if (!new_stream || !current_streams) {
167 return false;
168 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700169 if (current_streams->find(new_stream->id()) != nullptr) {
170 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100171 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700172 return false;
173 }
174 return true;
175}
176
deadbeef5e97fb52015-10-15 12:49:08 -0700177// If the direction is "recvonly" or "inactive", treat the description
178// as containing no streams.
179// See: https://code.google.com/p/webrtc/issues/detail?id=5054
180std::vector<cricket::StreamParams> GetActiveStreams(
181 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800182 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700183 ? desc->streams()
184 : std::vector<cricket::StreamParams>();
185}
186
deadbeefab9b2d12015-10-14 11:33:11 -0700187bool IsValidOfferToReceiveMedia(int value) {
188 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
189 return (value >= Options::kUndefined) &&
190 (value <= Options::kMaxOfferToReceiveMedia);
191}
192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800194void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700195 const std::vector<rtc::scoped_refptr<
196 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700197 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200198 cricket::MediaDescriptionOptions* video_media_description_options,
199 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700200 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700201 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
202 if (audio_media_description_options) {
203 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700204 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700205 }
206 } else {
207 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
208 if (video_media_description_options) {
209 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800210 sender->id(), sender->internal()->stream_ids(), {},
211 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700212 }
213 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700214 }
zhihuang1c378ed2017-08-17 14:10:50 -0700215}
olka3c747662017-08-17 06:50:32 -0700216
zhihuang1c378ed2017-08-17 14:10:50 -0700217// Add options to |session_options| from |rtp_data_channels|.
218void AddRtpDataChannelOptions(
219 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
220 rtp_data_channels,
221 cricket::MediaDescriptionOptions* data_media_description_options) {
222 if (!data_media_description_options) {
223 return;
224 }
deadbeefab9b2d12015-10-14 11:33:11 -0700225 // Check for data channels.
226 for (const auto& kv : rtp_data_channels) {
227 const DataChannel* channel = kv.second;
228 if (channel->state() == DataChannel::kConnecting ||
229 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700230 // Legacy RTP data channels are signaled with the track/stream ID set to
231 // the data channel's label.
232 data_media_description_options->AddRtpDataChannel(channel->label(),
233 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700234 }
235 }
236}
237
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700238uint32_t ConvertIceTransportTypeToCandidateFilter(
239 PeerConnectionInterface::IceTransportsType type) {
240 switch (type) {
241 case PeerConnectionInterface::kNone:
242 return cricket::CF_NONE;
243 case PeerConnectionInterface::kRelay:
244 return cricket::CF_RELAY;
245 case PeerConnectionInterface::kNoHost:
246 return (cricket::CF_ALL & ~cricket::CF_HOST);
247 case PeerConnectionInterface::kAll:
248 return cricket::CF_ALL;
249 default:
nissec80e7412017-01-11 05:56:46 -0800250 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700251 }
252 return cricket::CF_NONE;
253}
254
deadbeef293e9262017-01-11 12:28:30 -0800255// Helper to set an error and return from a method.
256bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
257 if (error) {
258 error->set_type(type);
259 }
260 return type == webrtc::RTCErrorType::NONE;
261}
262
Steve Anton038834f2017-07-14 15:59:59 -0700263bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700264 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700265 if (error_out) {
266 *error_out = std::move(error);
267 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700269}
270
Steve Antonba818672017-11-06 10:21:57 -0800271std::string GetSignalingStateString(
272 PeerConnectionInterface::SignalingState state) {
273 switch (state) {
274 case PeerConnectionInterface::kStable:
275 return "kStable";
276 case PeerConnectionInterface::kHaveLocalOffer:
277 return "kHaveLocalOffer";
278 case PeerConnectionInterface::kHaveLocalPrAnswer:
279 return "kHavePrAnswer";
280 case PeerConnectionInterface::kHaveRemoteOffer:
281 return "kHaveRemoteOffer";
282 case PeerConnectionInterface::kHaveRemotePrAnswer:
283 return "kHaveRemotePrAnswer";
284 case PeerConnectionInterface::kClosed:
285 return "kClosed";
286 }
287 RTC_NOTREACHED();
288 return "";
289}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290
Steve Anton75737c02017-11-06 10:37:17 -0800291IceCandidatePairType GetIceCandidatePairCounter(
292 const cricket::Candidate& local,
293 const cricket::Candidate& remote) {
294 const auto& l = local.type();
295 const auto& r = remote.type();
296 const auto& host = LOCAL_PORT_TYPE;
297 const auto& srflx = STUN_PORT_TYPE;
298 const auto& relay = RELAY_PORT_TYPE;
299 const auto& prflx = PRFLX_PORT_TYPE;
300 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800301 bool local_hostname =
302 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
303 bool remote_hostname = !remote.address().hostname().empty() &&
304 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800305 bool local_private = IPIsPrivate(local.address().ipaddr());
306 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800307 if (local_hostname) {
308 if (remote_hostname) {
309 return kIceCandidatePairHostNameHostName;
310 } else if (remote_private) {
311 return kIceCandidatePairHostNameHostPrivate;
312 } else {
313 return kIceCandidatePairHostNameHostPublic;
314 }
315 } else if (local_private) {
316 if (remote_hostname) {
317 return kIceCandidatePairHostPrivateHostName;
318 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return kIceCandidatePairHostPrivateHostPrivate;
320 } else {
321 return kIceCandidatePairHostPrivateHostPublic;
322 }
323 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800324 if (remote_hostname) {
325 return kIceCandidatePairHostPublicHostName;
326 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800327 return kIceCandidatePairHostPublicHostPrivate;
328 } else {
329 return kIceCandidatePairHostPublicHostPublic;
330 }
331 }
332 }
333 if (l == host && r == srflx)
334 return kIceCandidatePairHostSrflx;
335 if (l == host && r == relay)
336 return kIceCandidatePairHostRelay;
337 if (l == host && r == prflx)
338 return kIceCandidatePairHostPrflx;
339 if (l == srflx && r == host)
340 return kIceCandidatePairSrflxHost;
341 if (l == srflx && r == srflx)
342 return kIceCandidatePairSrflxSrflx;
343 if (l == srflx && r == relay)
344 return kIceCandidatePairSrflxRelay;
345 if (l == srflx && r == prflx)
346 return kIceCandidatePairSrflxPrflx;
347 if (l == relay && r == host)
348 return kIceCandidatePairRelayHost;
349 if (l == relay && r == srflx)
350 return kIceCandidatePairRelaySrflx;
351 if (l == relay && r == relay)
352 return kIceCandidatePairRelayRelay;
353 if (l == relay && r == prflx)
354 return kIceCandidatePairRelayPrflx;
355 if (l == prflx && r == host)
356 return kIceCandidatePairPrflxHost;
357 if (l == prflx && r == srflx)
358 return kIceCandidatePairPrflxSrflx;
359 if (l == prflx && r == relay)
360 return kIceCandidatePairPrflxRelay;
361 return kIceCandidatePairMax;
362}
363
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800364// Logic to decide if an m= section can be recycled. This means that the new
365// m= section is not rejected, but the old local or remote m= section is
366// rejected. |old_content_one| and |old_content_two| refer to the m= section
367// of the old remote and old local descriptions in no particular order.
368// We need to check both the old local and remote because either
369// could be the most current from the latest negotation.
370bool IsMediaSectionBeingRecycled(SdpType type,
371 const ContentInfo& content,
372 const ContentInfo* old_content_one,
373 const ContentInfo* old_content_two) {
374 return type == SdpType::kOffer && !content.rejected &&
375 ((old_content_one && old_content_one->rejected) ||
376 (old_content_two && old_content_two->rejected));
377}
378
Steve Anton75737c02017-11-06 10:37:17 -0800379// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380// |current_desc|. The number of m= sections in |new_desc| should be no
381// less than |current_desc|. In the case of checking an answer's
382// |new_desc|, the |current_desc| is the last offer that was set as the
383// local or remote. In the case of checking an offer's |new_desc| we
384// check against the local and remote descriptions stored from the last
385// negotiation, because either of these could be the most up to date for
386// possible rejected m sections. These are the |current_desc| and
387// |secondary_current_desc|.
388bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
389 const SessionDescription* secondary_current_desc,
390 const SessionDescription& new_desc,
391 const SdpType type) {
392 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800393 return false;
394 }
395
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800396 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
397 const cricket::ContentInfo* secondary_content_info = nullptr;
398 if (secondary_current_desc &&
399 i < secondary_current_desc->contents().size()) {
400 secondary_content_info = &secondary_current_desc->contents()[i];
401 }
402 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
403 &current_desc.contents()[i],
404 secondary_content_info)) {
405 // For new offer descriptions, if the media section can be recycled, it's
406 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800407 continue;
408 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800409 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800410 return false;
411 }
412 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 new_desc.contents()[i].media_description();
414 const MediaContentDescription* current_desc_mdesc =
415 current_desc.contents()[i].media_description();
416 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800417 return false;
418 }
419 }
420 return true;
421}
422
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800423bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
424 const SessionDescription& desc2) {
425 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800426}
427
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700428void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
429 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200430 // Array of structs needed to map {KeyExchangeProtocolType,
431 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
432 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
433 static constexpr struct {
434 KeyExchangeProtocolType protocol_type;
435 cricket::MediaType media_type;
436 KeyExchangeProtocolMedia protocol_media;
437 } kEnumCounterKeyProtocolMediaMap[] = {
438 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
439 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
440 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
441 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
443 kEnumCounterKeyProtocolMediaTypeDtlsData},
444 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
445 kEnumCounterKeyProtocolMediaTypeSdesAudio},
446 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
447 kEnumCounterKeyProtocolMediaTypeSdesVideo},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
449 kEnumCounterKeyProtocolMediaTypeSdesData},
450 };
451
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700452 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
453 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100454
Mirko Bonadeiab499822018-09-11 10:43:20 +0200455 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
456 if (i.protocol_type == protocol_type && i.media_type == media_type) {
457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
458 i.protocol_media,
459 kEnumCounterKeyProtocolMediaTypeMax);
460 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100461 }
462}
463
Harald Alvestrand76829d72018-07-18 23:24:36 +0200464void NoteAddIceCandidateResult(int result) {
465 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
466 kAddIceCandidateMax);
467}
468
Steve Anton75737c02017-11-06 10:37:17 -0800469// Checks that each non-rejected content has SDES crypto keys or a DTLS
470// fingerprint, unless it's in a BUNDLE group, in which case only the
471// BUNDLE-tag section (first media section/description in the BUNDLE group)
472// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
473// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
474// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700475RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100482 // Note what media is used with each crypto protocol, for all sections.
483 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
484 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700485 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800486 const std::string& mid = content_info.name;
487 if (bundle && bundle->HasContentName(mid) &&
488 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800489 // This isn't the first media section in the BUNDLE group, so it's not
490 // required to have crypto attributes, since only the crypto attributes
491 // from the first section actually get used.
492 continue;
493 }
494
495 // If the content isn't rejected or bundled into another m= section, crypto
496 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800498 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800499 if (!media || !tinfo) {
500 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800501 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 if (dtls_enabled) {
504 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_WARNING)
506 << "Session description must have DTLS fingerprint if "
507 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800508 return RTCError(RTCErrorType::INVALID_PARAMETER,
509 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800510 }
511 } else {
512 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100513 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800514 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800515 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800516 }
517 }
518 }
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800520}
521
522// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
523// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
524// media section/description in the BUNDLE group) needs a ufrag and pwd.
525bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
526 const cricket::ContentGroup* bundle =
527 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800528 for (const cricket::ContentInfo& content_info : desc->contents()) {
529 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800530 continue;
531 }
Steve Anton8a006912017-12-04 15:25:56 -0800532 const std::string& mid = content_info.name;
533 if (bundle && bundle->HasContentName(mid) &&
534 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800535 // This isn't the first media section in the BUNDLE group, so it's not
536 // required to have ufrag/password, since only the ufrag/password from
537 // the first section actually get used.
538 continue;
539 }
540
541 // If the content isn't rejected or bundled into another m= section,
542 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800543 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800544 if (!tinfo) {
545 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800547 return false;
548 }
549 if (tinfo->description.ice_ufrag.empty() ||
550 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100551 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800552 return false;
553 }
554 }
555 return true;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
559bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
560 const SessionDescriptionInterface* new_desc,
561 const std::string& content_name) {
562 if (!old_desc) {
563 return false;
564 }
565 const SessionDescription* new_sd = new_desc->description();
566 const SessionDescription* old_sd = old_desc->description();
567 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
568 if (!cinfo || cinfo->rejected) {
569 return false;
570 }
571 // If the content isn't rejected, check if ufrag and password has changed.
572 const cricket::TransportDescription* new_transport_desc =
573 new_sd->GetTransportDescriptionByName(content_name);
574 const cricket::TransportDescription* old_transport_desc =
575 old_sd->GetTransportDescriptionByName(content_name);
576 if (!new_transport_desc || !old_transport_desc) {
577 // No transport description exists. This is not an ICE restart.
578 return false;
579 }
580 if (cricket::IceCredentialsChanged(
581 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
582 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-16 17:08:42 -0800590// Generates a string error message for SetLocalDescription/SetRemoteDescription
591// from an RTCError.
592std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
593 SdpType type,
594 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200595 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800596 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
597 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200598 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800599}
600
Seth Hampson5b4f0752018-04-02 16:31:36 -0700601std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
602 std::string output = "streams=[";
603 const char* separator = "";
604 for (const auto& stream_id : stream_ids) {
605 output.append(separator).append(stream_id);
606 separator = ", ";
607 }
608 output.append("]");
609 return output;
610}
611
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 }
618 return rtc_configuration_parameter;
619}
620
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800621cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
622 switch (type) {
623 case DataMessageType::kText:
624 return cricket::DMT_TEXT;
625 case DataMessageType::kBinary:
626 return cricket::DMT_BINARY;
627 case DataMessageType::kControl:
628 return cricket::DMT_CONTROL;
629 default:
630 return cricket::DMT_NONE;
631 }
632 return cricket::DMT_NONE;
633}
634
635DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
636 switch (type) {
637 case cricket::DMT_TEXT:
638 return DataMessageType::kText;
639 case cricket::DMT_BINARY:
640 return DataMessageType::kBinary;
641 case cricket::DMT_CONTROL:
642 return DataMessageType::kControl;
643 case cricket::DMT_NONE:
644 default:
645 RTC_NOTREACHED();
646 }
647 return DataMessageType::kControl;
648}
649
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800650void ReportSimulcastApiVersion(const char* name,
651 const SessionDescription& session) {
652 bool has_legacy = false;
653 bool has_spec_compliant = false;
654 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200655 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800656 continue;
657 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200658 has_spec_compliant |= content.media_description()->HasSimulcast();
659 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800660 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
661 }
662 }
663
664 if (has_legacy) {
665 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
666 kSimulcastApiVersionMax);
667 }
668 if (has_spec_compliant) {
669 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
670 kSimulcastApiVersionMax);
671 }
672 if (!has_legacy && !has_spec_compliant) {
673 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
674 kSimulcastApiVersionMax);
675 }
676}
677
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200678const ContentInfo* FindTransceiverMSection(
679 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
680 const SessionDescriptionInterface* session_description) {
681 return transceiver->mid()
682 ? session_description->description()->GetContentByName(
683 *transceiver->mid())
684 : nullptr;
685}
686
Steve Anton75737c02017-11-06 10:37:17 -0800687} // namespace
688
Henrik Boström31638672017-11-23 17:48:32 +0100689// Upon completion, posts a task to execute the callback of the
690// SetSessionDescriptionObserver asynchronously on the same thread. At this
691// point, the state of the peer connection might no longer reflect the effects
692// of the SetRemoteDescription operation, as the peer connection could have been
693// modified during the post.
694// TODO(hbos): Remove this class once we remove the version of
695// PeerConnectionInterface::SetRemoteDescription() that takes a
696// SetSessionDescriptionObserver as an argument.
697class PeerConnection::SetRemoteDescriptionObserverAdapter
698 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
699 public:
700 SetRemoteDescriptionObserverAdapter(
701 rtc::scoped_refptr<PeerConnection> pc,
702 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
703 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
704
705 // SetRemoteDescriptionObserverInterface implementation.
706 void OnSetRemoteDescriptionComplete(RTCError error) override {
707 if (error.ok())
708 pc_->PostSetSessionDescriptionSuccess(wrapper_);
709 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100710 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100711 }
712
713 private:
714 rtc::scoped_refptr<PeerConnection> pc_;
715 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
716};
717
deadbeef293e9262017-01-11 12:28:30 -0800718bool PeerConnectionInterface::RTCConfiguration::operator==(
719 const PeerConnectionInterface::RTCConfiguration& o) const {
720 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700721 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800722 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000723 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700724 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800725 BundlePolicy bundle_policy;
726 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700727 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
728 int ice_candidate_pool_size;
729 bool disable_ipv6;
730 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700731 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100732 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200734 absl::optional<int> screencast_min_bitrate;
735 absl::optional<bool> combined_audio_video_bwe;
736 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800737 TcpCandidatePolicy tcp_candidate_policy;
738 CandidateNetworkPolicy candidate_network_policy;
739 int audio_jitter_buffer_max_packets;
740 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100741 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100742 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800743 int ice_connection_receiving_timeout;
744 int ice_backup_candidate_pair_ping_interval;
745 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800746 bool prioritize_most_likely_ice_candidate_pairs;
747 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800748 bool prune_turn_ports;
749 bool presume_writable_when_fully_relayed;
750 bool enable_ice_renomination;
751 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700752 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200753 absl::optional<int> ice_check_interval_strong_connectivity;
754 absl::optional<int> ice_check_interval_weak_connectivity;
755 absl::optional<int> ice_check_min_interval;
756 absl::optional<int> ice_unwritable_timeout;
757 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800758 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200759 absl::optional<int> stun_candidate_keepalive_interval;
760 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200761 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800762 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700764 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700765 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700766 bool use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700767 bool use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700768 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100769 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800770 };
771 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
772 "Did you add something to RTCConfiguration and forget to "
773 "update operator==?");
774 return type == o.type && servers == o.servers &&
775 bundle_policy == o.bundle_policy &&
776 rtcp_mux_policy == o.rtcp_mux_policy &&
777 tcp_candidate_policy == o.tcp_candidate_policy &&
778 candidate_network_policy == o.candidate_network_policy &&
779 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
780 audio_jitter_buffer_fast_accelerate ==
781 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100782 audio_jitter_buffer_min_delay_ms ==
783 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100784 audio_jitter_buffer_enable_rtx_handling ==
785 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800786 ice_connection_receiving_timeout ==
787 o.ice_connection_receiving_timeout &&
788 ice_backup_candidate_pair_ping_interval ==
789 o.ice_backup_candidate_pair_ping_interval &&
790 continual_gathering_policy == o.continual_gathering_policy &&
791 certificates == o.certificates &&
792 prioritize_most_likely_ice_candidate_pairs ==
793 o.prioritize_most_likely_ice_candidate_pairs &&
794 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800795 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700796 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100797 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800798 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800799 screencast_min_bitrate == o.screencast_min_bitrate &&
800 combined_audio_video_bwe == o.combined_audio_video_bwe &&
801 enable_dtls_srtp == o.enable_dtls_srtp &&
802 ice_candidate_pool_size == o.ice_candidate_pool_size &&
803 prune_turn_ports == o.prune_turn_ports &&
804 presume_writable_when_fully_relayed ==
805 o.presume_writable_when_fully_relayed &&
806 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800807 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700808 surface_ice_candidates_on_ice_transport_type_changed ==
809 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800810 ice_check_interval_strong_connectivity ==
811 o.ice_check_interval_strong_connectivity &&
812 ice_check_interval_weak_connectivity ==
813 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700814 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700815 ice_unwritable_timeout == o.ice_unwritable_timeout &&
816 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800817 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800818 stun_candidate_keepalive_interval ==
819 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200820 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800821 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800822 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700823 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700824 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700825 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700826 use_media_transport_for_data_channels ==
827 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700828 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100829 crypto_options == o.crypto_options &&
830 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800831}
832
833bool PeerConnectionInterface::RTCConfiguration::operator!=(
834 const PeerConnectionInterface::RTCConfiguration& o) const {
835 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800836}
837
zhihuang8f65cdf2016-05-06 18:40:30 -0700838// Generate a RTCP CNAME when a PeerConnection is created.
839std::string GenerateRtcpCname() {
840 std::string cname;
841 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100842 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800843 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700844 }
845 return cname;
846}
847
zhihuang1c378ed2017-08-17 14:10:50 -0700848bool ValidateOfferAnswerOptions(
849 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
850 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
851 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700852}
853
zhihuang1c378ed2017-08-17 14:10:50 -0700854// From |rtc_options|, fill parts of |session_options| shared by all generated
855// m= sections (in other words, nothing that involves a map/array).
856void ExtractSharedMediaSessionOptions(
857 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
858 cricket::MediaSessionOptions* session_options) {
859 session_options->vad_enabled = rtc_options.voice_activity_detection;
860 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200861 session_options->raw_packetization_for_video =
862 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700863}
zhihuanga77e6bb2017-08-14 18:17:48 -0700864
zhihuang38ede132017-06-15 12:52:32 -0700865PeerConnection::PeerConnection(PeerConnectionFactory* factory,
866 std::unique_ptr<RtcEventLog> event_log,
867 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700869 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100870 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700871 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700872 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700873 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100874 call_(std::move(call)),
875 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876
877PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100878 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800879 RTC_DCHECK_RUN_ON(signaling_thread());
880
Steve Anton8af21862017-12-15 11:20:13 -0800881 // Need to stop transceivers before destroying the stats collector because
882 // AudioRtpSender has a reference to the StatsCollector it will update when
883 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100884 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800885 transceiver->Stop();
886 }
Steve Anton4171afb2017-11-20 10:20:22 -0800887
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700888 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800889 if (stats_collector_) {
890 stats_collector_->WaitForPendingRequest();
891 stats_collector_ = nullptr;
892 }
Steve Anton75737c02017-11-06 10:37:17 -0800893
Steve Anton8af21862017-12-15 11:20:13 -0800894 // Don't destroy BaseChannels until after stats has been cleaned up so that
895 // the last stats request can still read from the channels.
896 DestroyAllChannels();
897
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800899
900 webrtc_session_desc_factory_.reset();
901 sctp_invoker_.reset();
902 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800903 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800904 transport_controller_.reset();
905
deadbeef91dd5672016-05-18 16:55:30 -0700906 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100907 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
908 RTC_DCHECK_RUN_ON(network_thread());
909 port_allocator_.reset();
910 });
eladalon248fd4f2017-09-06 05:18:15 -0700911 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700912 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100913 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700914 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800915 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700916 event_log_.reset();
917 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918}
919
Steve Anton8af21862017-12-15 11:20:13 -0800920void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800921 // Destroy video channels first since they may have a pointer to a voice
922 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100923 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800924 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800925 DestroyTransceiverChannel(transceiver);
926 }
927 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100928 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800929 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800930 DestroyTransceiverChannel(transceiver);
931 }
932 }
933 DestroyDataChannel();
934}
935
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000937 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700938 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100939 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100940 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100941 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700942
943 RTCError config_error = ValidateConfiguration(configuration);
944 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100945 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700946 return false;
947 }
948
Benjamin Wrightcab58882018-05-02 15:12:47 -0700949 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100950 RTC_LOG(LS_ERROR)
951 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100952 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800953 return false;
954 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200955
Benjamin Wrightcab58882018-05-02 15:12:47 -0700956 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800957 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100958 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100959 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800960 return false;
961 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700962
Benjamin Wrightcab58882018-05-02 15:12:47 -0700963 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700964 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700965 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700966 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800967
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200968 cricket::ServerAddresses stun_servers;
969 std::vector<cricket::RelayServerConfig> turn_servers;
970
971 RTCErrorType parse_error =
972 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
973 if (parse_error != RTCErrorType::NONE) {
974 return false;
975 }
976
deadbeef91dd5672016-05-18 16:55:30 -0700977 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700978 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100979 const auto pa_result =
980 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200981 RTC_FROM_HERE,
982 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100983 stun_servers, turn_servers, configuration));
984
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200985 // If initialization was successful, note if STUN or TURN servers
986 // were supplied.
987 if (!stun_servers.empty()) {
988 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
989 }
990 if (!turn_servers.empty()) {
991 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
992 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700994 // Send information about IPv4/IPv6 status.
995 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +0100996 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700997 address_family = kPeerConnection_IPv6;
998 } else {
999 address_family = kPeerConnection_IPv4;
1000 }
1001 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1002 kPeerConnectionAddressFamilyCounter_Max);
1003
Zhi Huange830e682018-03-30 10:48:35 -07001004 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1005
Steve Anton75737c02017-11-06 10:37:17 -08001006 // RFC 3264: The numeric value of the session id and version in the
1007 // o line MUST be representable with a "64 bit signed integer".
1008 // Due to this constraint session id |session_id_| is max limited to
1009 // LLONG_MAX.
1010 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001011 JsepTransportController::Config config;
1012 config.redetermine_role_on_ice_restart =
1013 configuration.redetermine_role_on_ice_restart;
1014 config.ssl_max_version = factory_->options().ssl_max_version;
1015 config.disable_encryption = options.disable_encryption;
1016 config.bundle_policy = configuration.bundle_policy;
1017 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001018 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1019 // stub.
1020 config.crypto_options = configuration.crypto_options.has_value()
1021 ? *configuration.crypto_options
1022 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001023 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001024 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001025#if defined(ENABLE_EXTERNAL_AUTH)
1026 config.enable_external_auth = true;
1027#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001028 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001029
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001030 if (configuration.use_datagram_transport ||
1031 configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001032 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001033 if (!factory_->media_transport_factory()) {
1034 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001035 << "PeerConnecton is initialized with use_media_transport = true or "
1036 << "use_media_transport_for_data_channels = true "
1037 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001038 return false;
1039 }
1040
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001041 if (configuration.use_media_transport ||
1042 configuration.use_media_transport_for_data_channels) {
1043 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1044 // RTP media transport is introduced. But until then, we require SDES to
1045 // be enabled.
1046 if (configuration.enable_dtls_srtp.has_value() &&
1047 configuration.enable_dtls_srtp.value()) {
1048 RTC_LOG(LS_WARNING)
1049 << "When media transport is used, SDES must be enabled. Set "
1050 "configuration.enable_dtls_srtp to false. use_media_transport="
1051 << configuration.use_media_transport
1052 << ", use_media_transport_for_data_channels="
1053 << configuration.use_media_transport_for_data_channels;
1054 return false;
1055 }
1056 }
1057
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001058 config.use_media_transport_for_media = configuration.use_media_transport;
1059 config.use_media_transport_for_data_channels =
1060 configuration.use_media_transport_for_data_channels;
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07001061 config.use_datagram_transport = configuration.use_datagram_transport;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001062 config.media_transport_factory = factory_->media_transport_factory();
1063 }
1064
Zhi Huange830e682018-03-30 10:48:35 -07001065 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001066 signaling_thread(), network_thread(), port_allocator_.get(),
1067 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001068 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001069 this, &PeerConnection::OnTransportControllerConnectionState);
1070 transport_controller_->SignalStandardizedIceConnectionState.connect(
1071 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001072 transport_controller_->SignalConnectionState.connect(
1073 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001074 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001075 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001076 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001077 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001078 transport_controller_->SignalIceCandidateError.connect(
1079 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001080 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001081 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1082 transport_controller_->SignalDtlsHandshakeError.connect(
1083 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1084
1085 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001086
deadbeefab9b2d12015-10-14 11:33:11 -07001087 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001088 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089
Steve Antonba818672017-11-06 10:21:57 -08001090 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001091 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001092
Steve Anton75737c02017-11-06 10:37:17 -08001093 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1094 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1095 if (!configuration.certificates.empty()) {
1096 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1097 // just picking the first one. The decision should be made based on the DTLS
1098 // handshake. The DTLS negotiations need to know about all certificates.
1099 certificate = configuration.certificates[0];
1100 }
1101
Steve Antond25da372017-11-06 14:50:29 -08001102 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001103
1104 if (options.disable_encryption) {
1105 dtls_enabled_ = false;
1106 } else {
1107 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001108 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001109 // |configuration| can override the default |dtls_enabled_| value.
1110 if (configuration.enable_dtls_srtp) {
1111 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1112 }
1113 }
1114
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001115 if (configuration.use_media_transport_for_data_channels) {
1116 if (configuration.enable_rtp_data_channel) {
1117 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1118 "use_media_transport_for_data_channels are "
1119 "incompatible and cannot both be set to true";
1120 return false;
1121 }
1122 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1123 } else if (configuration.enable_rtp_data_channel) {
1124 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1125 // set. It takes precendence over the disable_sctp_data_channels
1126 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001127 data_channel_type_ = cricket::DCT_RTP;
1128 } else {
1129 // DTLS has to be enabled to use SCTP.
1130 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1131 data_channel_type_ = cricket::DCT_SCTP;
1132 }
1133 }
1134
1135 video_options_.screencast_min_bitrate_kbps =
1136 configuration.screencast_min_bitrate;
1137 audio_options_.combined_audio_video_bwe =
1138 configuration.combined_audio_video_bwe;
1139
1140 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001141 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001142
1143 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001144 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001145
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001146 audio_options_.audio_jitter_buffer_min_delay_ms =
1147 configuration.audio_jitter_buffer_min_delay_ms;
1148
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001149 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1150 configuration.audio_jitter_buffer_enable_rtx_handling;
1151
Steve Anton75737c02017-11-06 10:37:17 -08001152 // Whether the certificate generator/certificate is null or not determines
1153 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1154 // the right instructions by clearing the variables if needed.
1155 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001156 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001157 certificate = nullptr;
1158 } else if (certificate) {
1159 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001160 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001161 }
1162
1163 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1164 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001165 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001166 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1167 this, &PeerConnection::OnCertificateReady);
1168
1169 if (options.disable_encryption) {
1170 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1171 }
1172
1173 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001174 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001175 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001176
Steve Anton4171afb2017-11-20 10:20:22 -08001177 // Add default audio/video transceivers for Plan B SDP.
1178 if (!IsUnifiedPlan()) {
1179 transceivers_.push_back(
1180 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1181 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1182 transceivers_.push_back(
1183 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1184 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1185 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001186 int delay_ms =
1187 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001188 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1189 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001190
1191 if (dependencies.video_bitrate_allocator_factory) {
1192 video_bitrate_allocator_factory_ =
1193 std::move(dependencies.video_bitrate_allocator_factory);
1194 } else {
1195 video_bitrate_allocator_factory_ =
1196 CreateBuiltinVideoBitrateAllocatorFactory();
1197 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001198 return true;
1199}
1200
Steve Anton038834f2017-07-14 15:59:59 -07001201RTCError PeerConnection::ValidateConfiguration(
1202 const RTCConfiguration& config) const {
1203 if (config.ice_regather_interval_range &&
1204 config.continual_gathering_policy == GATHER_ONCE) {
1205 return RTCError(RTCErrorType::INVALID_PARAMETER,
1206 "ice_regather_interval_range specified but continual "
1207 "gathering policy is GATHER_ONCE");
1208 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001209 auto result =
1210 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1211 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001212}
1213
Yves Gerey665174f2018-06-19 15:03:05 +02001214rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001215 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001216 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1217 "Plan SdpSemantics. Please use GetSenders "
1218 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001219 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220}
1221
Yves Gerey665174f2018-06-19 15:03:05 +02001222rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001223 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001224 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1225 "Plan SdpSemantics. Please use GetReceivers "
1226 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001227 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228}
1229
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001230bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001231 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001232 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1233 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001234 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 if (IsClosed()) {
1236 return false;
1237 }
deadbeefab9b2d12015-10-14 11:33:11 -07001238 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 return false;
1240 }
deadbeefab9b2d12015-10-14 11:33:11 -07001241
1242 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001243 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1244 observer->SignalAudioTrackAdded.connect(this,
1245 &PeerConnection::OnAudioTrackAdded);
1246 observer->SignalAudioTrackRemoved.connect(
1247 this, &PeerConnection::OnAudioTrackRemoved);
1248 observer->SignalVideoTrackAdded.connect(this,
1249 &PeerConnection::OnVideoTrackAdded);
1250 observer->SignalVideoTrackRemoved.connect(
1251 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001252 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001253
deadbeefab9b2d12015-10-14 11:33:11 -07001254 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001255 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001256 }
1257 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001258 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001259 }
1260
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001261 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001262 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 return true;
1264}
1265
1266void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001267 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001268 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1269 "Plan SdpSemantics. Please use RemoveTrack "
1270 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001271 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001272 if (!IsClosed()) {
1273 for (const auto& track : local_stream->GetAudioTracks()) {
1274 RemoveAudioTrack(track.get(), local_stream);
1275 }
1276 for (const auto& track : local_stream->GetVideoTracks()) {
1277 RemoveVideoTrack(track.get(), local_stream);
1278 }
deadbeefab9b2d12015-10-14 11:33:11 -07001279 }
deadbeefab9b2d12015-10-14 11:33:11 -07001280 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001281 stream_observers_.erase(
1282 std::remove_if(
1283 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001284 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001285 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001286 }),
1287 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 if (IsClosed()) {
1290 return;
1291 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001292 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293}
1294
Steve Anton2d6c76a2018-01-05 17:10:52 -08001295RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001296 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001297 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001298 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001299 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001300 if (!track) {
1301 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1302 }
1303 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1304 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1306 "Track has invalid kind: " + track->kind());
1307 }
Steve Antonf9381f02017-12-14 10:23:57 -08001308 if (IsClosed()) {
1309 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1310 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001311 }
Steve Anton4171afb2017-11-20 10:20:22 -08001312 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001313 LOG_AND_RETURN_ERROR(
1314 RTCErrorType::INVALID_PARAMETER,
1315 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001316 }
Steve Antonf9381f02017-12-14 10:23:57 -08001317 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001318 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1319 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001320 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001321 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001322 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001323 }
1324 return sender_or_error;
1325}
deadbeefe1f9d832016-01-14 15:35:42 -08001326
Steve Antonf9381f02017-12-14 10:23:57 -08001327RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1328PeerConnection::AddTrackPlanB(
1329 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001330 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001331 if (stream_ids.size() > 1u) {
1332 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1333 "AddTrack with more than one stream is not "
1334 "supported with Plan B semantics.");
1335 }
1336 std::vector<std::string> adjusted_stream_ids = stream_ids;
1337 if (adjusted_stream_ids.empty()) {
1338 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1339 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001340 cricket::MediaType media_type =
1341 (track->kind() == MediaStreamTrackInterface::kAudioKind
1342 ? cricket::MEDIA_TYPE_AUDIO
1343 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001344 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001345 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001346 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001347 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001348 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001349 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001350 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001351 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001352 if (sender_info) {
1353 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001354 }
Steve Antonf9381f02017-12-14 10:23:57 -08001355 } else {
1356 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001357 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001358 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001359 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001360 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001361 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001362 if (sender_info) {
1363 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001364 }
deadbeefe1f9d832016-01-14 15:35:42 -08001365 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001366 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001367}
deadbeefe1f9d832016-01-14 15:35:42 -08001368
Steve Antonf9381f02017-12-14 10:23:57 -08001369RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1370PeerConnection::AddTrackUnifiedPlan(
1371 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001372 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001373 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1374 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001375 RTC_LOG(LS_INFO) << "Reusing an existing "
1376 << cricket::MediaTypeToString(transceiver->media_type())
1377 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001378 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001379 transceiver->internal()->set_direction(
1380 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001381 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001382 transceiver->internal()->set_direction(
1383 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001384 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001385 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001386 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001387 } else {
1388 cricket::MediaType media_type =
1389 (track->kind() == MediaStreamTrackInterface::kAudioKind
1390 ? cricket::MEDIA_TYPE_AUDIO
1391 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001392 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1393 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001394 std::string sender_id = track->id();
1395 // Avoid creating a sender with an existing ID by generating a random ID.
1396 // This can happen if this is the second time AddTrack has created a sender
1397 // for this track.
1398 if (FindSenderById(sender_id)) {
1399 sender_id = rtc::CreateRandomUuid();
1400 }
Florent Castelli892acf02018-10-01 22:47:20 +02001401 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001402 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1403 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001404 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001405 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001406 }
Steve Antonf9381f02017-12-14 10:23:57 -08001407 return transceiver->sender();
1408}
1409
1410rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1411PeerConnection::FindFirstTransceiverForAddedTrack(
1412 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1413 RTC_DCHECK(track);
1414 for (auto transceiver : transceivers_) {
1415 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001416 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001417 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001418 !transceiver->internal()->has_ever_been_used_to_send() &&
1419 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001420 return transceiver;
1421 }
1422 }
1423 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001424}
1425
1426bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1427 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001428 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001429}
1430
Steve Anton24db5732018-07-23 10:27:33 -07001431RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001432 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001433 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001434 if (!sender) {
1435 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1436 }
deadbeefe1f9d832016-01-14 15:35:42 -08001437 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001438 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1439 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001440 }
Steve Antonf9381f02017-12-14 10:23:57 -08001441 if (IsUnifiedPlan()) {
1442 auto transceiver = FindTransceiverBySender(sender);
1443 if (!transceiver || !sender->track()) {
1444 return RTCError::OK();
1445 }
1446 sender->SetTrack(nullptr);
1447 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001448 transceiver->internal()->set_direction(
1449 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001450 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001451 transceiver->internal()->set_direction(
1452 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001453 }
Steve Anton4171afb2017-11-20 10:20:22 -08001454 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001455 bool removed;
1456 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1457 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1458 } else {
1459 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1460 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1461 }
1462 if (!removed) {
1463 LOG_AND_RETURN_ERROR(
1464 RTCErrorType::INVALID_PARAMETER,
1465 "Couldn't find sender " + sender->id() + " to remove.");
1466 }
Steve Anton4171afb2017-11-20 10:20:22 -08001467 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001468 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001469 return RTCError::OK();
1470}
1471
1472rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1473PeerConnection::FindTransceiverBySender(
1474 rtc::scoped_refptr<RtpSenderInterface> sender) {
1475 for (auto transceiver : transceivers_) {
1476 if (transceiver->sender() == sender) {
1477 return transceiver;
1478 }
1479 }
1480 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001481}
1482
Steve Anton9158ef62017-11-27 13:01:52 -08001483RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1484PeerConnection::AddTransceiver(
1485 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1486 return AddTransceiver(track, RtpTransceiverInit());
1487}
1488
1489RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1490PeerConnection::AddTransceiver(
1491 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1492 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001493 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001494 RTC_CHECK(IsUnifiedPlan())
1495 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001496 if (!track) {
1497 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1498 }
1499 cricket::MediaType media_type;
1500 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1501 media_type = cricket::MEDIA_TYPE_AUDIO;
1502 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1503 media_type = cricket::MEDIA_TYPE_VIDEO;
1504 } else {
1505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1506 "Track kind is not audio or video");
1507 }
1508 return AddTransceiver(media_type, track, init);
1509}
1510
1511RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1512PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1513 return AddTransceiver(media_type, RtpTransceiverInit());
1514}
1515
1516RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1517PeerConnection::AddTransceiver(cricket::MediaType media_type,
1518 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001519 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001520 RTC_CHECK(IsUnifiedPlan())
1521 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001522 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1523 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1524 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1525 "media type is not audio or video");
1526 }
1527 return AddTransceiver(media_type, nullptr, init);
1528}
1529
1530RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1531PeerConnection::AddTransceiver(
1532 cricket::MediaType media_type,
1533 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001534 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001535 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001536 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1537 media_type == cricket::MEDIA_TYPE_VIDEO));
1538 if (track) {
1539 RTC_DCHECK_EQ(media_type,
1540 (track->kind() == MediaStreamTrackInterface::kAudioKind
1541 ? cricket::MEDIA_TYPE_AUDIO
1542 : cricket::MEDIA_TYPE_VIDEO));
1543 }
1544
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001545 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1546 init.send_encodings.size(), 0, 7, 8);
1547
Amit Hilbuchaa584152019-02-06 17:09:52 -08001548 size_t num_rids = absl::c_count_if(init.send_encodings,
1549 [](const RtpEncodingParameters& encoding) {
1550 return !encoding.rid.empty();
1551 });
1552 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001553 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001554 RTCErrorType::INVALID_PARAMETER,
1555 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001556 }
1557
Amit Hilbuchf4770402019-04-08 14:11:57 -07001558 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1559 [](const RtpEncodingParameters& encoding) {
1560 return !IsLegalRsidName(encoding.rid);
1561 })) {
1562 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1563 "Invalid RID value provided.");
1564 }
1565
Amit Hilbuchaa584152019-02-06 17:09:52 -08001566 if (absl::c_any_of(init.send_encodings,
1567 [](const RtpEncodingParameters& encoding) {
1568 return encoding.ssrc.has_value();
1569 })) {
1570 LOG_AND_RETURN_ERROR(
1571 RTCErrorType::UNSUPPORTED_PARAMETER,
1572 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001573 }
1574
1575 RtpParameters parameters;
1576 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001577
1578 // Encodings are dropped from the tail if too many are provided.
1579 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1580 parameters.encodings.erase(
1581 parameters.encodings.begin() + kMaxSimulcastStreams,
1582 parameters.encodings.end());
1583 }
1584
1585 // Single RID should be removed.
1586 if (parameters.encodings.size() == 1 &&
1587 !parameters.encodings[0].rid.empty()) {
1588 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1589 parameters.encodings[0].rid.clear();
1590 }
1591
1592 // If RIDs were not provided, they are generated for simulcast scenario.
1593 if (parameters.encodings.size() > 1 && num_rids == 0) {
1594 rtc::UniqueStringGenerator rid_generator;
1595 for (RtpEncodingParameters& encoding : parameters.encodings) {
1596 encoding.rid = rid_generator();
1597 }
1598 }
1599
Florent Castelli892acf02018-10-01 22:47:20 +02001600 if (UnimplementedRtpParameterHasValue(parameters)) {
1601 LOG_AND_RETURN_ERROR(
1602 RTCErrorType::UNSUPPORTED_PARAMETER,
1603 "Attempted to set an unimplemented parameter of RtpParameters.");
1604 }
Steve Anton9158ef62017-11-27 13:01:52 -08001605
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001606 auto result = cricket::CheckRtpParametersValues(parameters);
1607 if (!result.ok()) {
1608 LOG_AND_RETURN_ERROR(result.type(), result.message());
1609 }
1610
Steve Anton3d954a62018-04-02 11:27:23 -07001611 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1612 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001613 // Set the sender ID equal to the track ID if the track is specified unless
1614 // that sender ID is already in use.
1615 std::string sender_id =
1616 (track && !FindSenderById(track->id()) ? track->id()
1617 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001618 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001619 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001620 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1621 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1622 transceiver->internal()->set_direction(init.direction);
1623
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001624 if (update_negotiation_needed) {
1625 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001626 }
Steve Antonf9381f02017-12-14 10:23:57 -08001627
1628 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1629}
1630
Steve Anton02ee47c2018-01-10 16:26:06 -08001631rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1632PeerConnection::CreateSender(
1633 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001634 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001635 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001636 const std::vector<std::string>& stream_ids,
1637 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001638 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001639 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001640 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1641 RTC_DCHECK(!track ||
1642 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1643 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1644 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001645 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001646 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001647 } else {
1648 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1649 RTC_DCHECK(!track ||
1650 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1651 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001652 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001653 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001654 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001655 bool set_track_succeeded = sender->SetTrack(track);
1656 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001657 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001658 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001659 return sender;
1660}
1661
1662rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1663PeerConnection::CreateReceiver(cricket::MediaType media_type,
1664 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001665 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1666 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001667 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001668 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001669 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1670 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001671 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001672 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001673 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001674 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001675 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1676 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001677 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001678 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001679 return receiver;
1680}
1681
1682rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1683PeerConnection::CreateAndAddTransceiver(
1684 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1685 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1686 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001687 // Ensure that the new sender does not have an ID that is already in use by
1688 // another sender.
1689 // Allow receiver IDs to conflict since those come from remote SDP (which
1690 // could be invalid, but should not cause a crash).
1691 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001692 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001693 signaling_thread(),
1694 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001695 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001696 transceiver->internal()->SignalNegotiationNeeded.connect(
1697 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001698 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001699}
1700
Steve Anton52d86772018-02-20 15:48:12 -08001701void PeerConnection::OnNegotiationNeeded() {
1702 RTC_DCHECK_RUN_ON(signaling_thread());
1703 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001704 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001705}
1706
deadbeeffac06552015-11-25 11:26:01 -08001707rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001708 const std::string& kind,
1709 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001710 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001711 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1712 "Plan SdpSemantics. Please use AddTransceiver "
1713 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001714 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001715 if (IsClosed()) {
1716 return nullptr;
1717 }
Steve Anton4171afb2017-11-20 10:20:22 -08001718
Seth Hampson5b4f0752018-04-02 16:31:36 -07001719 // Internally we need to have one stream with Plan B semantics, so we
1720 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001721 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001722 if (stream_id.empty()) {
1723 stream_ids.push_back(rtc::CreateRandomUuid());
1724 RTC_LOG(LS_INFO)
1725 << "No stream_id specified for sender. Generated stream ID: "
1726 << stream_ids[0];
1727 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001728 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001729 }
1730
Steve Anton4171afb2017-11-20 10:20:22 -08001731 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001732 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001733 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001734 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001735 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001736 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001737 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001738 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001739 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001740 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001741 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001742 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001743 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001744 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001745 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001746 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001747 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001748 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001749 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001750 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001751 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001752
deadbeefe1f9d832016-01-14 15:35:42 -08001753 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001754}
1755
deadbeef70ab1a12015-09-28 16:53:55 -07001756std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1757 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001758 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001759 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001760 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001761 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001762 }
1763 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001764}
1765
Steve Anton4171afb2017-11-20 10:20:22 -08001766std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1767PeerConnection::GetSendersInternal() const {
1768 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1769 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001770 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001771 auto senders = transceiver->internal()->senders();
1772 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1773 }
1774 return all_senders;
1775}
1776
deadbeef70ab1a12015-09-28 16:53:55 -07001777std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1778PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001779 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001780 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001781 for (const auto& receiver : GetReceiversInternal()) {
1782 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001783 }
1784 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001785}
1786
Steve Anton4171afb2017-11-20 10:20:22 -08001787std::vector<
1788 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1789PeerConnection::GetReceiversInternal() const {
1790 std::vector<
1791 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1792 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001793 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001794 auto receivers = transceiver->internal()->receivers();
1795 all_receivers.insert(all_receivers.end(), receivers.begin(),
1796 receivers.end());
1797 }
1798 return all_receivers;
1799}
1800
Steve Anton9158ef62017-11-27 13:01:52 -08001801std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1802PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001803 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001804 RTC_CHECK(IsUnifiedPlan())
1805 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001806 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001807 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001808 all_transceivers.push_back(transceiver);
1809 }
1810 return all_transceivers;
1811}
1812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001814 MediaStreamTrackInterface* track,
1815 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001816 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001817 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001818 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return false;
1821 }
1822
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001823 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001824 // The StatsCollector is used to tell if a track is valid because it may
1825 // remember tracks that the PeerConnection previously removed.
1826 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1828 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001829 return false;
1830 }
Steve Antonad182762018-09-05 20:22:40 +00001831 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1832 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001833 return true;
1834}
1835
hbos74e1a4f2016-09-15 23:33:01 -07001836void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001837 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001838 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001839 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001840 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001841 stats_collector_->GetStatsReport(callback);
1842}
1843
Henrik Boström1df1bf82018-03-20 13:24:20 +01001844void PeerConnection::GetStats(
1845 rtc::scoped_refptr<RtpSenderInterface> selector,
1846 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1847 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001848 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001849 RTC_DCHECK(callback);
1850 RTC_DCHECK(stats_collector_);
1851 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1852 if (selector) {
1853 for (const auto& proxy_transceiver : transceivers_) {
1854 for (const auto& proxy_sender :
1855 proxy_transceiver->internal()->senders()) {
1856 if (proxy_sender == selector) {
1857 internal_sender = proxy_sender->internal();
1858 break;
1859 }
1860 }
1861 if (internal_sender)
1862 break;
1863 }
1864 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001865 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001866 // belong to the PeerConnection (in Plan B, senders can be removed from the
1867 // PeerConnection). This means that "all the stats objects representing the
1868 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1869 // produces an empty stats report.
1870 stats_collector_->GetStatsReport(internal_sender, callback);
1871}
1872
1873void PeerConnection::GetStats(
1874 rtc::scoped_refptr<RtpReceiverInterface> selector,
1875 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1876 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001877 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001878 RTC_DCHECK(callback);
1879 RTC_DCHECK(stats_collector_);
1880 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1881 if (selector) {
1882 for (const auto& proxy_transceiver : transceivers_) {
1883 for (const auto& proxy_receiver :
1884 proxy_transceiver->internal()->receivers()) {
1885 if (proxy_receiver == selector) {
1886 internal_receiver = proxy_receiver->internal();
1887 break;
1888 }
1889 }
1890 if (internal_receiver)
1891 break;
1892 }
1893 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001894 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001895 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1896 // the PeerConnection). This means that "all the stats objects representing
1897 // the selector" is an empty set. Invoking GetStatsReport() with a null
1898 // selector produces an empty stats report.
1899 stats_collector_->GetStatsReport(internal_receiver, callback);
1900}
1901
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001903 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001904 return signaling_state_;
1905}
1906
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907PeerConnectionInterface::IceConnectionState
1908PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001909 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 return ice_connection_state_;
1911}
1912
Alex Loiko9289eda2018-11-23 16:18:59 +00001913PeerConnectionInterface::IceConnectionState
1914PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001915 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001916 return standardized_ice_connection_state_;
1917}
1918
Jonas Olsson635474e2018-10-18 15:58:17 +02001919PeerConnectionInterface::PeerConnectionState
1920PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001921 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001922 return connection_state_;
1923}
1924
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925PeerConnectionInterface::IceGatheringState
1926PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001927 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 return ice_gathering_state_;
1929}
1930
Yves Gerey665174f2018-06-19 15:03:05 +02001931rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932 const std::string& label,
1933 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001934 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001935 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001936
deadbeefab9b2d12015-10-14 11:33:11 -07001937 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001938
kwibergd1fe2812016-04-27 06:47:29 -07001939 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001940 if (config) {
1941 internal_config.reset(new InternalDataChannelInit(*config));
1942 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001943 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001944 InternalCreateDataChannel(label, internal_config.get()));
1945 if (!channel.get()) {
1946 return nullptr;
1947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001948
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001949 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1950 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001951 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001952 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001953 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001954 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955 return DataChannelProxy::Create(signaling_thread(), channel.get());
1956}
1957
1958void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001959 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001960 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001961 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001962
nisse7ce109a2017-01-31 00:57:56 -08001963 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001964 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001965 return;
1966 }
deadbeefab9b2d12015-10-14 11:33:11 -07001967
Steve Anton8d3444d2017-10-20 15:30:51 -07001968 if (IsClosed()) {
1969 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001970 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001971 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001972 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001973 return;
1974 }
1975
Steve Anton25ca0ac2019-06-25 10:40:48 -07001976 // If a session error has occurred the PeerConnection is in a possibly
1977 // inconsistent state so fail right away.
1978 if (session_error() != SessionError::kNone) {
1979 std::string error_message = GetSessionErrorMsg();
1980 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
1981 PostCreateSessionDescriptionFailure(
1982 observer,
1983 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
1984 return;
1985 }
1986
zhihuang1c378ed2017-08-17 14:10:50 -07001987 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001988 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001989 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001990 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001991 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001992 return;
1993 }
1994
Steve Anton22da89f2018-01-25 13:58:07 -08001995 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1996 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1997 if (IsUnifiedPlan()) {
1998 RTCError error = HandleLegacyOfferOptions(options);
1999 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002000 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002001 return;
2002 }
2003 }
2004
zhihuang1c378ed2017-08-17 14:10:50 -07002005 cricket::MediaSessionOptions session_options;
2006 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002007 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008}
2009
Steve Anton22da89f2018-01-25 13:58:07 -08002010RTCError PeerConnection::HandleLegacyOfferOptions(
2011 const RTCOfferAnswerOptions& options) {
2012 RTC_DCHECK(IsUnifiedPlan());
2013
2014 if (options.offer_to_receive_audio == 0) {
2015 RemoveRecvDirectionFromReceivingTransceiversOfType(
2016 cricket::MEDIA_TYPE_AUDIO);
2017 } else if (options.offer_to_receive_audio == 1) {
2018 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2019 } else if (options.offer_to_receive_audio > 1) {
2020 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2021 "offer_to_receive_audio > 1 is not supported.");
2022 }
2023
2024 if (options.offer_to_receive_video == 0) {
2025 RemoveRecvDirectionFromReceivingTransceiversOfType(
2026 cricket::MEDIA_TYPE_VIDEO);
2027 } else if (options.offer_to_receive_video == 1) {
2028 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2029 } else if (options.offer_to_receive_video > 1) {
2030 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2031 "offer_to_receive_video > 1 is not supported.");
2032 }
2033
2034 return RTCError::OK();
2035}
2036
2037void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2038 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002039 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002040 RtpTransceiverDirection new_direction =
2041 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2042 if (new_direction != transceiver->direction()) {
2043 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2044 << " transceiver (MID="
2045 << transceiver->mid().value_or("<not set>") << ") from "
2046 << RtpTransceiverDirectionToString(
2047 transceiver->direction())
2048 << " to "
2049 << RtpTransceiverDirectionToString(new_direction)
2050 << " since CreateOffer specified offer_to_receive=0";
2051 transceiver->internal()->set_direction(new_direction);
2052 }
Steve Anton22da89f2018-01-25 13:58:07 -08002053 }
2054}
2055
2056void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2057 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002058 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002059 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002060 RTC_LOG(LS_INFO)
2061 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2062 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002063 RtpTransceiverInit init;
2064 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002065 AddTransceiver(media_type, nullptr, init,
2066 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002067 }
2068}
2069
2070std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2071PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2072 std::vector<
2073 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2074 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002075 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002076 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002077 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2078 receiving_transceivers.push_back(transceiver);
2079 }
2080 }
2081 return receiving_transceivers;
2082}
2083
htaa2a49d92016-03-04 02:51:39 -08002084void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2085 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002086 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002087 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002088 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002089 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002090 return;
2091 }
2092
Steve Anton25ca0ac2019-06-25 10:40:48 -07002093 // If a session error has occurred the PeerConnection is in a possibly
2094 // inconsistent state so fail right away.
2095 if (session_error() != SessionError::kNone) {
2096 std::string error_message = GetSessionErrorMsg();
2097 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2098 PostCreateSessionDescriptionFailure(
2099 observer,
2100 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2101 return;
2102 }
2103
Steve Antondffead82018-02-06 10:31:29 -08002104 if (!(signaling_state_ == kHaveRemoteOffer ||
2105 signaling_state_ == kHaveLocalPrAnswer)) {
2106 std::string error =
2107 "PeerConnection cannot create an answer in a state other than "
2108 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002109 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002110 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002111 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002112 return;
2113 }
2114
Steve Antondffead82018-02-06 10:31:29 -08002115 // The remote description should be set if we're in the right state.
2116 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002117
Steve Anton22da89f2018-01-25 13:58:07 -08002118 if (IsUnifiedPlan()) {
2119 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2120 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2121 "supported with Unified Plan semantics. Use the "
2122 "RtpTransceiver API instead.";
2123 }
2124 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2125 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2126 "supported with Unified Plan semantics. Use the "
2127 "RtpTransceiver API instead.";
2128 }
2129 }
2130
htaa2a49d92016-03-04 02:51:39 -08002131 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002132 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002133
Steve Antond25da372017-11-06 14:50:29 -08002134 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135}
2136
2137void PeerConnection::SetLocalDescription(
2138 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002139 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002140 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002141 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002142
Steve Anton80dd7b52018-02-16 17:08:42 -08002143 // The SetLocalDescription contract is that we take ownership of the session
2144 // description regardless of the outcome, so wrap it in a unique_ptr right
2145 // away. Ideally, SetLocalDescription's signature will be changed to take the
2146 // description as a unique_ptr argument to formalize this agreement.
2147 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2148
nisse7ce109a2017-01-31 00:57:56 -08002149 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002150 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002151 return;
2152 }
Steve Anton8a006912017-12-04 15:25:56 -08002153
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002155 PostSetSessionDescriptionFailure(
2156 observer,
2157 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002158 return;
2159 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002160
Steve Anton80dd7b52018-02-16 17:08:42 -08002161 // If a session error has occurred the PeerConnection is in a possibly
2162 // inconsistent state so fail right away.
2163 if (session_error() != SessionError::kNone) {
2164 std::string error_message = GetSessionErrorMsg();
2165 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002166 PostSetSessionDescriptionFailure(
2167 observer,
2168 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002169 return;
2170 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002171
Steve Anton80dd7b52018-02-16 17:08:42 -08002172 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2173 if (!error.ok()) {
2174 std::string error_message = GetSetDescriptionErrorMessage(
2175 cricket::CS_LOCAL, desc->GetType(), error);
2176 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002177 PostSetSessionDescriptionFailure(
2178 observer,
2179 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002180 return;
2181 }
2182
2183 // Grab the description type before moving ownership to ApplyLocalDescription,
2184 // which may destroy it before returning.
2185 const SdpType type = desc->GetType();
2186
2187 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002188 // |desc| may be destroyed at this point.
2189
2190 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002191 // If ApplyLocalDescription fails, the PeerConnection could be in an
2192 // inconsistent state, so act conservatively here and set the session error
2193 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2194 SetSessionError(SessionError::kContent, error.message());
2195 std::string error_message =
2196 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2197 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002198 PostSetSessionDescriptionFailure(
2199 observer,
2200 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002201 return;
2202 }
Steve Anton8a006912017-12-04 15:25:56 -08002203 RTC_DCHECK(local_description());
2204
2205 PostSetSessionDescriptionSuccess(observer);
2206
Steve Antonad182762018-09-05 20:22:40 +00002207 // MaybeStartGathering needs to be called after posting
2208 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2209 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002210 transport_controller_->MaybeStartGathering();
2211
Steve Antona3a92c22017-12-07 10:27:41 -08002212 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002213 // TODO(deadbeef): We already had to hop to the network thread for
2214 // MaybeStartGathering...
2215 network_thread()->Invoke<void>(
2216 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2217 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002218 // Make UMA notes about what was agreed to.
2219 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002220 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002221
2222 if (IsUnifiedPlan()) {
2223 bool was_negotiation_needed = is_negotiation_needed_;
2224 UpdateNegotiationNeeded();
2225 if (signaling_state() == kStable && was_negotiation_needed &&
2226 is_negotiation_needed_) {
2227 Observer()->OnRenegotiationNeeded();
2228 }
2229 }
2230
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002231 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002232}
2233
2234RTCError PeerConnection::ApplyLocalDescription(
2235 std::unique_ptr<SessionDescriptionInterface> desc) {
2236 RTC_DCHECK_RUN_ON(signaling_thread());
2237 RTC_DCHECK(desc);
2238
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 // Update stats here so that we have the most recent stats for tracks and
2240 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002241 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002242
Steve Antondcc3c022017-12-22 16:02:54 -08002243 // Take a reference to the old local description since it's used below to
2244 // compare against the new local description. When setting the new local
2245 // description, grab ownership of the replaced session description in case it
2246 // is the same as |old_local_description|, to keep it alive for the duration
2247 // of the method.
2248 const SessionDescriptionInterface* old_local_description =
2249 local_description();
2250 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002251 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002252 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002253 replaced_local_description = pending_local_description_
2254 ? std::move(pending_local_description_)
2255 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002256 current_local_description_ = std::move(desc);
2257 pending_local_description_ = nullptr;
2258 current_remote_description_ = std::move(pending_remote_description_);
2259 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002260 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002261 pending_local_description_ = std::move(desc);
2262 }
2263 // The session description to apply now must be accessed by
2264 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002265 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002266
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002267 // Report statistics about any use of simulcast.
2268 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2269 *local_description()->description());
2270
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002271 if (!is_caller_) {
2272 if (remote_description()) {
2273 // Remote description was applied first, so this PC is the callee.
2274 is_caller_ = false;
2275 } else {
2276 // Local description is applied first, so this PC is the caller.
2277 is_caller_ = true;
2278 }
2279 }
2280
Zhi Huange830e682018-03-30 10:48:35 -07002281 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2282 if (!error.ok()) {
2283 return error;
2284 }
2285
Steve Antondcc3c022017-12-22 16:02:54 -08002286 if (IsUnifiedPlan()) {
2287 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002288 cricket::CS_LOCAL, *local_description(), old_local_description,
2289 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002290 if (!error.ok()) {
2291 return error;
2292 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002293 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2294 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002295 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002296 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2297 // Note that code paths that don't set MID won't be able to use
2298 // information about DTLS transports.
2299 if (transceiver->mid()) {
2300 auto dtls_transport =
2301 LookupDtlsTransportByMidInternal(*transceiver->mid());
2302 transceiver->internal()->sender_internal()->set_transport(
2303 dtls_transport);
2304 transceiver->internal()->receiver_internal()->set_transport(
2305 dtls_transport);
2306 }
2307
Steve Antondcc3c022017-12-22 16:02:54 -08002308 const ContentInfo* content =
2309 FindMediaSectionForTransceiver(transceiver, local_description());
2310 if (!content) {
2311 continue;
2312 }
2313 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002314 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2315 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002316 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002317 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2318 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2319 // "recvonly", process the removal of a remote track for the media
2320 // description, given transceiver, removeList, and muteTracks.
2321 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2322 (transceiver->internal()->fired_direction() &&
2323 RtpTransceiverDirectionHasRecv(
2324 *transceiver->internal()->fired_direction()))) {
2325 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2326 &removed_streams);
2327 }
2328 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2329 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002330 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002331 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002332 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002333 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002334 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002335 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002336 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002337 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002338 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002339 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002340 }
2341 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002342 // Media channels will be created only when offer is set. These may use new
2343 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002344 if (type == SdpType::kOffer) {
2345 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2346 // description is applied. Restore back to old description.
2347 RTCError error = CreateChannels(*local_description()->description());
2348 if (!error.ok()) {
2349 return error;
2350 }
2351 }
Steve Antondcc3c022017-12-22 16:02:54 -08002352 // Remove unused channels if MediaContentDescription is rejected.
2353 RemoveUnusedChannels(local_description()->description());
2354 }
Steve Anton8a006912017-12-04 15:25:56 -08002355
Zhi Huange830e682018-03-30 10:48:35 -07002356 error = UpdateSessionState(type, cricket::CS_LOCAL,
2357 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002358 if (!error.ok()) {
2359 return error;
2360 }
Steve Antondcc3c022017-12-22 16:02:54 -08002361
Steve Anton8a006912017-12-04 15:25:56 -08002362 if (remote_description()) {
2363 // Now that we have a local description, we can push down remote candidates.
2364 UseCandidatesInSessionDescription(remote_description());
2365 }
2366
2367 pending_ice_restarts_.clear();
2368 if (session_error() != SessionError::kNone) {
2369 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2370 }
2371
deadbeefab9b2d12015-10-14 11:33:11 -07002372 // If setting the description decided our SSL role, allocate any necessary
2373 // SCTP sids.
2374 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002375 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002376 AllocateSctpSids(role);
2377 }
2378
Steve Antond3679212018-01-17 17:41:02 -08002379 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002380 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002381 const ContentInfo* content =
2382 FindMediaSectionForTransceiver(transceiver, local_description());
2383 if (!content) {
2384 continue;
2385 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002386 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2387 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002388 // 0 is a special value meaning "this sender has no associated send
2389 // stream". Need to call this so the sender won't attempt to configure
2390 // a no longer existing stream and run into DCHECKs in the lower
2391 // layers.
2392 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002393 } else {
2394 // Get the StreamParams from the channel which could generate SSRCs.
2395 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002396 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002397 streams[0].stream_ids());
2398 transceiver->internal()->sender_internal()->SetSsrc(
2399 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002400 }
2401 }
2402 } else {
2403 // Plan B semantics.
2404
Steve Antondcc3c022017-12-22 16:02:54 -08002405 // Update state and SSRC of local MediaStreams and DataChannels based on the
2406 // local session description.
2407 const cricket::ContentInfo* audio_content =
2408 GetFirstAudioContent(local_description()->description());
2409 if (audio_content) {
2410 if (audio_content->rejected) {
2411 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2412 } else {
2413 const cricket::AudioContentDescription* audio_desc =
2414 audio_content->media_description()->as_audio();
2415 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2416 }
deadbeeffaac4972015-11-12 15:33:07 -08002417 }
deadbeefab9b2d12015-10-14 11:33:11 -07002418
Steve Antondcc3c022017-12-22 16:02:54 -08002419 const cricket::ContentInfo* video_content =
2420 GetFirstVideoContent(local_description()->description());
2421 if (video_content) {
2422 if (video_content->rejected) {
2423 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2424 } else {
2425 const cricket::VideoContentDescription* video_desc =
2426 video_content->media_description()->as_video();
2427 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2428 }
deadbeeffaac4972015-11-12 15:33:07 -08002429 }
deadbeefab9b2d12015-10-14 11:33:11 -07002430 }
2431
2432 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002433 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002434 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002435 const cricket::RtpDataContentDescription* rtp_data_desc =
2436 data_content->media_description()->as_rtp_data();
2437 // rtp_data_desc will be null if this is an SCTP description.
2438 if (rtp_data_desc) {
2439 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002440 }
2441 }
2442
Steve Anton8a006912017-12-04 15:25:56 -08002443 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444}
2445
Steve Anton06817cd2018-12-18 15:55:30 -08002446// The SDP parser used to populate these values by default for the 'content
2447// name' if an a=mid line was absent.
2448static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2449 switch (media_type) {
2450 case cricket::MEDIA_TYPE_AUDIO:
2451 return cricket::CN_AUDIO;
2452 case cricket::MEDIA_TYPE_VIDEO:
2453 return cricket::CN_VIDEO;
2454 case cricket::MEDIA_TYPE_DATA:
2455 return cricket::CN_DATA;
2456 }
2457 RTC_NOTREACHED();
2458 return "";
2459}
2460
2461void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002462 cricket::SessionDescription* new_remote_description) {
2463 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002464 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002465 const cricket::ContentInfos& local_contents =
2466 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002467 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002468 const cricket::ContentInfos& remote_contents =
2469 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002470 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002471 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2472 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002473 if (!content.name.empty()) {
2474 continue;
2475 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002476 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002477 absl::string_view source_explanation;
2478 if (IsUnifiedPlan()) {
2479 if (i < local_contents.size()) {
2480 new_mid = local_contents[i].name;
2481 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002482 } else if (i < remote_contents.size()) {
2483 new_mid = remote_contents[i].name;
2484 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002485 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002486 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002487 source_explanation = "generated just now";
2488 }
2489 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002490 new_mid = std::string(
2491 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002492 source_explanation = "to match pre-existing behavior";
2493 }
Steve Antond7180cc2019-02-07 10:44:53 -08002494 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002495 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002496 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002497 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2498 << " is missing an a=mid line. Filling in the value '"
2499 << new_mid << "' " << source_explanation << ".";
2500 }
2501}
2502
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002503void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002504 SetSessionDescriptionObserver* observer,
2505 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002506 SetRemoteDescription(
2507 std::unique_ptr<SessionDescriptionInterface>(desc),
2508 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2509 new SetRemoteDescriptionObserverAdapter(this, observer)));
2510}
2511
2512void PeerConnection::SetRemoteDescription(
2513 std::unique_ptr<SessionDescriptionInterface> desc,
2514 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002515 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002516 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002517
nisse7ce109a2017-01-31 00:57:56 -08002518 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002519 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002520 return;
2521 }
Steve Anton8a006912017-12-04 15:25:56 -08002522
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002523 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002524 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002525 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002526 return;
2527 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002528
Steve Anton80dd7b52018-02-16 17:08:42 -08002529 // If a session error has occurred the PeerConnection is in a possibly
2530 // inconsistent state so fail right away.
2531 if (session_error() != SessionError::kNone) {
2532 std::string error_message = GetSessionErrorMsg();
2533 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2534 observer->OnSetRemoteDescriptionComplete(
2535 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2536 return;
2537 }
Steve Anton71439a62018-02-15 11:53:06 -08002538
Steve Antonba42e992018-04-09 14:10:01 -07002539 if (desc->GetType() == SdpType::kOffer) {
2540 // Report to UMA the format of the received offer.
2541 ReportSdpFormatReceived(*desc);
2542 }
2543
Steve Anton06817cd2018-12-18 15:55:30 -08002544 // Handle remote descriptions missing a=mid lines for interop with legacy end
2545 // points.
2546 FillInMissingRemoteMids(desc->description());
2547
Steve Anton80dd7b52018-02-16 17:08:42 -08002548 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002549 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002550 std::string error_message = GetSetDescriptionErrorMessage(
2551 cricket::CS_REMOTE, desc->GetType(), error);
2552 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002553 observer->OnSetRemoteDescriptionComplete(
2554 RTCError(error.type(), std::move(error_message)));
2555 return;
2556 }
Steve Anton71439a62018-02-15 11:53:06 -08002557
Steve Anton80dd7b52018-02-16 17:08:42 -08002558 // Grab the description type before moving ownership to
2559 // ApplyRemoteDescription, which may destroy it before returning.
2560 const SdpType type = desc->GetType();
2561
2562 error = ApplyRemoteDescription(std::move(desc));
2563 // |desc| may be destroyed at this point.
2564
2565 if (!error.ok()) {
2566 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2567 // inconsistent state, so act conservatively here and set the session error
2568 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2569 SetSessionError(SessionError::kContent, error.message());
2570 std::string error_message =
2571 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2572 RTC_LOG(LS_ERROR) << error_message;
2573 observer->OnSetRemoteDescriptionComplete(
2574 RTCError(error.type(), std::move(error_message)));
2575 return;
2576 }
2577 RTC_DCHECK(remote_description());
2578
2579 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002580 // TODO(deadbeef): We already had to hop to the network thread for
2581 // MaybeStartGathering...
2582 network_thread()->Invoke<void>(
2583 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2584 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002585 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002586 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002587 }
2588
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002589 if (IsUnifiedPlan()) {
2590 bool was_negotiation_needed = is_negotiation_needed_;
2591 UpdateNegotiationNeeded();
2592 if (signaling_state() == kStable && was_negotiation_needed &&
2593 is_negotiation_needed_) {
2594 Observer()->OnRenegotiationNeeded();
2595 }
2596 }
2597
Steve Anton8a006912017-12-04 15:25:56 -08002598 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002599 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002600}
2601
2602RTCError PeerConnection::ApplyRemoteDescription(
2603 std::unique_ptr<SessionDescriptionInterface> desc) {
2604 RTC_DCHECK_RUN_ON(signaling_thread());
2605 RTC_DCHECK(desc);
2606
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002607 // Update stats here so that we have the most recent stats for tracks and
2608 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002609 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002610
Steve Antondcc3c022017-12-22 16:02:54 -08002611 // Take a reference to the old remote description since it's used below to
2612 // compare against the new remote description. When setting the new remote
2613 // description, grab ownership of the replaced session description in case it
2614 // is the same as |old_remote_description|, to keep it alive for the duration
2615 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002616 const SessionDescriptionInterface* old_remote_description =
2617 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002618 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002619 SdpType type = desc->GetType();
2620 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002621 replaced_remote_description = pending_remote_description_
2622 ? std::move(pending_remote_description_)
2623 : std::move(current_remote_description_);
2624 current_remote_description_ = std::move(desc);
2625 pending_remote_description_ = nullptr;
2626 current_local_description_ = std::move(pending_local_description_);
2627 } else {
2628 replaced_remote_description = std::move(pending_remote_description_);
2629 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002630 }
Steve Anton8a006912017-12-04 15:25:56 -08002631 // The session description to apply now must be accessed by
2632 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002633 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002634
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002635 // Report statistics about any use of simulcast.
2636 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2637 *remote_description()->description());
2638
Zhi Huange830e682018-03-30 10:48:35 -07002639 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2640 if (!error.ok()) {
2641 return error;
2642 }
Steve Anton8a006912017-12-04 15:25:56 -08002643 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002644 if (IsUnifiedPlan()) {
2645 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002646 cricket::CS_REMOTE, *remote_description(), local_description(),
2647 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002648 if (!error.ok()) {
2649 return error;
2650 }
Steve Antondcc3c022017-12-22 16:02:54 -08002651 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002652 // Media channels will be created only when offer is set. These may use new
2653 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002654 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002655 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002656 // description is applied. Restore back to old description.
2657 RTCError error = CreateChannels(*remote_description()->description());
2658 if (!error.ok()) {
2659 return error;
2660 }
2661 }
Steve Antondcc3c022017-12-22 16:02:54 -08002662 // Remove unused channels if MediaContentDescription is rejected.
2663 RemoveUnusedChannels(remote_description()->description());
2664 }
Steve Anton8a006912017-12-04 15:25:56 -08002665
Zhi Huange830e682018-03-30 10:48:35 -07002666 // NOTE: Candidates allocation will be initiated only when
2667 // SetLocalDescription is called.
2668 error = UpdateSessionState(type, cricket::CS_REMOTE,
2669 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002670 if (!error.ok()) {
2671 return error;
2672 }
2673
2674 if (local_description() &&
2675 !UseCandidatesInSessionDescription(remote_description())) {
2676 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2677 }
2678
2679 if (old_remote_description) {
2680 for (const cricket::ContentInfo& content :
2681 old_remote_description->description()->contents()) {
2682 // Check if this new SessionDescription contains new ICE ufrag and
2683 // password that indicates the remote peer requests an ICE restart.
2684 // TODO(deadbeef): When we start storing both the current and pending
2685 // remote description, this should reset pending_ice_restarts and compare
2686 // against the current description.
2687 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2688 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002689 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002690 pending_ice_restarts_.insert(content.name);
2691 }
2692 } else {
2693 // We retain all received candidates only if ICE is not restarted.
2694 // When ICE is restarted, all previous candidates belong to an old
2695 // generation and should not be kept.
2696 // TODO(deadbeef): This goes against the W3C spec which says the remote
2697 // description should only contain candidates from the last set remote
2698 // description plus any candidates added since then. We should remove
2699 // this once we're sure it won't break anything.
2700 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2701 old_remote_description, content.name, mutable_remote_description());
2702 }
2703 }
2704 }
2705
2706 if (session_error() != SessionError::kNone) {
2707 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2708 }
2709
2710 // Set the the ICE connection state to connecting since the connection may
2711 // become writable with peer reflexive candidates before any remote candidate
2712 // is signaled.
2713 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2714 // is to have a new signal the indicates a change in checking state from the
2715 // transport and expose a new checking() member from transport that can be
2716 // read to determine the current checking state. The existing SignalConnecting
2717 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002718 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002719 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002720 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2721 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2722 }
2723
deadbeefab9b2d12015-10-14 11:33:11 -07002724 // If setting the description decided our SSL role, allocate any necessary
2725 // SCTP sids.
2726 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002727 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002728 AllocateSctpSids(role);
2729 }
2730
Steve Antondcc3c022017-12-22 16:02:54 -08002731 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002732 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002733 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002734 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002735 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002736 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002737 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002738 const ContentInfo* content =
2739 FindMediaSectionForTransceiver(transceiver, remote_description());
2740 if (!content) {
2741 continue;
2742 }
2743 const MediaContentDescription* media_desc = content->media_description();
2744 RtpTransceiverDirection local_direction =
2745 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002746 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2747 // RTCSessionDescription: Set the associated remote streams given
2748 // transceiver.[[Receiver]], msids, addList, and removeList".
2749 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2750 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2751 std::vector<std::string> stream_ids;
2752 if (!media_desc->streams().empty()) {
2753 // The remote description has signaled the stream IDs.
2754 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002755 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002756 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2757 << " (" << GetStreamIdsString(stream_ids) << ").";
2758 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2759 stream_ids, &added_streams,
2760 &removed_streams);
2761 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2762 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2763 // and transceiver's current direction is neither sendrecv nor recvonly,
2764 // process the addition of a remote track for the media description.
2765 if (!transceiver->fired_direction() ||
2766 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2767 RTC_LOG(LS_INFO)
2768 << "Processing the addition of a remote track for MID="
2769 << content->name << ".";
2770 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002771 }
Steve Antondcc3c022017-12-22 16:02:54 -08002772 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002773 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002774 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2775 // removal of a remote track for the media description, given transceiver,
2776 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002777 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002778 (transceiver->fired_direction() &&
2779 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2780 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2781 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002782 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002783 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002784 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002785 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002786 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002787 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002788 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002789 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002790 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002791 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2792 if (transceiver->mid()) {
2793 auto dtls_transport =
2794 LookupDtlsTransportByMidInternal(*transceiver->mid());
2795 transceiver->internal()->sender_internal()->set_transport(
2796 dtls_transport);
2797 transceiver->internal()->receiver_internal()->set_transport(
2798 dtls_transport);
2799 }
Steve Antondcc3c022017-12-22 16:02:54 -08002800 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002801 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002802 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002803 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002804 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2805 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002806 transceiver->Stop();
2807 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002808 if (!content->rejected &&
2809 RtpTransceiverDirectionHasRecv(local_direction)) {
2810 // Set ssrc to 0 in the case of an unsignalled ssrc.
2811 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002812 if (!media_desc->streams().empty() &&
2813 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002814 ssrc = media_desc->streams()[0].first_ssrc();
2815 }
2816 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002817 }
Steve Antondcc3c022017-12-22 16:02:54 -08002818 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002819 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002820 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002821 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002822 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002823 observer->OnTrack(transceiver);
2824 observer->OnAddTrack(transceiver->receiver(),
2825 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002826 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002827 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002828 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002829 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002830 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002831 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002832 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002833 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002834 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002835 }
Steve Antondcc3c022017-12-22 16:02:54 -08002836 }
2837
Henrik Boströmfdb92012017-11-09 19:55:44 +01002838 const cricket::ContentInfo* audio_content =
2839 GetFirstAudioContent(remote_description()->description());
2840 const cricket::ContentInfo* video_content =
2841 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002842 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002843 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002844 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002845 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002846 const cricket::RtpDataContentDescription* rtp_data_desc =
2847 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002848
2849 // Check if the descriptions include streams, just in case the peer supports
2850 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002851 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002852 (audio_desc && !audio_desc->streams().empty()) ||
2853 (video_desc && !video_desc->streams().empty())) {
2854 remote_peer_supports_msid_ = true;
2855 }
deadbeefab9b2d12015-10-14 11:33:11 -07002856
2857 // We wait to signal new streams until we finish processing the description,
2858 // since only at that point will new streams have all their tracks.
2859 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2860
Steve Antondcc3c022017-12-22 16:02:54 -08002861 if (!IsUnifiedPlan()) {
2862 // TODO(steveanton): When removing RTP senders/receivers in response to a
2863 // rejected media section, there is some cleanup logic that expects the
2864 // voice/ video channel to still be set. But in this method the voice/video
2865 // channel would have been destroyed by the SetRemoteDescription caller
2866 // above so the cleanup that relies on them fails to run. The RemoveSenders
2867 // calls should be moved to right before the DestroyChannel calls to fix
2868 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002869
Steve Antondcc3c022017-12-22 16:02:54 -08002870 // Find all audio rtp streams and create corresponding remote AudioTracks
2871 // and MediaStreams.
2872 if (audio_content) {
2873 if (audio_content->rejected) {
2874 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2875 } else {
2876 bool default_audio_track_needed =
2877 !remote_peer_supports_msid_ &&
2878 RtpTransceiverDirectionHasSend(audio_desc->direction());
2879 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2880 default_audio_track_needed, audio_desc->type(),
2881 new_streams);
2882 }
deadbeeffaac4972015-11-12 15:33:07 -08002883 }
deadbeefab9b2d12015-10-14 11:33:11 -07002884
Steve Antondcc3c022017-12-22 16:02:54 -08002885 // Find all video rtp streams and create corresponding remote VideoTracks
2886 // and MediaStreams.
2887 if (video_content) {
2888 if (video_content->rejected) {
2889 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2890 } else {
2891 bool default_video_track_needed =
2892 !remote_peer_supports_msid_ &&
2893 RtpTransceiverDirectionHasSend(video_desc->direction());
2894 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2895 default_video_track_needed, video_desc->type(),
2896 new_streams);
2897 }
deadbeeffaac4972015-11-12 15:33:07 -08002898 }
deadbeefab9b2d12015-10-14 11:33:11 -07002899
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002900 // If this is an RTP data transport, update the DataChannels with the
2901 // information from the remote peer.
2902 if (rtp_data_desc) {
2903 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002904 }
deadbeefab9b2d12015-10-14 11:33:11 -07002905
Steve Antondcc3c022017-12-22 16:02:54 -08002906 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002907 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002908 for (size_t i = 0; i < new_streams->count(); ++i) {
2909 MediaStreamInterface* new_stream = new_streams->at(i);
2910 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002911 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002912 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2913 }
deadbeefab9b2d12015-10-14 11:33:11 -07002914
Steve Antondcc3c022017-12-22 16:02:54 -08002915 UpdateEndedRemoteMediaStreams();
2916 }
deadbeefab9b2d12015-10-14 11:33:11 -07002917
Steve Anton8a006912017-12-04 15:25:56 -08002918 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002919}
2920
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002921void PeerConnection::SetAssociatedRemoteStreams(
2922 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2923 const std::vector<std::string>& stream_ids,
2924 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2925 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2926 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2927 for (const std::string& stream_id : stream_ids) {
2928 rtc::scoped_refptr<MediaStreamInterface> stream =
2929 remote_streams_->find(stream_id);
2930 if (!stream) {
2931 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2932 MediaStream::Create(stream_id));
2933 remote_streams_->AddStream(stream);
2934 added_streams->push_back(stream);
2935 }
2936 media_streams.push_back(stream);
2937 }
2938 // Special case: "a=msid" missing, use random stream ID.
2939 if (media_streams.empty() &&
2940 !(remote_description()->description()->msid_signaling() &
2941 cricket::kMsidSignalingMediaSection)) {
2942 if (!missing_msid_default_stream_) {
2943 missing_msid_default_stream_ = MediaStreamProxy::Create(
2944 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2945 added_streams->push_back(missing_msid_default_stream_);
2946 }
2947 media_streams.push_back(missing_msid_default_stream_);
2948 }
2949 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2950 receiver->streams();
2951 // SetStreams() will add/remove the receiver's track to/from the streams. This
2952 // differs from the spec - the spec uses an "addList" and "removeList" to
2953 // update the stream-track relationships in a later step. We do this earlier,
2954 // changing the order of things, but the end-result is the same.
2955 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2956 // instead. https://crbug.com/webrtc/9480
2957 receiver->SetStreams(media_streams);
2958 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2959}
2960
Steve Anton0f5400a2018-07-17 14:25:36 -07002961void PeerConnection::ProcessRemovalOfRemoteTrack(
2962 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2963 transceiver,
2964 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2965 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2966 RTC_DCHECK(transceiver->mid());
2967 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2968 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002969 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002970 transceiver->internal()->receiver_internal()->streams();
2971 // This will remove the remote track from the streams.
2972 transceiver->internal()->receiver_internal()->set_stream_ids({});
2973 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002974 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2975}
2976
2977void PeerConnection::RemoveRemoteStreamsIfEmpty(
2978 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2979 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2980 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2981 // streams, see if the stream was removed by checking if this was the last
2982 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002983 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002984 if (remote_stream->GetAudioTracks().empty() &&
2985 remote_stream->GetVideoTracks().empty()) {
2986 remote_streams_->RemoveStream(remote_stream);
2987 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002988 }
2989 }
2990}
2991
Steve Antondcc3c022017-12-22 16:02:54 -08002992RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2993 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002994 const SessionDescriptionInterface& new_session,
2995 const SessionDescriptionInterface* old_local_description,
2996 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002997 RTC_DCHECK(IsUnifiedPlan());
2998
Steve Anton7464fca2018-01-19 11:10:37 -08002999 const cricket::ContentGroup* bundle_group = nullptr;
3000 if (new_session.GetType() == SdpType::kOffer) {
3001 auto bundle_group_or_error =
3002 GetEarlyBundleGroup(*new_session.description());
3003 if (!bundle_group_or_error.ok()) {
3004 return bundle_group_or_error.MoveError();
3005 }
3006 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003007 }
Steve Antondcc3c022017-12-22 16:02:54 -08003008
Steve Antondcc3c022017-12-22 16:02:54 -08003009 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003010 for (size_t i = 0; i < new_contents.size(); ++i) {
3011 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003012 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003013 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003014 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3015 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003016 const cricket::ContentInfo* old_local_content = nullptr;
3017 if (old_local_description &&
3018 i < old_local_description->description()->contents().size()) {
3019 old_local_content =
3020 &old_local_description->description()->contents()[i];
3021 }
3022 const cricket::ContentInfo* old_remote_content = nullptr;
3023 if (old_remote_description &&
3024 i < old_remote_description->description()->contents().size()) {
3025 old_remote_content =
3026 &old_remote_description->description()->contents()[i];
3027 }
Steve Antondcc3c022017-12-22 16:02:54 -08003028 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003029 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3030 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003031 if (!transceiver_or_error.ok()) {
3032 return transceiver_or_error.MoveError();
3033 }
3034 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003035 RTCError error =
3036 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3037 if (!error.ok()) {
3038 return error;
3039 }
3040 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003041 if (GetDataMid() && new_content.name != *GetDataMid()) {
3042 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003043 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3044 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003045 continue;
3046 }
3047 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3048 if (!error.ok()) {
3049 return error;
3050 }
Steve Antondcc3c022017-12-22 16:02:54 -08003051 } else {
3052 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3053 "Unknown section type.");
3054 }
3055 }
3056
3057 return RTCError::OK();
3058}
3059
3060RTCError PeerConnection::UpdateTransceiverChannel(
3061 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3062 transceiver,
3063 const cricket::ContentInfo& content,
3064 const cricket::ContentGroup* bundle_group) {
3065 RTC_DCHECK(IsUnifiedPlan());
3066 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003067 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003068 if (content.rejected) {
3069 if (channel) {
3070 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003071 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003072 }
3073 } else {
3074 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003075 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003076 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003077 } else {
Steve Anton69470252018-02-09 11:43:08 -08003078 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003079 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003080 }
3081 if (!channel) {
3082 LOG_AND_RETURN_ERROR(
3083 RTCErrorType::INTERNAL_ERROR,
3084 "Failed to create channel for mid=" + content.name);
3085 }
3086 transceiver->internal()->SetChannel(channel);
3087 }
3088 }
3089 return RTCError::OK();
3090}
3091
Steve Antonfa2260d2017-12-28 16:38:23 -08003092RTCError PeerConnection::UpdateDataChannel(
3093 cricket::ContentSource source,
3094 const cricket::ContentInfo& content,
3095 const cricket::ContentGroup* bundle_group) {
3096 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003097 // If data channels are disabled, ignore this media section. CreateAnswer
3098 // will take care of rejecting it.
3099 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003100 }
3101 if (content.rejected) {
3102 DestroyDataChannel();
3103 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003104 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003105 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003106 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3107 "Failed to create data channel.");
3108 }
3109 }
3110 if (source == cricket::CS_REMOTE) {
3111 const MediaContentDescription* data_desc = content.media_description();
3112 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3113 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3114 }
3115 }
3116 }
3117 return RTCError::OK();
3118}
3119
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003120// This method will extract any send encodings that were sent by the remote
3121// connection. This is currently only relevant for Simulcast scenario (where
3122// the number of layers may be communicated by the server).
3123static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3124 const MediaContentDescription& desc) {
3125 if (!desc.HasSimulcast()) {
3126 return {};
3127 }
3128 std::vector<RtpEncodingParameters> result;
3129 const SimulcastDescription& simulcast = desc.simulcast_description();
3130
3131 // This is a remote description, the parameters we are after should appear
3132 // as receive streams.
3133 for (const auto& alternatives : simulcast.receive_layers()) {
3134 RTC_DCHECK(!alternatives.empty());
3135 // There is currently no way to specify or choose from alternatives.
3136 // We will always use the first alternative, which is the most preferred.
3137 const SimulcastLayer& layer = alternatives[0];
3138 RtpEncodingParameters parameters;
3139 parameters.rid = layer.rid;
3140 parameters.active = !layer.is_paused;
3141 result.push_back(parameters);
3142 }
3143
3144 return result;
3145}
3146
3147static RTCError UpdateSimulcastLayerStatusInSender(
3148 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003149 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003150 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003151 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003152 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003153
3154 // The simulcast envelope cannot be changed, only the status of the streams.
3155 // So we will iterate over the send encodings rather than the layers.
3156 for (RtpEncodingParameters& encoding : parameters.encodings) {
3157 auto iter = std::find_if(layers.begin(), layers.end(),
3158 [&encoding](const SimulcastLayer& layer) {
3159 return layer.rid == encoding.rid;
3160 });
3161 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003162 if (iter == layers.end()) {
3163 disabled_layers.push_back(encoding.rid);
3164 continue;
3165 }
3166
3167 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003168 }
3169
Amit Hilbuch619b2942019-02-26 15:55:19 -08003170 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003171 if (result.ok()) {
3172 result = sender->DisableEncodingLayers(disabled_layers);
3173 }
3174
3175 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003176}
3177
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003178static bool SimulcastIsRejected(
3179 const ContentInfo* local_content,
3180 const MediaContentDescription& answer_media_desc) {
3181 bool simulcast_offered = local_content &&
3182 local_content->media_description() &&
3183 local_content->media_description()->HasSimulcast();
3184 bool simulcast_answered = answer_media_desc.HasSimulcast();
3185 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3186 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3187 return simulcast_offered && (!simulcast_answered || !rids_supported);
3188}
3189
Amit Hilbuch2297d332019-02-19 12:49:22 -08003190static RTCError DisableSimulcastInSender(
3191 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003192 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003193 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003194 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003195 return RTCError::OK();
3196 }
3197
Amit Hilbuch2297d332019-02-19 12:49:22 -08003198 std::vector<std::string> disabled_layers;
3199 std::transform(
3200 parameters.encodings.begin() + 1, parameters.encodings.end(),
3201 std::back_inserter(disabled_layers),
3202 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3203 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003204}
3205
Steve Antondcc3c022017-12-22 16:02:54 -08003206RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3207PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003208 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003209 size_t mline_index,
3210 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003211 const ContentInfo* old_local_content,
3212 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003213 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003214 // If this is an offer then the m= section might be recycled. If the m=
3215 // section is being recycled (defined as: rejected in the current local or
3216 // remote description and not rejected in new description), dissociate the
3217 // currently associated RtpTransceiver by setting its mid property to null,
3218 // and discard the mapping between the transceiver and its m= section index.
3219 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3220 old_remote_content)) {
3221 // We want to dissociate the transceiver that has the rejected mid.
3222 const std::string& old_mid =
3223 (old_local_content && old_local_content->rejected)
3224 ? old_local_content->name
3225 : old_remote_content->name;
3226 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003227 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003228 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3229 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003230 old_transceiver->internal()->set_mid(absl::nullopt);
3231 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003232 }
3233 }
3234 const MediaContentDescription* media_desc = content.media_description();
3235 auto transceiver = GetAssociatedTransceiver(content.name);
3236 if (source == cricket::CS_LOCAL) {
3237 // Find the RtpTransceiver that corresponds to this m= section, using the
3238 // mapping between transceivers and m= section indices established when
3239 // creating the offer.
3240 if (!transceiver) {
3241 transceiver = GetTransceiverByMLineIndex(mline_index);
3242 }
3243 if (!transceiver) {
3244 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3245 "Unknown transceiver");
3246 }
3247 } else {
3248 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3249 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3250 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003251 // When simulcast is requested, a transceiver cannot be associated because
3252 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003253 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003254 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3255 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003256 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3257 }
3258 // If no RtpTransceiver was found in the previous step, create one with a
3259 // recvonly direction.
3260 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003261 RTC_LOG(LS_INFO) << "Adding "
3262 << cricket::MediaTypeToString(media_desc->type())
3263 << " transceiver for MID=" << content.name
3264 << " at i=" << mline_index
3265 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003266 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003267 std::vector<RtpEncodingParameters> send_encodings =
3268 GetSendEncodingsFromRemoteDescription(*media_desc);
3269 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3270 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003271 std::string receiver_id;
3272 if (!media_desc->streams().empty()) {
3273 receiver_id = media_desc->streams()[0].id;
3274 } else {
3275 receiver_id = rtc::CreateRandomUuid();
3276 }
3277 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003278 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003279 transceiver->internal()->set_direction(
3280 RtpTransceiverDirection::kRecvOnly);
3281 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003282
3283 // Check if the offer indicated simulcast but the answer rejected it.
3284 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003285 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003286 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003287 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003288 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003289 if (!error.ok()) {
3290 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3291 return std::move(error);
3292 }
3293 }
Steve Antondcc3c022017-12-22 16:02:54 -08003294 }
3295 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003296 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003297 LOG_AND_RETURN_ERROR(
3298 RTCErrorType::INVALID_PARAMETER,
3299 "Transceiver type does not match media description type.");
3300 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003301 if (media_desc->HasSimulcast()) {
3302 std::vector<SimulcastLayer> layers =
3303 source == cricket::CS_LOCAL
3304 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3305 : media_desc->simulcast_description()
3306 .receive_layers()
3307 .GetAllLayers();
3308 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003309 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003310 if (!error.ok()) {
3311 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3312 return std::move(error);
3313 }
3314 }
Steve Antondcc3c022017-12-22 16:02:54 -08003315 // Associate the found or created RtpTransceiver with the m= section by
3316 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3317 // section, and establish a mapping between the transceiver and the index of
3318 // the m= section.
3319 transceiver->internal()->set_mid(content.name);
3320 transceiver->internal()->set_mline_index(mline_index);
3321 return std::move(transceiver);
3322}
3323
3324rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3325PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3326 RTC_DCHECK(IsUnifiedPlan());
3327 for (auto transceiver : transceivers_) {
3328 if (transceiver->mid() == mid) {
3329 return transceiver;
3330 }
3331 }
3332 return nullptr;
3333}
3334
3335rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3336PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3337 RTC_DCHECK(IsUnifiedPlan());
3338 for (auto transceiver : transceivers_) {
3339 if (transceiver->internal()->mline_index() == mline_index) {
3340 return transceiver;
3341 }
3342 }
3343 return nullptr;
3344}
3345
3346rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3347PeerConnection::FindAvailableTransceiverToReceive(
3348 cricket::MediaType media_type) const {
3349 RTC_DCHECK(IsUnifiedPlan());
3350 // From JSEP section 5.10 (Applying a Remote Description):
3351 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3352 // the same type that were added to the PeerConnection by addTrack and are not
3353 // associated with any m= section and are not stopped, find the first such
3354 // RtpTransceiver.
3355 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003356 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003357 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3358 !transceiver->stopped()) {
3359 return transceiver;
3360 }
3361 }
3362 return nullptr;
3363}
3364
Steve Antoned10bd92017-12-05 10:52:59 -08003365const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3366 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3367 transceiver,
3368 const SessionDescriptionInterface* sdesc) const {
3369 RTC_DCHECK(transceiver);
3370 RTC_DCHECK(sdesc);
3371 if (IsUnifiedPlan()) {
3372 if (!transceiver->internal()->mid()) {
3373 // This transceiver is not associated with a media section yet.
3374 return nullptr;
3375 }
3376 return sdesc->description()->GetContentByName(
3377 *transceiver->internal()->mid());
3378 } else {
3379 // Plan B only allows at most one audio and one video section, so use the
3380 // first media section of that type.
3381 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003382 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003383 }
3384}
3385
deadbeef46c73892016-11-16 19:42:04 -08003386PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003387 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003388 return configuration_;
3389}
3390
deadbeef293e9262017-01-11 12:28:30 -08003391bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3392 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003393 RTC_DCHECK_RUN_ON(signaling_thread());
3394 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003395 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003396 if (IsClosed()) {
3397 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3398 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3399 }
3400
Qingsi Wanga2d60672018-04-11 16:57:45 -07003401 // According to JSEP, after setLocalDescription, changing the candidate pool
3402 // size is not allowed, and changing the set of ICE servers will not result
3403 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003404 if (local_description() && configuration.ice_candidate_pool_size !=
3405 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003406 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3407 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003408 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003409 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003410
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003411 if (local_description() &&
3412 configuration.use_media_transport != configuration_.use_media_transport) {
3413 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3414 "SetLocalDescription.";
3415 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3416 }
3417
3418 if (remote_description() &&
3419 configuration.use_media_transport != configuration_.use_media_transport) {
3420 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3421 "SetRemoteDescription.";
3422 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3423 }
3424
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003425 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003426 configuration.use_media_transport_for_data_channels !=
3427 configuration_.use_media_transport_for_data_channels) {
3428 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3429 "after calling SetLocalDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
3433 if (remote_description() &&
3434 configuration.use_media_transport_for_data_channels !=
3435 configuration_.use_media_transport_for_data_channels) {
3436 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3437 "after calling SetRemoteDescription.";
3438 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3439 }
3440
3441 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003442 configuration.crypto_options != configuration_.crypto_options) {
3443 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3444 "SetLocalDescription.";
3445 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3446 }
3447
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003448 if (local_description() && configuration.use_datagram_transport !=
3449 configuration_.use_datagram_transport) {
3450 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3451 "after calling SetLocalDescription.";
3452 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3453 }
3454
3455 if (remote_description() && configuration.use_datagram_transport !=
3456 configuration_.use_datagram_transport) {
3457 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3458 "after calling SetRemoteDescription.";
3459 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3460 }
3461
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003462 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003463 configuration.use_media_transport ||
3464 configuration.use_datagram_transport) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003465 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3466 << "Media transport requires MaxBundle policy.";
3467 }
3468
deadbeef293e9262017-01-11 12:28:30 -08003469 // The simplest (and most future-compatible) way to tell if the config was
3470 // modified in an invalid way is to copy each property we do support
3471 // modifying, then use operator==. There are far more properties we don't
3472 // support modifying than those we do, and more could be added.
3473 RTCConfiguration modified_config = configuration_;
3474 modified_config.servers = configuration.servers;
3475 modified_config.type = configuration.type;
3476 modified_config.ice_candidate_pool_size =
3477 configuration.ice_candidate_pool_size;
3478 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003479 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3480 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003481 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003482 modified_config.ice_check_interval_strong_connectivity =
3483 configuration.ice_check_interval_strong_connectivity;
3484 modified_config.ice_check_interval_weak_connectivity =
3485 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003486 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3487 modified_config.ice_unwritable_min_checks =
3488 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003489 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003490 modified_config.stun_candidate_keepalive_interval =
3491 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003492 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003493 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003494 modified_config.active_reset_srtp_params =
3495 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003496 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003497 modified_config.use_media_transport_for_data_channels =
3498 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003499 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003500 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003501 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3502 }
3503
Steve Anton038834f2017-07-14 15:59:59 -07003504 // Validate the modified configuration.
3505 RTCError validate_error = ValidateConfiguration(modified_config);
3506 if (!validate_error.ok()) {
3507 return SafeSetError(std::move(validate_error), error);
3508 }
3509
deadbeef293e9262017-01-11 12:28:30 -08003510 // Note that this isn't possible through chromium, since it's an unsigned
3511 // short in WebIDL.
3512 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003513 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003514 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3515 }
3516
3517 // Parse ICE servers before hopping to network thread.
3518 cricket::ServerAddresses stun_servers;
3519 std::vector<cricket::RelayServerConfig> turn_servers;
3520 RTCErrorType parse_error =
3521 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3522 if (parse_error != RTCErrorType::NONE) {
3523 return SafeSetError(parse_error, error);
3524 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003525 // Note if STUN or TURN servers were supplied.
3526 if (!stun_servers.empty()) {
3527 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3528 }
3529 if (!turn_servers.empty()) {
3530 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3531 }
deadbeef293e9262017-01-11 12:28:30 -08003532
3533 // In theory this shouldn't fail.
3534 if (!network_thread()->Invoke<bool>(
3535 RTC_FROM_HERE,
3536 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3537 stun_servers, turn_servers, modified_config.type,
3538 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003539 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003540 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003541 modified_config.stun_candidate_keepalive_interval,
3542 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003543 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003544 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3545 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003546
deadbeefd1a38b52016-12-10 13:15:33 -08003547 // As described in JSEP, calling setConfiguration with new ICE servers or
3548 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3549 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003550 if (modified_config.servers != configuration_.servers ||
3551 modified_config.type != configuration_.type ||
3552 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003553 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003554 }
skvladd1f5fda2017-02-03 16:54:05 -08003555
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003556 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003557 transport_controller_->SetMediaTransportSettings(
3558 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003559 modified_config.use_media_transport_for_data_channels,
3560 modified_config.use_datagram_transport);
skvladd1f5fda2017-02-03 16:54:05 -08003561
Zhi Huangb57e1692018-06-12 11:41:11 -07003562 if (configuration_.active_reset_srtp_params !=
3563 modified_config.active_reset_srtp_params) {
3564 transport_controller_->SetActiveResetSrtpParams(
3565 modified_config.active_reset_srtp_params);
3566 }
3567
deadbeef293e9262017-01-11 12:28:30 -08003568 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003569 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003570 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003571}
3572
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003573bool PeerConnection::AddIceCandidate(
3574 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003575 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003576 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003577 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003578 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003579 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003580 return false;
3581 }
Steve Antond25da372017-11-06 14:50:29 -08003582
3583 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003584 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003585 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003586 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003587 return false;
3588 }
3589
3590 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003591 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003592 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003593 return false;
3594 }
3595
3596 bool valid = false;
3597 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3598 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003599 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003600 return false;
3601 }
3602
3603 // Add this candidate to the remote session description.
3604 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003605 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003606 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003607 return false;
3608 }
3609
3610 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003611 bool result = UseCandidate(ice_candidate);
3612 if (result) {
3613 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003614 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3615 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3616 }
3617 if (ice_candidate->candidate().address().IsPrivateIP()) {
3618 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3619 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003620 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3621 } else {
3622 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3623 }
3624 return result;
Steve Antond25da372017-11-06 14:50:29 -08003625 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003626 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003627 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003628 return true;
3629 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003630}
3631
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003632bool PeerConnection::RemoveIceCandidates(
3633 const std::vector<cricket::Candidate>& candidates) {
3634 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003635 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003636 if (IsClosed()) {
3637 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3638 return false;
3639 }
3640
Steve Antond25da372017-11-06 14:50:29 -08003641 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003642 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3643 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003644 return false;
3645 }
3646
3647 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003648 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003649 return false;
3650 }
3651
3652 size_t number_removed =
3653 mutable_remote_description()->RemoveCandidates(candidates);
3654 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003655 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003656 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003657 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003658 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003659 }
3660
3661 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003662 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3663 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003664 RTC_LOG(LS_ERROR)
3665 << "RemoveIceCandidates: Error when removing remote candidates: "
3666 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003667 }
3668 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003669}
3670
Niels Möller0c4f7be2018-05-07 14:01:37 +02003671RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003672 if (!worker_thread()->IsCurrent()) {
3673 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003674 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003675 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003676 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003677
Niels Möller0c4f7be2018-05-07 14:01:37 +02003678 const bool has_min = bitrate.min_bitrate_bps.has_value();
3679 const bool has_start = bitrate.start_bitrate_bps.has_value();
3680 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003681 if (has_min && *bitrate.min_bitrate_bps < 0) {
3682 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3683 "min_bitrate_bps <= 0");
3684 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003685 if (has_start) {
3686 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003687 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003688 "start_bitrate_bps < min_bitrate_bps");
3689 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003690 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3691 "curent_bitrate_bps < 0");
3692 }
3693 }
3694 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003695 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003697 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003698 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3699 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3700 "max_bitrate_bps < min_bitrate_bps");
3701 } else if (*bitrate.max_bitrate_bps < 0) {
3702 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3703 "max_bitrate_bps < 0");
3704 }
3705 }
3706
zstein4b979802017-06-02 14:37:37 -07003707 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003708 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003709
3710 return RTCError::OK();
3711}
3712
Alex Narest78609d52017-10-20 10:37:47 +02003713void PeerConnection::SetBitrateAllocationStrategy(
3714 std::unique_ptr<rtc::BitrateAllocationStrategy>
3715 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003716 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003717 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3718 // move-capture values in lambdas.
3719 struct Task {
3720 PeerConnection* const pc;
3721 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3722 void operator()() {
3723 RTC_DCHECK_RUN_ON(pc->worker_thread());
3724 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3725 }
3726 };
3727 worker_thread()->Invoke<void>(
3728 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003729 return;
3730 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003731 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003732 RTC_DCHECK(call_.get());
3733 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3734}
3735
henrika5f6bf242017-11-01 11:06:56 +01003736void PeerConnection::SetAudioPlayout(bool playout) {
3737 if (!worker_thread()->IsCurrent()) {
3738 worker_thread()->Invoke<void>(
3739 RTC_FROM_HERE,
3740 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3741 return;
3742 }
3743 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003744 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003745 audio_state->SetPlayout(playout);
3746}
3747
3748void PeerConnection::SetAudioRecording(bool recording) {
3749 if (!worker_thread()->IsCurrent()) {
3750 worker_thread()->Invoke<void>(
3751 RTC_FROM_HERE,
3752 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3753 return;
3754 }
3755 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003756 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003757 audio_state->SetRecording(recording);
3758}
3759
Steve Anton8c0f7a72017-10-03 10:03:10 -07003760std::unique_ptr<rtc::SSLCertificate>
3761PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003762 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3763 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003764 return nullptr;
3765 }
Steve Antonf25303e2018-10-16 15:23:31 -07003766 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003767}
3768
Zhi Huang70b820f2018-01-27 14:16:15 -08003769std::unique_ptr<rtc::SSLCertChain>
3770PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003771 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003772 auto audio_transceiver = GetFirstAudioTransceiver();
3773 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003774 return nullptr;
3775 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003776 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003777 audio_transceiver->internal()->channel()->transport_name());
3778}
3779
3780rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3781PeerConnection::GetFirstAudioTransceiver() const {
3782 for (auto transceiver : transceivers_) {
3783 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3784 return transceiver;
3785 }
3786 }
3787 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003788}
3789
Bjorn Tereliusde939432017-11-20 17:38:14 +01003790bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3791 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003792 // TODO(eladalon): In C++14, this can be done with a lambda.
3793 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003794 bool operator()() {
3795 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3796 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003797 PeerConnection* const pc;
3798 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003799 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003800 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003801 return worker_thread()->Invoke<bool>(
3802 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003803}
3804
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003805bool PeerConnection::StartRtcEventLog(
3806 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003807 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3808 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3809 output_period_ms = 5000;
3810 }
3811 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003812}
3813
ivoc14d5dbe2016-07-04 07:06:55 -07003814void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003815 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003816 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3817}
3818
Harald Alvestrandad88c882018-11-28 16:47:46 +01003819rtc::scoped_refptr<DtlsTransportInterface>
3820PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003821 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003822 return transport_controller_->LookupDtlsTransportByMid(mid);
3823}
3824
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003825rtc::scoped_refptr<DtlsTransport>
3826PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003827 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003828 return transport_controller_->LookupDtlsTransportByMid(mid);
3829}
3830
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003831rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3832 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003833 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003834 return sctp_transport_;
3835}
3836
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003837const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003838 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003839 return pending_local_description_ ? pending_local_description_.get()
3840 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003841}
3842
3843const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003844 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003845 return pending_remote_description_ ? pending_remote_description_.get()
3846 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003847}
3848
deadbeeffe4a8a42016-12-20 17:56:17 -08003849const SessionDescriptionInterface* PeerConnection::current_local_description()
3850 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003851 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003852 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003853}
3854
3855const SessionDescriptionInterface* PeerConnection::current_remote_description()
3856 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003857 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003858 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003859}
3860
3861const SessionDescriptionInterface* PeerConnection::pending_local_description()
3862 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003863 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003864 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003865}
3866
3867const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3868 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003869 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003870 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003871}
3872
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003873void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003874 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003875 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003876 // Update stats here so that we have the most recent stats for tracks and
3877 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003878 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003879
Steve Anton75737c02017-11-06 10:37:17 -08003880 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003881 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003882
Mirko Bonadei739baf02019-01-27 17:29:42 +01003883 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003884 transceiver->Stop();
3885 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003886
3887 // Ensure that all asynchronous stats requests are completed before destroying
3888 // the transport controller below.
3889 if (stats_collector_) {
3890 stats_collector_->WaitForPendingRequest();
3891 }
3892
3893 // Don't destroy BaseChannels until after stats has been cleaned up so that
3894 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003895 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003896
Qingsi Wang93a84392018-01-30 17:13:09 -08003897 // The event log is used in the transport controller, which must be outlived
3898 // by the former. CreateOffer by the peer connection is implemented
3899 // asynchronously and if the peer connection is closed without resetting the
3900 // WebRTC session description factory, the session description factory would
3901 // call the transport controller.
3902 webrtc_session_desc_factory_.reset();
3903 transport_controller_.reset();
3904
deadbeef42a42632017-03-10 15:18:00 -08003905 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003906 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3907 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003908
Steve Anton978b8762017-09-29 12:15:02 -07003909 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003910 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003911 call_.reset();
3912 // The event log must outlive call (and any other object that uses it).
3913 event_log_.reset();
3914 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003915 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003916 // The .h file says that observer can be discarded after close() returns.
3917 // Make sure this is true.
3918 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003919}
3920
Steve Antonad182762018-09-05 20:22:40 +00003921void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003922 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003923 switch (msg->message_id) {
3924 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3925 SetSessionDescriptionMsg* param =
3926 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3927 param->observer->OnSuccess();
3928 delete param;
3929 break;
3930 }
3931 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3932 SetSessionDescriptionMsg* param =
3933 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3934 param->observer->OnFailure(std::move(param->error));
3935 delete param;
3936 break;
3937 }
3938 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3939 CreateSessionDescriptionMsg* param =
3940 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3941 param->observer->OnFailure(std::move(param->error));
3942 delete param;
3943 break;
3944 }
3945 case MSG_GETSTATS: {
3946 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3947 StatsReports reports;
3948 stats_->GetStats(param->track, &reports);
3949 param->observer->OnComplete(reports);
3950 delete param;
3951 break;
3952 }
3953 case MSG_FREE_DATACHANNELS: {
3954 sctp_data_channels_to_free_.clear();
3955 break;
3956 }
3957 case MSG_REPORT_USAGE_PATTERN: {
3958 ReportUsagePattern();
3959 break;
3960 }
3961 default:
3962 RTC_NOTREACHED() << "Not implemented";
3963 break;
3964 }
3965}
3966
Steve Antonafb0bb72018-02-20 11:35:37 -08003967cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3968 RTC_DCHECK(!IsUnifiedPlan());
3969 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3970 GetAudioTransceiver()->internal()->channel());
3971 if (voice_channel) {
3972 return voice_channel->media_channel();
3973 } else {
3974 return nullptr;
3975 }
3976}
3977
3978cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3979 RTC_DCHECK(!IsUnifiedPlan());
3980 auto* video_channel = static_cast<cricket::VideoChannel*>(
3981 GetVideoTransceiver()->internal()->channel());
3982 if (video_channel) {
3983 return video_channel->media_channel();
3984 } else {
3985 return nullptr;
3986 }
3987}
3988
Steve Anton4171afb2017-11-20 10:20:22 -08003989void PeerConnection::CreateAudioReceiver(
3990 MediaStreamInterface* stream,
3991 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003992 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3993 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003994 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3995 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003996 auto* audio_receiver = new AudioRtpReceiver(
3997 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003998 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003999 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4000 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4001 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004002 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004003 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004004 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004005}
4006
Steve Anton4171afb2017-11-20 10:20:22 -08004007void PeerConnection::CreateVideoReceiver(
4008 MediaStreamInterface* stream,
4009 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004010 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4011 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004012 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4013 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004014 auto* video_receiver = new VideoRtpReceiver(
4015 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004016 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004017 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4018 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4019 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004020 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004021 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004022 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004023}
4024
deadbeef70ab1a12015-09-28 16:53:55 -07004025// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4026// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004027rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004028 const RtpSenderInfo& remote_sender_info) {
4029 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4030 if (!receiver) {
4031 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4032 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004033 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004034 }
Steve Anton4171afb2017-11-20 10:20:22 -08004035 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4036 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4037 } else {
4038 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4039 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004040 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004041}
4042
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004043void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4044 MediaStreamInterface* stream) {
4045 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004046 RTC_DCHECK(track);
4047 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004048 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004049 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004050 // We already have a sender for this track, so just change the stream_id
4051 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004052 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004053 return;
4054 }
4055
4056 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004057 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004058 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004059 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004060 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004061 // If the sender has already been configured in SDP, we call SetSsrc,
4062 // which will connect the sender to the underlying transport. This can
4063 // occur if a local session description that contains the ID of the sender
4064 // is set before AddStream is called. It can also occur if the local
4065 // session description is not changed and RemoveStream is called, and
4066 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004067 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004068 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004069 if (sender_info) {
4070 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004071 }
4072}
4073
4074// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4075// indefinitely, when we have unified plan SDP.
4076void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4077 MediaStreamInterface* stream) {
4078 RTC_DCHECK(!IsClosed());
4079 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004080 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004081 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4082 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004083 return;
4084 }
Steve Anton4171afb2017-11-20 10:20:22 -08004085 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004086}
4087
4088void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4089 MediaStreamInterface* stream) {
4090 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004091 RTC_DCHECK(track);
4092 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004093 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004094 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004095 // We already have a sender for this track, so just change the stream_id
4096 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004097 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004098 return;
4099 }
4100
4101 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004102 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004103 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004104 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004105 GetVideoTransceiver()->internal()->AddSender(new_sender);
4106 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004107 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004108 if (sender_info) {
4109 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004110 }
4111}
4112
4113void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4114 MediaStreamInterface* stream) {
4115 RTC_DCHECK(!IsClosed());
4116 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004117 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004118 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4119 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004120 return;
4121 }
Steve Anton4171afb2017-11-20 10:20:22 -08004122 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004123}
4124
Steve Antonba818672017-11-06 10:21:57 -08004125void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004126 if (ice_connection_state_ == new_state) {
4127 return;
4128 }
4129
deadbeefcbecd352015-09-23 11:50:27 -07004130 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004131 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004132 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004133 return;
4134 }
Steve Antonba818672017-11-06 10:21:57 -08004135
Mirko Bonadei675513b2017-11-09 11:09:25 +01004136 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4137 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004138 RTC_DCHECK(ice_connection_state_ !=
4139 PeerConnectionInterface::kIceConnectionClosed);
4140
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004141 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004142 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004143}
4144
Alex Loiko9289eda2018-11-23 16:18:59 +00004145void PeerConnection::SetStandardizedIceConnectionState(
4146 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004147 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004148 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004149 }
4150
4151 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004152 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004153 }
4154
4155 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4156 << standardized_ice_connection_state_ << " => " << new_state;
4157
Alex Loiko9289eda2018-11-23 16:18:59 +00004158 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004159 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004160}
4161
Jonas Olsson635474e2018-10-18 15:58:17 +02004162void PeerConnection::SetConnectionState(
4163 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004164 if (connection_state_ == new_state)
4165 return;
4166 if (IsClosed())
4167 return;
4168 connection_state_ = new_state;
4169 Observer()->OnConnectionChange(new_state);
4170}
4171
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004172void PeerConnection::OnIceGatheringChange(
4173 PeerConnectionInterface::IceGatheringState new_state) {
4174 if (IsClosed()) {
4175 return;
4176 }
4177 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004178 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004179}
4180
jbauch81bf7b02017-03-25 08:31:12 -07004181void PeerConnection::OnIceCandidate(
4182 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004183 if (IsClosed()) {
4184 return;
4185 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004186 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004187 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4188 candidate->candidate().address().IsPrivateIP()) {
4189 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4190 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004191 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4192 candidate->candidate().address().IsUnresolvedIP()) {
4193 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4194 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004195 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004196}
4197
Eldar Relloda13ea22019-06-01 12:23:43 +03004198void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4199 const std::string& url,
4200 int error_code,
4201 const std::string& error_text) {
4202 if (IsClosed()) {
4203 return;
4204 }
4205 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4206}
4207
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004208void PeerConnection::OnIceCandidatesRemoved(
4209 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004210 if (IsClosed()) {
4211 return;
4212 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004213 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004214}
4215
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004216void PeerConnection::ChangeSignalingState(
4217 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004218 if (signaling_state_ == signaling_state) {
4219 return;
4220 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004221 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4222 << GetSignalingStateString(signaling_state_)
4223 << " New state: "
4224 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004225 signaling_state_ = signaling_state;
4226 if (signaling_state == kClosed) {
4227 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004228 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004229 standardized_ice_connection_state_ =
4230 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004231 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4232 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004233 if (ice_gathering_state_ != kIceGatheringComplete) {
4234 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004235 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004236 }
4237 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004238 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004239}
4240
deadbeefeb459812015-12-15 19:24:43 -08004241void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4242 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004243 if (IsClosed()) {
4244 return;
4245 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004246 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004247 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004248}
4249
deadbeefeb459812015-12-15 19:24:43 -08004250void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4251 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004252 if (IsClosed()) {
4253 return;
4254 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004255 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004256 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004257}
4258
4259void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4260 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004261 if (IsClosed()) {
4262 return;
4263 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004264 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004265 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004266}
4267
4268void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4269 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004270 if (IsClosed()) {
4271 return;
4272 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004273 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004274 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004275}
4276
Henrik Boström31638672017-11-23 17:48:32 +01004277void PeerConnection::PostSetSessionDescriptionSuccess(
4278 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004279 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4280 signaling_thread()->Post(RTC_FROM_HERE, this,
4281 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004282}
4283
deadbeefab9b2d12015-10-14 11:33:11 -07004284void PeerConnection::PostSetSessionDescriptionFailure(
4285 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004286 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004287 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004288 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4289 msg->error = std::move(error);
4290 signaling_thread()->Post(RTC_FROM_HERE, this,
4291 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004292}
4293
4294void PeerConnection::PostCreateSessionDescriptionFailure(
4295 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004296 RTCError error) {
4297 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004298 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4299 msg->error = std::move(error);
4300 signaling_thread()->Post(RTC_FROM_HERE, this,
4301 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004302}
4303
zhihuang1c378ed2017-08-17 14:10:50 -07004304void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004305 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004306 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004307 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004308
Steve Antondcc3c022017-12-22 16:02:54 -08004309 if (IsUnifiedPlan()) {
4310 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4311 } else {
4312 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4313 }
4314
Steve Antonfa2260d2017-12-28 16:38:23 -08004315 // Intentionally unset the data channel type for RTP data channel with the
4316 // second condition. Otherwise the RTP data channels would be successfully
4317 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4318 // when building with chromium. We want to leave RTP data channels broken, so
4319 // people won't try to use them.
4320 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4321 session_options->data_channel_type = data_channel_type();
4322 }
4323
Steve Antondcc3c022017-12-22 16:02:54 -08004324 // Apply ICE restart flag and renomination flag.
4325 for (auto& options : session_options->media_description_options) {
4326 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4327 options.transport_options.enable_ice_renomination =
4328 configuration_.enable_ice_renomination;
4329 }
4330
4331 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004332 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004333 session_options->pooled_ice_credentials =
4334 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4335 RTC_FROM_HERE,
4336 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4337 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004338 session_options->offer_extmap_allow_mixed =
4339 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004340
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004341 if (configuration_.use_media_transport ||
4342 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004343 session_options->media_transport_settings =
4344 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4345 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004346
4347 // If datagram transport is in use, add opaque transport parameters.
4348 if (configuration_.use_datagram_transport) {
4349 for (auto& options : session_options->media_description_options) {
4350 options.transport_options.opaque_parameters =
4351 transport_controller_->GetTransportParameters(options.mid);
4352 }
4353 }
4354
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004355 // Allow fallback for using obsolete SCTP syntax.
4356 // Note that the default in |session_options| is true, while
4357 // the default in |options| is false.
4358 session_options->use_obsolete_sctp_sdp =
4359 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004360}
4361
4362void PeerConnection::GetOptionsForPlanBOffer(
4363 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4364 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004365 // Figure out transceiver directional preferences.
4366 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4367 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4368
4369 // By default, generate sendrecv/recvonly m= sections.
4370 bool recv_audio = true;
4371 bool recv_video = true;
4372
4373 // By default, only offer a new m= section if we have media to send with it.
4374 bool offer_new_audio_description = send_audio;
4375 bool offer_new_video_description = send_video;
4376 bool offer_new_data_description = HasDataChannels();
4377
4378 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004379 if (offer_answer_options.offer_to_receive_audio !=
4380 RTCOfferAnswerOptions::kUndefined) {
4381 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004382 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004383 offer_new_audio_description ||
4384 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004385 }
Steve Antondcc3c022017-12-22 16:02:54 -08004386 if (offer_answer_options.offer_to_receive_video !=
4387 RTCOfferAnswerOptions::kUndefined) {
4388 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004389 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004390 offer_new_video_description ||
4391 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004392 }
4393
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004394 absl::optional<size_t> audio_index;
4395 absl::optional<size_t> video_index;
4396 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004397 // If a current description exists, generate m= sections in the same order,
4398 // using the first audio/video/data section that appears and rejecting
4399 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004400 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004401 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004402 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004403 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4404 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4405 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004406 }
4407
zhihuang1c378ed2017-08-17 14:10:50 -07004408 // Add audio/video/data m= sections to the end if needed.
4409 if (!audio_index && offer_new_audio_description) {
4410 session_options->media_description_options.push_back(
4411 cricket::MediaDescriptionOptions(
4412 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004413 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4414 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004415 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004416 }
zhihuang1c378ed2017-08-17 14:10:50 -07004417 if (!video_index && offer_new_video_description) {
4418 session_options->media_description_options.push_back(
4419 cricket::MediaDescriptionOptions(
4420 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004421 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4422 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004423 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004424 }
zhihuang1c378ed2017-08-17 14:10:50 -07004425 if (!data_index && offer_new_data_description) {
4426 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004427 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004428 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004429 }
4430
4431 cricket::MediaDescriptionOptions* audio_media_description_options =
4432 !audio_index ? nullptr
4433 : &session_options->media_description_options[*audio_index];
4434 cricket::MediaDescriptionOptions* video_media_description_options =
4435 !video_index ? nullptr
4436 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004437
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004438 AddPlanBRtpSenderOptions(GetSendersInternal(),
4439 audio_media_description_options,
4440 video_media_description_options,
4441 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004442}
4443
Steve Antondcc3c022017-12-22 16:02:54 -08004444static cricket::MediaDescriptionOptions
4445GetMediaDescriptionOptionsForTransceiver(
4446 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4447 transceiver,
4448 const std::string& mid) {
4449 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004450 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004451 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004452 media_description_options.codec_preferences =
4453 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004454 // This behavior is specified in JSEP. The gist is that:
4455 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4456 // sendrecv.
4457 // 2. If the MSID is included, then it must be included in any subsequent
4458 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004459 if (transceiver->stopped() ||
4460 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4461 !transceiver->internal()->has_ever_been_used_to_send())) {
4462 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004463 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004464
4465 cricket::SenderOptions sender_options;
4466 sender_options.track_id = transceiver->sender()->id();
4467 sender_options.stream_ids = transceiver->sender()->stream_ids();
4468
4469 // The following sets up RIDs and Simulcast.
4470 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004471 RtpParameters send_parameters =
4472 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004473 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4474 send_parameters.encodings.end(),
4475 [](const RtpEncodingParameters& encoding) {
4476 return !encoding.rid.empty();
4477 });
4478
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004479 std::vector<RidDescription> send_rids;
4480 SimulcastLayerList send_layers;
4481 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4482 if (encoding.rid.empty()) {
4483 continue;
4484 }
4485 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4486 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4487 }
4488
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004489 if (has_rids) {
4490 sender_options.rids = send_rids;
4491 }
4492
4493 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004494 // When RIDs are configured, we must set num_sim_layers to 0 to.
4495 // Otherwise, num_sim_layers must be 1 because either there is no
4496 // simulcast, or simulcast is acheived by munging the SDP.
4497 sender_options.num_sim_layers = has_rids ? 0 : 1;
4498 media_description_options.sender_options.push_back(sender_options);
4499
Steve Antondcc3c022017-12-22 16:02:54 -08004500 return media_description_options;
4501}
4502
Steve Anton5c72e712018-12-10 14:25:30 -08004503// Returns the ContentInfo at mline index |i|, or null if none exists.
4504static const ContentInfo* GetContentByIndex(
4505 const SessionDescriptionInterface* sdesc,
4506 size_t i) {
4507 if (!sdesc) {
4508 return nullptr;
4509 }
4510 const ContentInfos& contents = sdesc->description()->contents();
4511 return (i < contents.size() ? &contents[i] : nullptr);
4512}
4513
Steve Antondcc3c022017-12-22 16:02:54 -08004514void PeerConnection::GetOptionsForUnifiedPlanOffer(
4515 const RTCOfferAnswerOptions& offer_answer_options,
4516 cricket::MediaSessionOptions* session_options) {
4517 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4518 // Offers) and 5.2.2 (Subsequent Offers).
4519 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004520 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004521 const ContentInfos& local_contents =
4522 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004523 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004524 const ContentInfos& remote_contents =
4525 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004526 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004527 // The mline indices that can be recycled. New transceivers should reuse these
4528 // slots first.
4529 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004530 // First, go through each media section that exists in either the local or
4531 // remote description and generate a media section in this offer for the
4532 // associated transceiver. If a media section can be recycled, generate a
4533 // default, rejected media section here that can be later overwritten.
4534 for (size_t i = 0;
4535 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4536 // Either |local_content| or |remote_content| is non-null.
4537 const ContentInfo* local_content =
4538 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004539 const ContentInfo* current_local_content =
4540 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004541 const ContentInfo* remote_content =
4542 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004543 const ContentInfo* current_remote_content =
4544 GetContentByIndex(current_remote_description(), i);
4545 bool had_been_rejected =
4546 (current_local_content && current_local_content->rejected) ||
4547 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004548 const std::string& mid =
4549 (local_content ? local_content->name : remote_content->name);
4550 cricket::MediaType media_type =
4551 (local_content ? local_content->media_description()->type()
4552 : remote_content->media_description()->type());
4553 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4554 media_type == cricket::MEDIA_TYPE_VIDEO) {
4555 auto transceiver = GetAssociatedTransceiver(mid);
4556 RTC_CHECK(transceiver);
4557 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004558 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004559 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004560 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004561 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4562 RtpTransceiverDirection::kInactive,
4563 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004564 recycleable_mline_indices.push(i);
4565 } else {
4566 session_options->media_description_options.push_back(
4567 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4568 // CreateOffer shouldn't really cause any state changes in
4569 // PeerConnection, but we need a way to match new transceivers to new
4570 // media sections in SetLocalDescription and JSEP specifies this is done
4571 // by recording the index of the media section generated for the
4572 // transceiver in the offer.
4573 transceiver->internal()->set_mline_index(i);
4574 }
4575 } else {
4576 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004577 RTC_CHECK(GetDataMid());
4578 if (had_been_rejected || mid != *GetDataMid()) {
4579 session_options->media_description_options.push_back(
4580 GetMediaDescriptionOptionsForRejectedData(mid));
4581 } else {
4582 session_options->media_description_options.push_back(
4583 GetMediaDescriptionOptionsForActiveData(mid));
4584 }
Steve Antondcc3c022017-12-22 16:02:54 -08004585 }
4586 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004587
Steve Antondcc3c022017-12-22 16:02:54 -08004588 // Next, look for transceivers that are newly added (that is, are not stopped
4589 // and not associated). Reuse media sections marked as recyclable first,
4590 // otherwise append to the end of the offer. New media sections should be
4591 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004592 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004593 if (transceiver->mid() || transceiver->stopped()) {
4594 continue;
4595 }
4596 size_t mline_index;
4597 if (!recycleable_mline_indices.empty()) {
4598 mline_index = recycleable_mline_indices.front();
4599 recycleable_mline_indices.pop();
4600 session_options->media_description_options[mline_index] =
4601 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004602 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004603 } else {
4604 mline_index = session_options->media_description_options.size();
4605 session_options->media_description_options.push_back(
4606 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004607 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004608 }
4609 // See comment above for why CreateOffer changes the transceiver's state.
4610 transceiver->internal()->set_mline_index(mline_index);
4611 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004612 // Lastly, add a m-section if we have local data channels and an m section
4613 // does not already exist.
4614 if (!GetDataMid() && HasDataChannels()) {
4615 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004616 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004617 }
Steve Antondcc3c022017-12-22 16:02:54 -08004618}
4619
4620void PeerConnection::GetOptionsForAnswer(
4621 const RTCOfferAnswerOptions& offer_answer_options,
4622 cricket::MediaSessionOptions* session_options) {
4623 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4624
4625 if (IsUnifiedPlan()) {
4626 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4627 } else {
4628 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4629 }
4630
Steve Antonfa2260d2017-12-28 16:38:23 -08004631 // Intentionally unset the data channel type for RTP data channel. Otherwise
4632 // the RTP data channels would be successfully negotiated by default and the
4633 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4634 // We want to leave RTP data channels broken, so people won't try to use them.
4635 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4636 session_options->data_channel_type = data_channel_type();
4637 }
4638
Steve Antondcc3c022017-12-22 16:02:54 -08004639 // Apply ICE renomination flag.
4640 for (auto& options : session_options->media_description_options) {
4641 options.transport_options.enable_ice_renomination =
4642 configuration_.enable_ice_renomination;
4643 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004644
4645 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004646 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004647 session_options->pooled_ice_credentials =
4648 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4649 RTC_FROM_HERE,
4650 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4651 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004652
4653 // If datagram transport is in use, add opaque transport parameters.
4654 if (configuration_.use_datagram_transport) {
4655 for (auto& options : session_options->media_description_options) {
4656 options.transport_options.opaque_parameters =
4657 transport_controller_->GetTransportParameters(options.mid);
4658 }
4659 }
deadbeefab9b2d12015-10-14 11:33:11 -07004660}
4661
Steve Antondcc3c022017-12-22 16:02:54 -08004662void PeerConnection::GetOptionsForPlanBAnswer(
4663 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004664 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004665 // Figure out transceiver directional preferences.
4666 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4667 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4668
4669 // By default, generate sendrecv/recvonly m= sections. The direction is also
4670 // restricted by the direction in the offer.
4671 bool recv_audio = true;
4672 bool recv_video = true;
4673
4674 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004675 if (offer_answer_options.offer_to_receive_audio !=
4676 RTCOfferAnswerOptions::kUndefined) {
4677 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004678 }
Steve Antondcc3c022017-12-22 16:02:54 -08004679 if (offer_answer_options.offer_to_receive_video !=
4680 RTCOfferAnswerOptions::kUndefined) {
4681 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004682 }
4683
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004684 absl::optional<size_t> audio_index;
4685 absl::optional<size_t> video_index;
4686 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004687
4688 // Generate m= sections that match those in the offer.
4689 // Note that mediasession.cc will handle intersection our preferred
4690 // direction with the offered direction.
4691 GenerateMediaDescriptionOptions(
4692 remote_description(),
4693 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4694 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4695 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004696
4697 cricket::MediaDescriptionOptions* audio_media_description_options =
4698 !audio_index ? nullptr
4699 : &session_options->media_description_options[*audio_index];
4700 cricket::MediaDescriptionOptions* video_media_description_options =
4701 !video_index ? nullptr
4702 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004703
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004704 AddPlanBRtpSenderOptions(GetSendersInternal(),
4705 audio_media_description_options,
4706 video_media_description_options,
4707 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004708}
zhihuangaf388472016-11-02 16:49:48 -07004709
Steve Antondcc3c022017-12-22 16:02:54 -08004710void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4711 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4712 cricket::MediaSessionOptions* session_options) {
4713 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4714 // Answers) and 5.3.2 (Subsequent Answers).
4715 RTC_DCHECK(remote_description());
4716 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4717 for (const ContentInfo& content :
4718 remote_description()->description()->contents()) {
4719 cricket::MediaType media_type = content.media_description()->type();
4720 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4721 media_type == cricket::MEDIA_TYPE_VIDEO) {
4722 auto transceiver = GetAssociatedTransceiver(content.name);
4723 RTC_CHECK(transceiver);
4724 session_options->media_description_options.push_back(
4725 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4726 } else {
4727 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004728 // Reject all data sections if data channels are disabled.
4729 // Reject a data section if it has already been rejected.
4730 // Reject all data sections except for the first one.
4731 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4732 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004733 session_options->media_description_options.push_back(
4734 GetMediaDescriptionOptionsForRejectedData(content.name));
4735 } else {
4736 session_options->media_description_options.push_back(
4737 GetMediaDescriptionOptionsForActiveData(content.name));
4738 }
Steve Antondcc3c022017-12-22 16:02:54 -08004739 }
4740 }
htaa2a49d92016-03-04 02:51:39 -08004741}
4742
zhihuang1c378ed2017-08-17 14:10:50 -07004743void PeerConnection::GenerateMediaDescriptionOptions(
4744 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004745 RtpTransceiverDirection audio_direction,
4746 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004747 absl::optional<size_t>* audio_index,
4748 absl::optional<size_t>* video_index,
4749 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004750 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004751 for (const cricket::ContentInfo& content :
4752 session_desc->description()->contents()) {
4753 if (IsAudioContent(&content)) {
4754 // If we already have an audio m= section, reject this extra one.
4755 if (*audio_index) {
4756 session_options->media_description_options.push_back(
4757 cricket::MediaDescriptionOptions(
4758 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004759 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004760 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004761 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004762 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004763 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4764 content.name, audio_direction,
4765 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004766 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004767 }
4768 } else if (IsVideoContent(&content)) {
4769 // If we already have an video m= section, reject this extra one.
4770 if (*video_index) {
4771 session_options->media_description_options.push_back(
4772 cricket::MediaDescriptionOptions(
4773 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004774 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004775 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004776 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004777 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004778 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4779 content.name, video_direction,
4780 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004781 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004782 }
4783 } else {
4784 RTC_DCHECK(IsDataContent(&content));
4785 // If we already have an data m= section, reject this extra one.
4786 if (*data_index) {
4787 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004788 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004789 } else {
4790 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004791 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004792 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004793 }
4794 }
htaa2a49d92016-03-04 02:51:39 -08004795 }
deadbeefab9b2d12015-10-14 11:33:11 -07004796}
4797
Steve Antonfa2260d2017-12-28 16:38:23 -08004798cricket::MediaDescriptionOptions
4799PeerConnection::GetMediaDescriptionOptionsForActiveData(
4800 const std::string& mid) const {
4801 // Direction for data sections is meaningless, but legacy endpoints might
4802 // expect sendrecv.
4803 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4804 RtpTransceiverDirection::kSendRecv,
4805 /*stopped=*/false);
4806 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4807 return options;
4808}
4809
4810cricket::MediaDescriptionOptions
4811PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4812 const std::string& mid) const {
4813 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4814 RtpTransceiverDirection::kInactive,
4815 /*stopped=*/true);
4816 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4817 return options;
4818}
4819
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004820absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004821 switch (data_channel_type_) {
4822 case cricket::DCT_RTP:
4823 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004824 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004825 }
4826 return rtp_data_channel_->content_name();
4827 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004828 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004829 case cricket::DCT_MEDIA_TRANSPORT:
4830 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004831 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004832 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004833 }
4834}
4835
Steve Anton4171afb2017-11-20 10:20:22 -08004836void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4837 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4838 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004839 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004840}
4841
Steve Anton4171afb2017-11-20 10:20:22 -08004842void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004843 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004844 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004845 cricket::MediaType media_type,
4846 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004847 RTC_DCHECK(!IsUnifiedPlan());
4848
Steve Anton4171afb2017-11-20 10:20:22 -08004849 std::vector<RtpSenderInfo>* current_senders =
4850 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004851
Steve Anton4171afb2017-11-20 10:20:22 -08004852 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004853 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004854 for (auto sender_it = current_senders->begin();
4855 sender_it != current_senders->end();
4856 /* incremented manually */) {
4857 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004858 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004859 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004860 std::string params_stream_id;
4861 if (params) {
4862 params_stream_id =
4863 (!params->first_stream_id().empty() ? params->first_stream_id()
4864 : kDefaultStreamId);
4865 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004866 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004867 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004868 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004869 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004870 sender_exists) {
4871 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004872 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004873 OnRemoteSenderRemoved(info, media_type);
4874 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004875 }
4876 }
4877
Steve Anton4171afb2017-11-20 10:20:22 -08004878 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004879 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004880 if (!params.has_ssrcs()) {
4881 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4882 // sender, this means it is coming from a Unified Plan endpoint,so we just
4883 // create a default.
4884 default_sender_needed = true;
4885 break;
4886 }
4887
Seth Hampson845e8782018-03-02 11:34:10 -08004888 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004889 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004890 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4891 // not supported in Plan B, we just take the first here and create the
4892 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004893 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004894 (!params.first_stream_id().empty() ? params.first_stream_id()
4895 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004896 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004897 uint32_t ssrc = params.first_ssrc();
4898
4899 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004900 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004901 if (!stream) {
4902 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004903 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004904 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004905 remote_streams_->AddStream(stream);
4906 new_streams->AddStream(stream);
4907 }
4908
Steve Anton4171afb2017-11-20 10:20:22 -08004909 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004910 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004911 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004912 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004913 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004914 }
4915 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004916
Steve Anton4171afb2017-11-20 10:20:22 -08004917 // Add default sender if necessary.
4918 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004919 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004920 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004921 if (!default_stream) {
4922 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004923 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004924 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004925 remote_streams_->AddStream(default_stream);
4926 new_streams->AddStream(default_stream);
4927 }
Steve Anton4171afb2017-11-20 10:20:22 -08004928 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4929 ? kDefaultAudioSenderId
4930 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004931 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004932 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004933 if (!default_sender_info) {
4934 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004935 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004936 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004937 }
4938 }
deadbeefab9b2d12015-10-14 11:33:11 -07004939}
4940
Steve Anton4171afb2017-11-20 10:20:22 -08004941void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4942 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004943 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4944 << " receiver for track_id=" << sender_info.sender_id
4945 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004946
Steve Anton3d954a62018-04-02 11:27:23 -07004947 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004948 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004949 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004950 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004951 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004952 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004953 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004954 }
4955}
4956
Steve Anton4171afb2017-11-20 10:20:22 -08004957void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4958 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004959 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4960 << " receiver for track_id=" << sender_info.sender_id
4961 << " and stream_id=" << sender_info.stream_id;
4962
Seth Hampson845e8782018-03-02 11:34:10 -08004963 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004964
Henrik Boström933d8b02017-10-10 10:05:16 -07004965 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004966 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004967 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4968 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004969 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004970 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004971 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004972 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004973 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004974 }
4975 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004976 // Stopping or destroying a VideoRtpReceiver will end the
4977 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004978 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004979 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004980 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004981 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004982 // There's no guarantee the track is still available, e.g. the track may
4983 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004984 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004985 }
4986 } else {
nisseede5da42017-01-12 05:15:36 -08004987 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004988 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004989 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004990 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004991 }
deadbeefab9b2d12015-10-14 11:33:11 -07004992}
4993
4994void PeerConnection::UpdateEndedRemoteMediaStreams() {
4995 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4996 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4997 MediaStreamInterface* stream = remote_streams_->at(i);
4998 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4999 streams_to_remove.push_back(stream);
5000 }
5001 }
5002
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005003 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005004 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005005 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005006 }
5007}
5008
Steve Anton4171afb2017-11-20 10:20:22 -08005009void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005010 const std::vector<cricket::StreamParams>& streams,
5011 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005012 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005013
Seth Hampson845e8782018-03-02 11:34:10 -08005014 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005015 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005016 for (auto sender_it = current_senders->begin();
5017 sender_it != current_senders->end();
5018 /* incremented manually */) {
5019 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005020 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005021 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5022 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005023 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005024 OnLocalSenderRemoved(info, media_type);
5025 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005026 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005027 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005028 }
5029 }
5030
Steve Anton4171afb2017-11-20 10:20:22 -08005031 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005032 for (const cricket::StreamParams& params : streams) {
5033 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005034 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005035 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005036 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005037 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005038 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005039 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005040 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005041 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005042 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005043 }
5044 }
5045}
5046
Steve Anton4171afb2017-11-20 10:20:22 -08005047void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5048 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005049 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005050 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005051 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005052 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5053 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005054 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005055 return;
5056 }
5057
deadbeeffac06552015-11-25 11:26:01 -08005058 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005059 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005060 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005061 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005062 }
deadbeeffac06552015-11-25 11:26:01 -08005063
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005064 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005065 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005066}
5067
Steve Anton4171afb2017-11-20 10:20:22 -08005068void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5069 cricket::MediaType media_type) {
5070 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005071 if (!sender) {
5072 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005073 // SessionDescriptions has been renegotiated.
5074 return;
5075 }
deadbeeffac06552015-11-25 11:26:01 -08005076
5077 // A sender has been removed from the SessionDescription but it's still
5078 // associated with the PeerConnection. This only occurs if the SDP doesn't
5079 // match with the calls to CreateSender, AddStream and RemoveStream.
5080 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005081 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005082 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005083 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005084 }
deadbeeffac06552015-11-25 11:26:01 -08005085
Steve Anton4171afb2017-11-20 10:20:22 -08005086 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005087}
5088
5089void PeerConnection::UpdateLocalRtpDataChannels(
5090 const cricket::StreamParamsVec& streams) {
5091 std::vector<std::string> existing_channels;
5092
5093 // Find new and active data channels.
5094 for (const cricket::StreamParams& params : streams) {
5095 // |it->sync_label| is actually the data channel label. The reason is that
5096 // we use the same naming of data channels as we do for
5097 // MediaStreams and Tracks.
5098 // For MediaStreams, the sync_label is the MediaStream label and the
5099 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005100 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005101 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005102 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005103 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005104 continue;
5105 }
5106 // Set the SSRC the data channel should use for sending.
5107 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5108 existing_channels.push_back(data_channel_it->first);
5109 }
5110
5111 UpdateClosingRtpDataChannels(existing_channels, true);
5112}
5113
5114void PeerConnection::UpdateRemoteRtpDataChannels(
5115 const cricket::StreamParamsVec& streams) {
5116 std::vector<std::string> existing_channels;
5117
5118 // Find new and active data channels.
5119 for (const cricket::StreamParams& params : streams) {
5120 // The data channel label is either the mslabel or the SSRC if the mslabel
5121 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005122 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005123 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005124 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005125 auto data_channel_it = rtp_data_channels_.find(label);
5126 if (data_channel_it == rtp_data_channels_.end()) {
5127 // This is a new data channel.
5128 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5129 } else {
5130 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5131 }
5132 existing_channels.push_back(label);
5133 }
5134
5135 UpdateClosingRtpDataChannels(existing_channels, false);
5136}
5137
5138void PeerConnection::UpdateClosingRtpDataChannels(
5139 const std::vector<std::string>& active_channels,
5140 bool is_local_update) {
5141 auto it = rtp_data_channels_.begin();
5142 while (it != rtp_data_channels_.end()) {
5143 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005144 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005145 ++it;
5146 continue;
5147 }
5148
5149 if (is_local_update) {
5150 data_channel->SetSendSsrc(0);
5151 } else {
5152 data_channel->RemotePeerRequestClose();
5153 }
5154
5155 if (data_channel->state() == DataChannel::kClosed) {
5156 rtp_data_channels_.erase(it);
5157 it = rtp_data_channels_.begin();
5158 } else {
5159 ++it;
5160 }
5161 }
5162}
5163
5164void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5165 uint32_t remote_ssrc) {
5166 rtc::scoped_refptr<DataChannel> channel(
5167 InternalCreateDataChannel(label, nullptr));
5168 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005169 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005170 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005171 return;
5172 }
5173 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005174 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5175 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005176 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005177}
5178
5179rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5180 const std::string& label,
5181 const InternalDataChannelInit* config) {
5182 if (IsClosed()) {
5183 return nullptr;
5184 }
Steve Anton75737c02017-11-06 10:37:17 -08005185 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005186 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005187 << "InternalCreateDataChannel: Data is not supported in this call.";
5188 return nullptr;
5189 }
5190 InternalDataChannelInit new_config =
5191 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005192 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005193 if (new_config.id < 0) {
5194 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005195 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005196 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005197 RTC_LOG(LS_ERROR)
5198 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005199 return nullptr;
5200 }
5201 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005202 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005203 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005204 return nullptr;
5205 }
5206 }
5207
Steve Anton75737c02017-11-06 10:37:17 -08005208 rtc::scoped_refptr<DataChannel> channel(
5209 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005210 if (!channel) {
5211 sid_allocator_.ReleaseSid(new_config.id);
5212 return nullptr;
5213 }
5214
5215 if (channel->data_channel_type() == cricket::DCT_RTP) {
5216 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005217 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5218 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005219 return nullptr;
5220 }
5221 rtp_data_channels_[channel->label()] = channel;
5222 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005223 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005224 sctp_data_channels_.push_back(channel);
5225 channel->SignalClosed.connect(this,
5226 &PeerConnection::OnSctpDataChannelClosed);
5227 }
5228
Steve Anton2d8609c2018-01-23 16:38:46 -08005229 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005230 return channel;
5231}
5232
5233bool PeerConnection::HasDataChannels() const {
5234 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5235}
5236
5237void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005238 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005239 for (const auto& channel : sctp_data_channels_) {
5240 if (channel->id() < 0) {
5241 int sid;
5242 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005243 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5244 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005245 continue;
5246 }
5247 channel->SetSctpSid(sid);
5248 }
5249 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005250 // Since closing modifies the list of channels, we have to do the actual
5251 // closing outside the loop.
5252 for (const auto& channel : channels_to_close) {
5253 channel->CloseAbruptly();
5254 }
deadbeefab9b2d12015-10-14 11:33:11 -07005255}
5256
5257void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005258 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005259 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5260 ++it) {
5261 if (it->get() == channel) {
5262 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005263 // After the closing procedure is done, it's safe to use this ID for
5264 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005265 sid_allocator_.ReleaseSid(channel->id());
5266 }
deadbeefbd292462015-12-14 18:15:29 -08005267 // Since this method is triggered by a signal from the DataChannel,
5268 // we can't free it directly here; we need to free it asynchronously.
5269 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005270 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005271 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5272 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005273 return;
5274 }
5275 }
5276}
5277
deadbeefab9b2d12015-10-14 11:33:11 -07005278void PeerConnection::OnDataChannelDestroyed() {
5279 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5280 // DataChannel may callback to us and try to modify the list.
5281 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5282 temp_rtp_dcs.swap(rtp_data_channels_);
5283 for (const auto& kv : temp_rtp_dcs) {
5284 kv.second->OnTransportChannelDestroyed();
5285 }
5286
5287 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5288 temp_sctp_dcs.swap(sctp_data_channels_);
5289 for (const auto& channel : temp_sctp_dcs) {
5290 channel->OnTransportChannelDestroyed();
5291 }
5292}
5293
5294void PeerConnection::OnDataChannelOpenMessage(
5295 const std::string& label,
5296 const InternalDataChannelInit& config) {
5297 rtc::scoped_refptr<DataChannel> channel(
5298 InternalCreateDataChannel(label, &config));
5299 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005300 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005301 return;
5302 }
5303
deadbeefa601f5c2016-06-06 14:27:39 -07005304 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5305 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005306 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005307 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005308}
5309
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005310bool PeerConnection::HandleOpenMessage_s(
5311 const cricket::ReceiveDataParams& params,
5312 const rtc::CopyOnWriteBuffer& buffer) {
5313 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5314 // Received OPEN message; parse and signal that a new data channel should
5315 // be created.
5316 std::string label;
5317 InternalDataChannelInit config;
5318 config.id = params.ssrc;
5319 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5320 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5321 << params.ssrc;
5322 return true;
5323 }
5324 config.open_handshake_role = InternalDataChannelInit::kAcker;
5325 OnDataChannelOpenMessage(label, config);
5326 return true;
5327 }
5328 return false;
5329}
5330
Steve Anton4171afb2017-11-20 10:20:22 -08005331rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5332PeerConnection::GetAudioTransceiver() const {
5333 // This method only works with Plan B SDP, where there is a single
5334 // audio/video transceiver.
5335 RTC_DCHECK(!IsUnifiedPlan());
5336 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005337 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005338 return transceiver;
5339 }
5340 }
5341 RTC_NOTREACHED();
5342 return nullptr;
5343}
5344
5345rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5346PeerConnection::GetVideoTransceiver() const {
5347 // This method only works with Plan B SDP, where there is a single
5348 // audio/video transceiver.
5349 RTC_DCHECK(!IsUnifiedPlan());
5350 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005351 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005352 return transceiver;
5353 }
5354 }
5355 RTC_NOTREACHED();
5356 return nullptr;
5357}
5358
5359// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5360// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005361bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005362 switch (type) {
5363 case cricket::MEDIA_TYPE_AUDIO:
5364 return !GetAudioTransceiver()->internal()->senders().empty();
5365 case cricket::MEDIA_TYPE_VIDEO:
5366 return !GetVideoTransceiver()->internal()->senders().empty();
5367 case cricket::MEDIA_TYPE_DATA:
5368 return false;
5369 }
5370 RTC_NOTREACHED();
5371 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005372}
5373
Steve Anton4171afb2017-11-20 10:20:22 -08005374rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5375PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005376 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005377 for (auto sender : transceiver->internal()->senders()) {
5378 if (sender->track() == track) {
5379 return sender;
5380 }
5381 }
5382 }
5383 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005384}
5385
Steve Anton4171afb2017-11-20 10:20:22 -08005386rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5387PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005388 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005389 for (auto sender : transceiver->internal()->senders()) {
5390 if (sender->id() == sender_id) {
5391 return sender;
5392 }
5393 }
5394 }
5395 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005396}
5397
Steve Anton4171afb2017-11-20 10:20:22 -08005398rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5399PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005400 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005401 for (auto receiver : transceiver->internal()->receivers()) {
5402 if (receiver->id() == receiver_id) {
5403 return receiver;
5404 }
5405 }
5406 }
5407 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005408}
5409
Steve Anton4171afb2017-11-20 10:20:22 -08005410std::vector<PeerConnection::RtpSenderInfo>*
5411PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5412 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5413 media_type == cricket::MEDIA_TYPE_VIDEO);
5414 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5415 ? &remote_audio_sender_infos_
5416 : &remote_video_sender_infos_;
5417}
5418
5419std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005420 cricket::MediaType media_type) {
5421 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5422 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005423 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5424 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005425}
5426
Steve Anton4171afb2017-11-20 10:20:22 -08005427const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5428 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005429 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005430 const std::string sender_id) const {
5431 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005432 if (sender_info.stream_id == stream_id &&
5433 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005434 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005435 }
5436 }
5437 return nullptr;
5438}
5439
5440DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5441 for (const auto& channel : sctp_data_channels_) {
5442 if (channel->id() == sid) {
5443 return channel;
5444 }
5445 }
5446 return nullptr;
5447}
5448
Karl Wibergfb3be392019-03-22 14:13:22 +01005449PeerConnection::InitializePortAllocatorResult
5450PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005451 const cricket::ServerAddresses& stun_servers,
5452 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005453 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005454 RTC_DCHECK_RUN_ON(network_thread());
5455
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005456 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005457 // To handle both internal and externally created port allocator, we will
5458 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005459 int port_allocator_flags = port_allocator_->flags();
5460 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5461 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5462 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005463 // If the disable-IPv6 flag was specified, we'll not override it
5464 // by experiment.
5465 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005466 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005467 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5468 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005469 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005470 }
5471
zhihuangb09b3f92017-03-07 14:40:51 -08005472 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005473 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005474 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005475 }
5476
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005477 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005478 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005479 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005480 }
5481
honghaiz60347052016-05-31 18:29:12 -07005482 if (configuration.candidate_network_policy ==
5483 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005484 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005485 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005486 }
5487
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005488 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005489 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005490 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5491 }
5492
Karl Wibergfb3be392019-03-22 14:13:22 +01005493 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005494 // No step delay is used while allocating ports.
5495 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005496 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005497 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005498 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005499
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005500 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005501 for (auto& turn_server : turn_servers_copy) {
5502 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005503 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005504 // Call this last since it may create pooled allocator sessions using the
5505 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005506 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005507 stun_servers, std::move(turn_servers_copy),
5508 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5509 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005510 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005511
5512 InitializePortAllocatorResult res;
5513 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5514 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005515}
5516
deadbeef91dd5672016-05-18 16:55:30 -07005517bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005518 const cricket::ServerAddresses& stun_servers,
5519 const std::vector<cricket::RelayServerConfig>& turn_servers,
5520 IceTransportsType type,
5521 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005522 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005523 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005524 absl::optional<int> stun_candidate_keepalive_interval,
5525 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005526 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005527 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005528 // According to JSEP, after setLocalDescription, changing the candidate pool
5529 // size is not allowed, and changing the set of ICE servers will not result
5530 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005531 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005532 port_allocator_->FreezeCandidatePool();
5533 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005534 // Add the custom tls turn servers if they exist.
5535 auto turn_servers_copy = turn_servers;
5536 for (auto& turn_server : turn_servers_copy) {
5537 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5538 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005539 // Call this last since it may create pooled allocator sessions using the
5540 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005541 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005542 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5543 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005544}
5545
Steve Antonba818672017-11-06 10:21:57 -08005546cricket::ChannelManager* PeerConnection::channel_manager() const {
5547 return factory_->channel_manager();
5548}
5549
Elad Alon99c3fe52017-10-13 16:29:40 +02005550bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005551 std::unique_ptr<RtcEventLogOutput> output,
5552 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005553 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005554 if (!event_log_) {
5555 return false;
5556 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005557 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005558}
5559
5560void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005561 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005562 if (event_log_) {
5563 event_log_->StopLogging();
5564 }
ivoc14d5dbe2016-07-04 07:06:55 -07005565}
nisseeaabdf62017-05-05 02:23:02 -07005566
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005567cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005568 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005569 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005570 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005571 if (channel && channel->content_name() == content_name) {
5572 return channel;
5573 }
Steve Anton75737c02017-11-06 10:37:17 -08005574 }
5575 if (rtp_data_channel() &&
5576 rtp_data_channel()->content_name() == content_name) {
5577 return rtp_data_channel();
5578 }
5579 return nullptr;
5580}
5581
5582bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005583 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005584 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005585 RTC_LOG(LS_INFO)
5586 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005587 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005588 return false;
5589 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005590 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005591 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005592 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005593 return false;
5594 }
5595
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005596 absl::optional<rtc::SSLRole> dtls_role;
5597 if (sctp_mid_) {
5598 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5599 } else if (is_caller_) {
5600 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5601 }
Zhi Huange830e682018-03-30 10:48:35 -07005602 if (dtls_role) {
5603 *role = *dtls_role;
5604 return true;
5605 }
5606 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005607}
5608
5609bool PeerConnection::GetSslRole(const std::string& content_name,
5610 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005611 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005612 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005613 RTC_LOG(LS_INFO)
5614 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005615 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005616 return false;
5617 }
5618
Zhi Huange830e682018-03-30 10:48:35 -07005619 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5620 if (dtls_role) {
5621 *role = *dtls_role;
5622 return true;
5623 }
5624 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005625}
5626
Steve Antonf8470812017-12-04 10:46:21 -08005627void PeerConnection::SetSessionError(SessionError error,
5628 const std::string& error_desc) {
5629 RTC_DCHECK_RUN_ON(signaling_thread());
5630 if (error != session_error_) {
5631 session_error_ = error;
5632 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005633 }
5634}
5635
Zhi Huange830e682018-03-30 10:48:35 -07005636RTCError PeerConnection::UpdateSessionState(
5637 SdpType type,
5638 cricket::ContentSource source,
5639 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005640 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005641
5642 // If there's already a pending error then no state transition should happen.
5643 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005644 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005645
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005646 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005647 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005648 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005649 }
5650
5651 // Update the signaling state according to the specified state machine (see
5652 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005653 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005654 ChangeSignalingState(source == cricket::CS_LOCAL
5655 ? PeerConnectionInterface::kHaveLocalOffer
5656 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005657 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005658 ChangeSignalingState(source == cricket::CS_LOCAL
5659 ? PeerConnectionInterface::kHaveLocalPrAnswer
5660 : PeerConnectionInterface::kHaveRemotePrAnswer);
5661 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005662 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005663 ChangeSignalingState(PeerConnectionInterface::kStable);
5664 }
5665
5666 // Update internal objects according to the session description's media
5667 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005668 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005669 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005670 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005671 }
5672
Steve Anton8a006912017-12-04 15:25:56 -08005673 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005674}
5675
Steve Anton8a006912017-12-04 15:25:56 -08005676RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005677 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005678 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005679 const SessionDescriptionInterface* sdesc =
5680 (source == cricket::CS_LOCAL ? local_description()
5681 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005682 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005683
5684 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005685 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005686 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005687 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005688 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005689 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005690 continue;
5691 }
5692 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005693 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005694 if (!content_desc) {
5695 continue;
5696 }
5697 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005698 bool success = (source == cricket::CS_LOCAL)
5699 ? channel->SetLocalContent(content_desc, type, &error)
5700 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005701 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005702 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005703 }
5704 }
5705
5706 // If using the RtpDataChannel, push down the new SDP section for it too.
5707 if (rtp_data_channel_) {
5708 const ContentInfo* data_content =
5709 cricket::GetFirstDataContent(sdesc->description());
5710 if (data_content && !data_content->rejected) {
5711 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005712 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005713 if (data_desc) {
5714 std::string error;
5715 bool success =
5716 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005717 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005718 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005719 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005720 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005721 }
Steve Anton75737c02017-11-06 10:37:17 -08005722 }
5723 }
5724 }
Steve Antoned10bd92017-12-05 10:52:59 -08005725
Steve Anton75737c02017-11-06 10:37:17 -08005726 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5727 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005728 if (sctp_transport_ && local_description() && remote_description()) {
5729 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5730 local_description()->description());
5731 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5732 remote_description()->description());
5733 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005734 int max_message_size;
5735 // A remote max message size of zero means "any size supported".
5736 // We configure the connection with our own max message size.
5737 if (remote_sctp_description->max_message_size() == 0) {
5738 max_message_size = local_sctp_description->max_message_size();
5739 } else {
5740 max_message_size =
5741 std::min(local_sctp_description->max_message_size(),
5742 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005743 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005744 sctp_transport_->Start(local_sctp_description->port(),
5745 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005746 }
Steve Anton75737c02017-11-06 10:37:17 -08005747 }
Steve Antoned10bd92017-12-05 10:52:59 -08005748
Steve Anton8a006912017-12-04 15:25:56 -08005749 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005750}
5751
Steve Anton8a006912017-12-04 15:25:56 -08005752RTCError PeerConnection::PushdownTransportDescription(
5753 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005754 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005755 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005756
Zhi Huange830e682018-03-30 10:48:35 -07005757 if (source == cricket::CS_LOCAL) {
5758 const SessionDescriptionInterface* sdesc = local_description();
5759 RTC_DCHECK(sdesc);
5760 return transport_controller_->SetLocalDescription(type,
5761 sdesc->description());
5762 } else {
5763 const SessionDescriptionInterface* sdesc = remote_description();
5764 RTC_DCHECK(sdesc);
5765 return transport_controller_->SetRemoteDescription(type,
5766 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005767 }
Steve Anton75737c02017-11-06 10:37:17 -08005768}
5769
5770bool PeerConnection::GetTransportDescription(
5771 const SessionDescription* description,
5772 const std::string& content_name,
5773 cricket::TransportDescription* tdesc) {
5774 if (!description || !tdesc) {
5775 return false;
5776 }
5777 const TransportInfo* transport_info =
5778 description->GetTransportInfoByName(content_name);
5779 if (!transport_info) {
5780 return false;
5781 }
5782 *tdesc = transport_info->description;
5783 return true;
5784}
5785
Steve Anton75737c02017-11-06 10:37:17 -08005786cricket::IceConfig PeerConnection::ParseIceConfig(
5787 const PeerConnectionInterface::RTCConfiguration& config) const {
5788 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005789 switch (config.continual_gathering_policy) {
5790 case PeerConnectionInterface::GATHER_ONCE:
5791 gathering_policy = cricket::GATHER_ONCE;
5792 break;
5793 case PeerConnectionInterface::GATHER_CONTINUALLY:
5794 gathering_policy = cricket::GATHER_CONTINUALLY;
5795 break;
5796 default:
5797 RTC_NOTREACHED();
5798 gathering_policy = cricket::GATHER_ONCE;
5799 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005800
Steve Anton75737c02017-11-06 10:37:17 -08005801 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005802 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5803 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005804 ice_config.prioritize_most_likely_candidate_pairs =
5805 config.prioritize_most_likely_ice_candidate_pairs;
5806 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005807 RTCConfigurationToIceConfigOptionalInt(
5808 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005809 ice_config.continual_gathering_policy = gathering_policy;
5810 ice_config.presume_writable_when_fully_relayed =
5811 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005812 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5813 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005814 ice_config.ice_check_interval_strong_connectivity =
5815 config.ice_check_interval_strong_connectivity;
5816 ice_config.ice_check_interval_weak_connectivity =
5817 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005818 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005819 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5820 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005821 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005822 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005823 ice_config.regather_all_networks_interval_range =
5824 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005825 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005826 return ice_config;
5827}
5828
Steve Anton75737c02017-11-06 10:37:17 -08005829bool PeerConnection::SendData(const cricket::SendDataParams& params,
5830 const rtc::CopyOnWriteBuffer& payload,
5831 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005832 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005833 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5834 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5835 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005836 return false;
5837 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005838 if (media_transport_) {
5839 SendDataParams send_params;
5840 send_params.type = ToWebrtcDataMessageType(params.type);
5841 send_params.ordered = params.ordered;
5842 if (params.max_rtx_count >= 0) {
5843 send_params.max_rtx_count = params.max_rtx_count;
5844 } else if (params.max_rtx_ms >= 0) {
5845 send_params.max_rtx_ms = params.max_rtx_ms;
5846 }
5847 return media_transport_->SendData(params.sid, send_params, payload).ok();
5848 }
Steve Anton75737c02017-11-06 10:37:17 -08005849 return rtp_data_channel_
5850 ? rtp_data_channel_->SendData(params, payload, result)
5851 : network_thread()->Invoke<bool>(
5852 RTC_FROM_HERE,
5853 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005854 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005855}
5856
5857bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005858 RTC_DCHECK_RUN_ON(signaling_thread());
5859 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005860 // Don't log an error here, because DataChannels are expected to call
5861 // ConnectDataChannel in this state. It's the only way to initially tell
5862 // whether or not the underlying transport is ready.
5863 return false;
5864 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005865 if (media_transport_) {
5866 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5867 &DataChannel::OnChannelReady);
5868 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5869 &DataChannel::OnDataReceived);
5870 SignalMediaTransportChannelClosing_s.connect(
5871 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5872 SignalMediaTransportChannelClosed_s.connect(
5873 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5874 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005875 rtp_data_channel_->SignalReadyToSendData.connect(
5876 webrtc_data_channel, &DataChannel::OnChannelReady);
5877 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5878 &DataChannel::OnDataReceived);
5879 } else {
5880 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5881 &DataChannel::OnChannelReady);
5882 SignalSctpDataReceived.connect(webrtc_data_channel,
5883 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005884 SignalSctpClosingProcedureStartedRemotely.connect(
5885 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5886 SignalSctpClosingProcedureComplete.connect(
5887 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005888 }
5889 return true;
5890}
5891
5892void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005893 RTC_DCHECK_RUN_ON(signaling_thread());
5894 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005895 RTC_LOG(LS_ERROR)
5896 << "DisconnectDataChannel called when rtp_data_channel_ and "
5897 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005898 return;
5899 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005900 if (media_transport_) {
5901 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5902 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5903 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5904 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5905 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005906 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5907 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5908 } else {
5909 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5910 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005911 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5912 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005913 }
5914}
5915
5916void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005917 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005918 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005919 return;
5920 }
Steve Anton75737c02017-11-06 10:37:17 -08005921 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005922 RTC_LOG(LS_ERROR)
5923 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005924 return;
5925 }
5926 network_thread()->Invoke<void>(
5927 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005928 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005929}
5930
5931void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005932 if (media_transport_) {
5933 media_transport_->CloseChannel(sid);
5934 return;
5935 }
Steve Anton75737c02017-11-06 10:37:17 -08005936 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005937 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005938 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005939 return;
5940 }
5941 network_thread()->Invoke<void>(
5942 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005943 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005944}
5945
5946bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005947 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005948 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005949 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005950 sctp_ready_to_send_data_;
5951}
5952
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005953void PeerConnection::OnDataReceived(int channel_id,
5954 DataMessageType type,
5955 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005956 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005957 cricket::ReceiveDataParams params;
5958 params.sid = channel_id;
5959 params.type = ToCricketDataMessageType(type);
5960 media_transport_invoker_->AsyncInvoke<void>(
5961 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5962 RTC_DCHECK_RUN_ON(signaling_thread());
5963 if (!HandleOpenMessage_s(params, buffer)) {
5964 SignalMediaTransportReceivedData_s(params, buffer);
5965 }
5966 });
5967}
5968
5969void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005970 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005971 media_transport_invoker_->AsyncInvoke<void>(
5972 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5973 RTC_DCHECK_RUN_ON(signaling_thread());
5974 SignalMediaTransportChannelClosing_s(channel_id);
5975 });
5976}
5977
5978void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005979 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005980 media_transport_invoker_->AsyncInvoke<void>(
5981 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5982 RTC_DCHECK_RUN_ON(signaling_thread());
5983 SignalMediaTransportChannelClosed_s(channel_id);
5984 });
5985}
5986
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005987absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005988 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005989 if (sctp_mid_ && transport_controller_) {
5990 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5991 if (dtls_transport) {
5992 return dtls_transport->transport_name();
5993 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005994 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005995 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005996 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005997}
5998
Qingsi Wang72a43a12018-02-20 16:03:18 -08005999cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6000 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006001 network_thread()->Invoke<void>(
6002 RTC_FROM_HERE,
6003 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6004 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006005 return candidate_states_list;
6006}
6007
Steve Anton5dfde182018-02-06 10:34:40 -08006008std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6009 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006010 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006011 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006012 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006013 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006014 if (channel) {
6015 transport_names_by_mid[channel->content_name()] =
6016 channel->transport_name();
6017 }
Steve Anton75737c02017-11-06 10:37:17 -08006018 }
Steve Anton5dfde182018-02-06 10:34:40 -08006019 if (rtp_data_channel_) {
6020 transport_names_by_mid[rtp_data_channel_->content_name()] =
6021 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006022 }
6023 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006024 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006025 RTC_DCHECK(transport_name);
6026 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006027 }
Steve Anton5dfde182018-02-06 10:34:40 -08006028 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006029}
6030
Steve Anton5dfde182018-02-06 10:34:40 -08006031std::map<std::string, cricket::TransportStats>
6032PeerConnection::GetTransportStatsByNames(
6033 const std::set<std::string>& transport_names) {
6034 if (!network_thread()->IsCurrent()) {
6035 return network_thread()
6036 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6037 RTC_FROM_HERE,
6038 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006039 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006040 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006041 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6042 for (const std::string& transport_name : transport_names) {
6043 cricket::TransportStats transport_stats;
6044 bool success =
6045 transport_controller_->GetStats(transport_name, &transport_stats);
6046 if (success) {
6047 transport_stats_by_name[transport_name] = std::move(transport_stats);
6048 } else {
6049 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6050 << transport_name;
6051 }
6052 }
6053 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006054}
6055
6056bool PeerConnection::GetLocalCertificate(
6057 const std::string& transport_name,
6058 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006059 if (!certificate) {
6060 return false;
6061 }
6062 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6063 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006064}
6065
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006066std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006067 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006068 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006069}
6070
6071cricket::DataChannelType PeerConnection::data_channel_type() const {
6072 return data_channel_type_;
6073}
6074
6075bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006076 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006077 return pending_ice_restarts_.find(content_name) !=
6078 pending_ice_restarts_.end();
6079}
6080
Steve Anton75737c02017-11-06 10:37:17 -08006081bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6082 return transport_controller_->NeedsIceRestart(content_name);
6083}
6084
6085void PeerConnection::OnCertificateReady(
6086 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6087 transport_controller_->SetLocalCertificate(certificate);
6088}
6089
6090void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006091 SetSessionError(SessionError::kTransport,
6092 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006093}
6094
Alex Loiko9289eda2018-11-23 16:18:59 +00006095void PeerConnection::OnTransportControllerConnectionState(
6096 cricket::IceConnectionState state) {
6097 switch (state) {
6098 case cricket::kIceConnectionConnecting:
6099 // If the current state is Connected or Completed, then there were
6100 // writable channels but now there are not, so the next state must
6101 // be Disconnected.
6102 // kIceConnectionConnecting is currently used as the default,
6103 // un-connected state by the TransportController, so its only use is
6104 // detecting disconnections.
6105 if (ice_connection_state_ ==
6106 PeerConnectionInterface::kIceConnectionConnected ||
6107 ice_connection_state_ ==
6108 PeerConnectionInterface::kIceConnectionCompleted) {
6109 SetIceConnectionState(
6110 PeerConnectionInterface::kIceConnectionDisconnected);
6111 }
6112 break;
6113 case cricket::kIceConnectionFailed:
6114 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6115 break;
6116 case cricket::kIceConnectionConnected:
6117 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6118 "all transports are writable.";
6119 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6120 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6121 break;
6122 case cricket::kIceConnectionCompleted:
6123 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6124 "all transports are complete.";
6125 if (ice_connection_state_ !=
6126 PeerConnectionInterface::kIceConnectionConnected) {
6127 // If jumping directly from "checking" to "connected",
6128 // signal "connected" first.
6129 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6130 }
6131 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6132 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6133 ReportTransportStats();
6134 break;
6135 default:
6136 RTC_NOTREACHED();
6137 }
6138}
6139
Steve Anton75737c02017-11-06 10:37:17 -08006140void PeerConnection::OnTransportControllerCandidatesGathered(
6141 const std::string& transport_name,
6142 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006143 int sdp_mline_index;
6144 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006145 RTC_LOG(LS_ERROR)
6146 << "OnTransportControllerCandidatesGathered: content name "
6147 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006148 return;
6149 }
6150
6151 for (cricket::Candidates::const_iterator citer = candidates.begin();
6152 citer != candidates.end(); ++citer) {
6153 // Use transport_name as the candidate media id.
6154 std::unique_ptr<JsepIceCandidate> candidate(
6155 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6156 if (local_description()) {
6157 mutable_local_description()->AddCandidate(candidate.get());
6158 }
6159 OnIceCandidate(std::move(candidate));
6160 }
6161}
6162
Eldar Relloda13ea22019-06-01 12:23:43 +03006163void PeerConnection::OnTransportControllerCandidateError(
6164 const cricket::IceCandidateErrorEvent& event) {
6165 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6166 event.error_text);
6167}
6168
Steve Anton75737c02017-11-06 10:37:17 -08006169void PeerConnection::OnTransportControllerCandidatesRemoved(
6170 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006171 // Sanity check.
6172 for (const cricket::Candidate& candidate : candidates) {
6173 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006174 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006175 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006176 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006177 return;
6178 }
6179 }
6180
6181 if (local_description()) {
6182 mutable_local_description()->RemoveCandidates(candidates);
6183 }
6184 OnIceCandidatesRemoved(candidates);
6185}
6186
6187void PeerConnection::OnTransportControllerDtlsHandshakeError(
6188 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006189 RTC_HISTOGRAM_ENUMERATION(
6190 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6191 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006192}
6193
Steve Antoned10bd92017-12-05 10:52:59 -08006194void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006195 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006196 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006197 if (channel && !channel->enabled()) {
6198 channel->Enable(true);
6199 }
Steve Anton75737c02017-11-06 10:37:17 -08006200 }
6201
Steve Anton4171afb2017-11-20 10:20:22 -08006202 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006203 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006204 }
Steve Anton75737c02017-11-06 10:37:17 -08006205}
6206
6207// Returns the media index for a local ice candidate given the content name.
6208bool PeerConnection::GetLocalCandidateMediaIndex(
6209 const std::string& content_name,
6210 int* sdp_mline_index) {
6211 if (!local_description() || !sdp_mline_index) {
6212 return false;
6213 }
6214
6215 bool content_found = false;
6216 const ContentInfos& contents = local_description()->description()->contents();
6217 for (size_t index = 0; index < contents.size(); ++index) {
6218 if (contents[index].name == content_name) {
6219 *sdp_mline_index = static_cast<int>(index);
6220 content_found = true;
6221 break;
6222 }
6223 }
6224 return content_found;
6225}
6226
6227bool PeerConnection::UseCandidatesInSessionDescription(
6228 const SessionDescriptionInterface* remote_desc) {
6229 if (!remote_desc) {
6230 return true;
6231 }
6232 bool ret = true;
6233
6234 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6235 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6236 for (size_t n = 0; n < candidates->count(); ++n) {
6237 const IceCandidateInterface* candidate = candidates->at(n);
6238 bool valid = false;
6239 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6240 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006241 RTC_LOG(LS_INFO)
6242 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006243 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006244 }
6245 continue;
6246 }
6247 ret = UseCandidate(candidate);
6248 if (!ret) {
6249 break;
6250 }
6251 }
6252 }
6253 return ret;
6254}
6255
6256bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006257 RTCErrorOr<const cricket::ContentInfo*> result =
6258 FindContentInfo(remote_description(), candidate);
6259 if (!result.ok()) {
6260 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6261 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006262 return false;
6263 }
Steve Anton75737c02017-11-06 10:37:17 -08006264 std::vector<cricket::Candidate> candidates;
6265 candidates.push_back(candidate->candidate());
6266 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006267 RTCError error = transport_controller_->AddRemoteCandidates(
6268 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006269 if (error.ok()) {
6270 // Candidates successfully submitted for checking.
6271 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6272 ice_connection_state_ ==
6273 PeerConnectionInterface::kIceConnectionDisconnected) {
6274 // If state is New, then the session has just gotten its first remote ICE
6275 // candidates, so go to Checking.
6276 // If state is Disconnected, the session is re-using old candidates or
6277 // receiving additional ones, so go to Checking.
6278 // If state is Connected, stay Connected.
6279 // TODO(bemasc): If state is Connected, and the new candidates are for a
6280 // newly added transport, then the state actually _should_ move to
6281 // checking. Add a way to distinguish that case.
6282 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6283 }
6284 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006285 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006286 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006287 }
6288 return true;
6289}
6290
Guido Urdaneta41633172019-05-23 20:12:29 +02006291RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6292 const SessionDescriptionInterface* description,
6293 const IceCandidateInterface* candidate) {
6294 if (candidate->sdp_mline_index() >= 0) {
6295 size_t mediacontent_index =
6296 static_cast<size_t>(candidate->sdp_mline_index());
6297 size_t content_size = description->description()->contents().size();
6298 if (mediacontent_index < content_size) {
6299 return &description->description()->contents()[mediacontent_index];
6300 } else {
6301 return RTCError(RTCErrorType::INVALID_RANGE,
6302 "Media line index (" +
6303 rtc::ToString(candidate->sdp_mline_index()) +
6304 ") out of range (number of mlines: " +
6305 rtc::ToString(content_size) + ").");
6306 }
6307 } else if (!candidate->sdp_mid().empty()) {
6308 auto& contents = description->description()->contents();
6309 auto it = absl::c_find_if(
6310 contents, [candidate](const cricket::ContentInfo& content_info) {
6311 return content_info.mid() == candidate->sdp_mid();
6312 });
6313 if (it == contents.end()) {
6314 return RTCError(
6315 RTCErrorType::INVALID_PARAMETER,
6316 "Mid " + candidate->sdp_mid() +
6317 " specified but no media section with that mid found.");
6318 } else {
6319 return &*it;
6320 }
6321 }
6322
6323 return RTCError(RTCErrorType::INVALID_PARAMETER,
6324 "Neither sdp_mline_index nor sdp_mid specified.");
6325}
6326
Steve Anton75737c02017-11-06 10:37:17 -08006327void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006328 // Destroy video channel first since it may have a pointer to the
6329 // voice channel.
6330 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006331 if (!video_info || video_info->rejected) {
6332 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006333 }
6334
Steve Anton6fec8802017-12-04 10:37:29 -08006335 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6336 if (!audio_info || audio_info->rejected) {
6337 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006338 }
6339
6340 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6341 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006342 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006343 }
6344}
6345
Steve Antondcc3c022017-12-22 16:02:54 -08006346RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6347 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006348 const cricket::ContentGroup* bundle_group = nullptr;
6349 if (configuration_.bundle_policy ==
6350 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006351 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006352 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006353 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6354 "max-bundle configured but session description "
6355 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006356 }
6357 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006358 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006359}
6360
6361RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006362 // Creating the media channels. Transports should already have been created
6363 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006364 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006365 if (voice && !voice->rejected &&
6366 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006367 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006368 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006369 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6370 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006371 }
6372 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6373 }
6374
Steve Antondcc3c022017-12-22 16:02:54 -08006375 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006376 if (video && !video->rejected &&
6377 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006378 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006379 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006380 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6381 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006382 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006383 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006384 }
6385
Steve Antondcc3c022017-12-22 16:02:54 -08006386 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006387 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006388 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006389 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006390 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6391 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006392 }
6393 }
6394
Steve Anton8a006912017-12-04 15:25:56 -08006395 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006396}
6397
Steve Anton4171afb2017-11-20 10:20:22 -08006398// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006399cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006400 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006401 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006402 MediaTransportConfig media_transport_config =
6403 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006404
Steve Anton75737c02017-11-06 10:37:17 -08006405 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006406 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006407 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6408 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006409 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006410 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006411 }
Steve Anton75737c02017-11-06 10:37:17 -08006412 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6413 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006414 voice_channel->SignalSentPacket.connect(this,
6415 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006416 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006417
Steve Antoneda6ccd2017-12-04 10:21:55 -08006418 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006419}
6420
Steve Anton4171afb2017-11-20 10:20:22 -08006421// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006422cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006423 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006424 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006425 MediaTransportConfig media_transport_config =
6426 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006427
Steve Anton75737c02017-11-06 10:37:17 -08006428 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006429 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006430 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6431 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006432 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006433 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006434 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006435 }
Steve Anton75737c02017-11-06 10:37:17 -08006436 video_channel->SignalDtlsSrtpSetupFailure.connect(
6437 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006438 video_channel->SignalSentPacket.connect(this,
6439 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006440 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006441
Steve Antoneda6ccd2017-12-04 10:21:55 -08006442 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006443}
6444
Zhi Huange830e682018-03-30 10:48:35 -07006445bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006446 switch (data_channel_type_) {
6447 case cricket::DCT_MEDIA_TRANSPORT:
6448 if (network_thread()->Invoke<bool>(
6449 RTC_FROM_HERE,
6450 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6451 this, mid))) {
6452 for (const auto& channel : sctp_data_channels_) {
6453 channel->OnTransportChannelCreated();
6454 }
6455 return true;
6456 }
Steve Anton75737c02017-11-06 10:37:17 -08006457 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006458 case cricket::DCT_SCTP:
6459 if (!sctp_factory_) {
6460 RTC_LOG(LS_ERROR)
6461 << "Trying to create SCTP transport, but didn't compile with "
6462 "SCTP support (HAVE_SCTP)";
6463 return false;
6464 }
6465 if (!network_thread()->Invoke<bool>(
6466 RTC_FROM_HERE,
6467 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6468 return false;
6469 }
6470 for (const auto& channel : sctp_data_channels_) {
6471 channel->OnTransportChannelCreated();
6472 }
6473 return true;
6474 case cricket::DCT_RTP:
6475 default:
6476 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6477 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6478 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006479 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006480 if (!rtp_data_channel_) {
6481 return false;
6482 }
6483 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6484 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6485 rtp_data_channel_->SignalSentPacket.connect(
6486 this, &PeerConnection::OnSentPacket_w);
6487 rtp_data_channel_->SetRtpTransport(rtp_transport);
6488 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006489 }
6490
Steve Anton75737c02017-11-06 10:37:17 -08006491 return true;
6492}
6493
6494Call::Stats PeerConnection::GetCallStats() {
6495 if (!worker_thread()->IsCurrent()) {
6496 return worker_thread()->Invoke<Call::Stats>(
6497 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6498 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006499 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006500 if (call_) {
6501 return call_->GetStats();
6502 } else {
6503 return Call::Stats();
6504 }
6505}
6506
Zhi Huange830e682018-03-30 10:48:35 -07006507bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006508 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006509 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006510 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6511 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006512 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006513 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006514 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006515 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6516 sctp_factory_->CreateSctpTransport(dtls_transport);
6517 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006518 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006519 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006520 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006521 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006522 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006523 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6524 // another thread. Would be nice if there was a helper class similar to
6525 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6526 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006527 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006528 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006529 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006530 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006531 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006532 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6533 std::move(cricket_sctp_transport));
6534 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006535 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006536}
6537
6538void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006539 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006540 sctp_transport_->Clear();
6541 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006542 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006543 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006544}
6545
6546void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006547 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006548 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006549 // Note: Cannot use rtc::Bind here because it will grab a reference to
6550 // PeerConnection and potentially cause PeerConnection to live longer than
6551 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6552 // be destroyed before PeerConnection is destroyed, and at that point all
6553 // pending tasks will be cleared.
6554 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6555 OnSctpTransportReadyToSendData_s(true);
6556 });
6557}
6558
6559void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006560 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006561 sctp_ready_to_send_data_ = ready;
6562 SignalSctpReadyToSendData(ready);
6563}
6564
6565void PeerConnection::OnSctpTransportDataReceived_n(
6566 const cricket::ReceiveDataParams& params,
6567 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006568 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006569 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006570 // Note: Cannot use rtc::Bind here because it will grab a reference to
6571 // PeerConnection and potentially cause PeerConnection to live longer than
6572 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6573 // be destroyed before PeerConnection is destroyed, and at that point all
6574 // pending tasks will be cleared.
6575 sctp_invoker_->AsyncInvoke<void>(
6576 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6577 OnSctpTransportDataReceived_s(params, payload);
6578 });
6579}
6580
6581void PeerConnection::OnSctpTransportDataReceived_s(
6582 const cricket::ReceiveDataParams& params,
6583 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006584 RTC_DCHECK_RUN_ON(signaling_thread());
6585 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006586 SignalSctpDataReceived(params, payload);
6587 }
6588}
6589
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006590void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006591 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006592 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006593 sctp_invoker_->AsyncInvoke<void>(
6594 RTC_FROM_HERE, signaling_thread(),
6595 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006596 &SignalSctpClosingProcedureStartedRemotely, sid));
6597}
6598
6599void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006600 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006601 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006602 sctp_invoker_->AsyncInvoke<void>(
6603 RTC_FROM_HERE, signaling_thread(),
6604 rtc::Bind(&sigslot::signal1<int>::operator(),
6605 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006606}
6607
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006608bool PeerConnection::SetupMediaTransportForDataChannels_n(
6609 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006610 media_transport_ =
6611 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006612 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006613 RTC_LOG(LS_ERROR)
6614 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006615 return false;
6616 }
6617
6618 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6619 media_transport_->SetDataSink(this);
6620 media_transport_data_mid_ = mid;
6621 transport_controller_->SignalMediaTransportStateChanged.connect(
6622 this, &PeerConnection::OnMediaTransportStateChanged_n);
6623 // Check the initial state right away, in case transport is already writable.
6624 OnMediaTransportStateChanged_n();
6625 return true;
6626}
6627
6628void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6629 if (!media_transport_) {
6630 return;
6631 }
6632 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6633 media_transport_data_mid_.reset();
6634 media_transport_->SetDataSink(nullptr);
6635 media_transport_invoker_ = nullptr;
6636 media_transport_ = nullptr;
6637}
6638
6639void PeerConnection::OnMediaTransportStateChanged_n() {
6640 if (!media_transport_data_mid_ ||
6641 transport_controller_->GetMediaTransportState(
6642 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6643 return;
6644 }
6645 media_transport_invoker_->AsyncInvoke<void>(
6646 RTC_FROM_HERE, signaling_thread(), [this] {
6647 RTC_DCHECK_RUN_ON(signaling_thread());
6648 media_transport_ready_to_send_data_ = true;
6649 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6650 });
6651}
6652
Steve Anton75737c02017-11-06 10:37:17 -08006653// Returns false if bundle is enabled and rtcp_mux is disabled.
6654bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6655 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6656 if (!bundle_enabled)
6657 return true;
6658
6659 const cricket::ContentGroup* bundle_group =
6660 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6661 RTC_DCHECK(bundle_group != NULL);
6662
6663 const cricket::ContentInfos& contents = desc->contents();
6664 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6665 citer != contents.end(); ++citer) {
6666 const cricket::ContentInfo* content = (&*citer);
6667 RTC_DCHECK(content != NULL);
6668 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006669 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006670 if (!HasRtcpMuxEnabled(content))
6671 return false;
6672 }
6673 }
6674 // RTCP-MUX is enabled in all the contents.
6675 return true;
6676}
6677
6678bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006679 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006680}
6681
Steve Anton06817cd2018-12-18 15:55:30 -08006682static RTCError ValidateMids(const cricket::SessionDescription& description) {
6683 std::set<std::string> mids;
6684 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006685 if (content.name.empty()) {
6686 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6687 "A media section is missing a MID attribute.");
6688 }
Steve Anton06817cd2018-12-18 15:55:30 -08006689 if (!mids.insert(content.name).second) {
6690 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6691 "Duplicate a=mid value '" + content.name + "'.");
6692 }
6693 }
6694 return RTCError::OK();
6695}
6696
Steve Anton8a006912017-12-04 15:25:56 -08006697RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006698 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006699 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006700 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006701 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006702 }
6703
6704 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006705 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006706 }
6707
Steve Anton3828c062017-12-06 10:34:51 -08006708 SdpType type = sdesc->GetType();
6709 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6710 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006711 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006712 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006713 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006714 }
6715
Steve Anton06817cd2018-12-18 15:55:30 -08006716 RTCError error = ValidateMids(*sdesc->description());
6717 if (!error.ok()) {
6718 return error;
6719 }
6720
Steve Anton75737c02017-11-06 10:37:17 -08006721 // Verify crypto settings.
6722 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006723 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6724 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006725 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006726 if (!crypto_error.ok()) {
6727 return crypto_error;
6728 }
Steve Anton75737c02017-11-06 10:37:17 -08006729 }
6730
6731 // Verify ice-ufrag and ice-pwd.
6732 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006733 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6734 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006735 }
6736
6737 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006738 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6739 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006740 }
6741
6742 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6743 // m-lines that do not rtcp-mux enabled.
6744
6745 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006746 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006747 // With an answer we want to compare the new answer session description with
6748 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006749 const cricket::SessionDescription* offer_desc =
6750 (source == cricket::CS_LOCAL) ? remote_description()->description()
6751 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006752 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6753 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6754 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006755 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6756 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006757 }
6758 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006759 // The re-offers should respect the order of m= sections in current
6760 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006761 // With a re-offer, either the current local or current remote descriptions
6762 // could be the most up to date, so we would like to check against both of
6763 // them if they exist. It could be the case that one of them has a 0 port
6764 // for a media section, but the other does not. This is important to check
6765 // against in the case that we are recycling an m= section.
6766 const cricket::SessionDescription* current_desc = nullptr;
6767 const cricket::SessionDescription* secondary_current_desc = nullptr;
6768 if (local_description()) {
6769 current_desc = local_description()->description();
6770 if (remote_description()) {
6771 secondary_current_desc = remote_description()->description();
6772 }
6773 } else if (remote_description()) {
6774 current_desc = remote_description()->description();
6775 }
Steve Anton75737c02017-11-06 10:37:17 -08006776 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006777 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6778 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006779 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6780 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006781 }
6782 }
6783
Steve Antonba42e992018-04-09 14:10:01 -07006784 if (IsUnifiedPlan()) {
6785 // Ensure that each audio and video media section has at most one
6786 // "StreamParams". This will return an error if receiving a session
6787 // description from a "Plan B" endpoint which adds multiple tracks of the
6788 // same type. With Unified Plan, there can only be at most one track per
6789 // media section.
6790 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006791 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006792 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6793 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6794 desc.streams().size() > 1u) {
6795 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6796 "Media section has more than one track specified "
6797 "with a=ssrc lines which is not supported with "
6798 "Unified Plan.");
6799 }
6800 }
6801 }
6802
Steve Anton8a006912017-12-04 15:25:56 -08006803 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006804}
6805
Steve Anton3828c062017-12-06 10:34:51 -08006806bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006807 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006808 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006809 return (state == PeerConnectionInterface::kStable) ||
6810 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006811 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006812 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006813 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6814 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6815 }
6816}
6817
Steve Anton3828c062017-12-06 10:34:51 -08006818bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006819 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006820 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006821 return (state == PeerConnectionInterface::kStable) ||
6822 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006823 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006824 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006825 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6826 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6827 }
6828}
6829
Steve Antonf8470812017-12-04 10:46:21 -08006830const char* PeerConnection::SessionErrorToString(SessionError error) const {
6831 switch (error) {
6832 case SessionError::kNone:
6833 return "ERROR_NONE";
6834 case SessionError::kContent:
6835 return "ERROR_CONTENT";
6836 case SessionError::kTransport:
6837 return "ERROR_TRANSPORT";
6838 }
6839 RTC_NOTREACHED();
6840 return "";
6841}
6842
Steve Anton75737c02017-11-06 10:37:17 -08006843std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006844 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006845 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6846 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006847 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006848}
6849
Steve Anton8e20f172018-03-06 10:55:04 -08006850void PeerConnection::ReportSdpFormatReceived(
6851 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006852 int num_audio_mlines = 0;
6853 int num_video_mlines = 0;
6854 int num_audio_tracks = 0;
6855 int num_video_tracks = 0;
6856 for (const ContentInfo& content : remote_offer.description()->contents()) {
6857 cricket::MediaType media_type = content.media_description()->type();
6858 int num_tracks = std::max(
6859 1, static_cast<int>(content.media_description()->streams().size()));
6860 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6861 num_audio_mlines += 1;
6862 num_audio_tracks += num_tracks;
6863 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6864 num_video_mlines += 1;
6865 num_video_tracks += num_tracks;
6866 }
6867 }
6868 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6869 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6870 format = kSdpFormatReceivedComplexUnifiedPlan;
6871 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6872 format = kSdpFormatReceivedComplexPlanB;
6873 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6874 format = kSdpFormatReceivedSimple;
6875 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006876 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6877 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006878}
6879
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006880void PeerConnection::NoteUsageEvent(UsageEvent event) {
6881 RTC_DCHECK_RUN_ON(signaling_thread());
6882 usage_event_accumulator_ |= static_cast<int>(event);
6883}
6884
6885void PeerConnection::ReportUsagePattern() const {
6886 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006887 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6888 usage_event_accumulator_,
6889 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006890 const int bad_bits =
6891 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6892 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6893 const int good_bits =
6894 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6895 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6896 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6897 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6898 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006899 // If called after close(), we can't report, because observer may have
6900 // been deallocated, and therefore pointer is null. Write to log instead.
6901 if (observer_) {
6902 Observer()->OnInterestingUsage(usage_event_accumulator_);
6903 } else {
6904 RTC_LOG(LS_INFO) << "Interesting usage signature "
6905 << usage_event_accumulator_
6906 << " observed after observer shutdown";
6907 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006908 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006909}
6910
Steve Anton0ffaaa22018-02-23 10:31:30 -08006911void PeerConnection::ReportNegotiatedSdpSemantics(
6912 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006913 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006914 switch (answer.description()->msid_signaling()) {
6915 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006916 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006917 break;
6918 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006919 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006920 break;
6921 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006922 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006923 break;
6924 case cricket::kMsidSignalingMediaSection |
6925 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006926 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006927 break;
6928 default:
6929 RTC_NOTREACHED();
6930 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006931 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6932 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006933}
6934
Steve Anton75737c02017-11-06 10:37:17 -08006935// We need to check the local/remote description for the Transport instead of
6936// the session, because a new Transport added during renegotiation may have
6937// them unset while the session has them set from the previous negotiation.
6938// Not doing so may trigger the auto generation of transport description and
6939// mess up DTLS identity information, ICE credential, etc.
6940bool PeerConnection::ReadyToUseRemoteCandidate(
6941 const IceCandidateInterface* candidate,
6942 const SessionDescriptionInterface* remote_desc,
6943 bool* valid) {
6944 *valid = true;
6945
6946 const SessionDescriptionInterface* current_remote_desc =
6947 remote_desc ? remote_desc : remote_description();
6948
6949 if (!current_remote_desc) {
6950 return false;
6951 }
6952
Guido Urdaneta41633172019-05-23 20:12:29 +02006953 RTCErrorOr<const cricket::ContentInfo*> result =
6954 FindContentInfo(current_remote_desc, candidate);
6955 if (!result.ok()) {
6956 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6957 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006958
6959 *valid = false;
6960 return false;
6961 }
6962
Guido Urdaneta41633172019-05-23 20:12:29 +02006963 std::string transport_name = GetTransportName(result.value()->name);
6964 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006965}
6966
6967bool PeerConnection::SrtpRequired() const {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006968 return !configuration_.use_datagram_transport &&
6969 (dtls_enabled_ ||
6970 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006971}
6972
6973void PeerConnection::OnTransportControllerGatheringState(
6974 cricket::IceGatheringState state) {
6975 RTC_DCHECK(signaling_thread()->IsCurrent());
6976 if (state == cricket::kIceGatheringGathering) {
6977 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6978 } else if (state == cricket::kIceGatheringComplete) {
6979 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6980 }
6981}
6982
6983void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006984 std::map<std::string, std::set<cricket::MediaType>>
6985 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006986 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006987 if (transceiver->internal()->channel()) {
6988 const std::string& transport_name =
6989 transceiver->internal()->channel()->transport_name();
6990 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006991 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006992 }
Steve Anton75737c02017-11-06 10:37:17 -08006993 }
6994 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006995 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6996 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006997 }
Zhi Huange830e682018-03-30 10:48:35 -07006998
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006999 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007000 if (transport_name) {
7001 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007002 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007003 }
Zhi Huange830e682018-03-30 10:48:35 -07007004
Steve Antonc7b964c2018-02-01 14:39:45 -08007005 for (const auto& entry : media_types_by_transport_name) {
7006 const std::string& transport_name = entry.first;
7007 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007008 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007009 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007010 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007011 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007012 }
7013 }
7014}
7015// Walk through the ConnectionInfos to gather best connection usage
7016// for IPv4 and IPv6.
7017void PeerConnection::ReportBestConnectionState(
7018 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007019 for (const cricket::TransportChannelStats& channel_stats :
7020 stats.channel_stats) {
7021 for (const cricket::ConnectionInfo& connection_info :
7022 channel_stats.connection_infos) {
7023 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007024 continue;
7025 }
7026
Steve Antonc7b964c2018-02-01 14:39:45 -08007027 const cricket::Candidate& local = connection_info.local_candidate;
7028 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007029
7030 // Increment the counter for IceCandidatePairType.
7031 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7032 (local.type() == RELAY_PORT_TYPE &&
7033 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007034 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7035 GetIceCandidatePairCounter(local, remote),
7036 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007037 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007038 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7039 GetIceCandidatePairCounter(local, remote),
7040 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007041 } else {
7042 RTC_CHECK(0);
7043 }
Steve Anton75737c02017-11-06 10:37:17 -08007044
7045 // Increment the counter for IP type.
7046 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007047 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7048 kBestConnections_IPv4,
7049 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007050 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007051 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7052 kBestConnections_IPv6,
7053 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007054 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007055 RTC_CHECK(!local.address().hostname().empty() &&
7056 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007057 }
7058
7059 return;
7060 }
7061 }
7062}
7063
7064void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007065 const cricket::TransportStats& stats,
7066 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007067 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7068 return;
7069 }
7070
7071 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7072 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7073 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7074 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7075 return;
7076 }
7077
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007078 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7079 for (cricket::MediaType media_type : media_types) {
7080 switch (media_type) {
7081 case cricket::MEDIA_TYPE_AUDIO:
7082 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7083 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7084 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7085 break;
7086 case cricket::MEDIA_TYPE_VIDEO:
7087 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7088 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7089 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7090 break;
7091 case cricket::MEDIA_TYPE_DATA:
7092 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7093 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7094 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7095 break;
7096 default:
7097 RTC_NOTREACHED();
7098 continue;
7099 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007100 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007101 }
7102
7103 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7104 for (cricket::MediaType media_type : media_types) {
7105 switch (media_type) {
7106 case cricket::MEDIA_TYPE_AUDIO:
7107 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7108 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7109 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7110 break;
7111 case cricket::MEDIA_TYPE_VIDEO:
7112 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7113 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7114 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7115 break;
7116 case cricket::MEDIA_TYPE_DATA:
7117 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7118 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7119 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7120 break;
7121 default:
7122 RTC_NOTREACHED();
7123 continue;
7124 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007125 }
Steve Anton75737c02017-11-06 10:37:17 -08007126 }
7127}
7128
7129void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007130 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007131 RTC_DCHECK(call_);
7132 call_->OnSentPacket(sent_packet);
7133}
7134
7135const std::string PeerConnection::GetTransportName(
7136 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007137 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007138 if (channel) {
7139 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007140 }
Steve Anton6fec8802017-12-04 10:37:29 -08007141 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007142 RTC_DCHECK(sctp_mid_);
7143 if (content_name == *sctp_mid_) {
7144 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007145 }
7146 }
7147 // Return an empty string if failed to retrieve the transport name.
7148 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007149}
7150
Steve Anton6fec8802017-12-04 10:37:29 -08007151void PeerConnection::DestroyTransceiverChannel(
7152 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7153 transceiver) {
7154 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007155
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007156 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007157 if (channel) {
7158 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007159 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007160 }
7161}
7162
7163void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007164 if (rtp_data_channel_) {
7165 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007166 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007167 rtp_data_channel_ = nullptr;
7168 }
7169
7170 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7171 // grab a reference to this PeerConnection. If this is called from the
7172 // PeerConnection destructor, the RefCountedObject vtable will have already
7173 // been destroyed (since it is a subclass of PeerConnection) and using
7174 // rtc::Bind will cause "Pure virtual function called" error to appear.
7175
7176 if (sctp_transport_) {
7177 OnDataChannelDestroyed();
7178 network_thread()->Invoke<void>(RTC_FROM_HERE,
7179 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007180 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007181 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007182
7183 if (media_transport_) {
7184 OnDataChannelDestroyed();
7185 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7186 RTC_DCHECK_RUN_ON(network_thread());
7187 TeardownMediaTransportForDataChannels_n();
7188 });
7189 }
Steve Anton6fec8802017-12-04 10:37:29 -08007190}
7191
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007192void PeerConnection::DestroyChannelInterface(
7193 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007194 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007195 switch (channel->media_type()) {
7196 case cricket::MEDIA_TYPE_AUDIO:
7197 channel_manager()->DestroyVoiceChannel(
7198 static_cast<cricket::VoiceChannel*>(channel));
7199 break;
7200 case cricket::MEDIA_TYPE_VIDEO:
7201 channel_manager()->DestroyVideoChannel(
7202 static_cast<cricket::VideoChannel*>(channel));
7203 break;
7204 case cricket::MEDIA_TYPE_DATA:
7205 channel_manager()->DestroyRtpDataChannel(
7206 static_cast<cricket::RtpDataChannel*>(channel));
7207 break;
7208 default:
7209 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7210 break;
7211 }
Zhi Huange830e682018-03-30 10:48:35 -07007212}
Steve Anton6fec8802017-12-04 10:37:29 -08007213
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007214bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007215 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007216 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007217 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007218 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007219 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007220 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007221 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007222 auto base_channel = GetChannel(mid);
7223 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007224 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007225 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007226 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007227 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007228 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007229
Karl Wiberg5966c502019-02-21 23:55:09 +01007230 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007231 // Only pass media transport to call object if media transport is used
7232 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007233 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007234 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007235
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007236 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007237}
7238
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007239void PeerConnection::OnSetStreams() {
7240 RTC_DCHECK_RUN_ON(signaling_thread());
7241 if (IsUnifiedPlan())
7242 UpdateNegotiationNeeded();
7243}
7244
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007245PeerConnectionObserver* PeerConnection::Observer() const {
7246 // In earlier production code, the pointer was not cleared on close,
7247 // which might have led to undefined behavior if the observer was not
7248 // deallocated, or strange crashes if it was.
7249 // We use CHECK in order to catch such behavior if it exists.
7250 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7251 RTC_CHECK(observer_);
7252 return observer_;
7253}
7254
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007255CryptoOptions PeerConnection::GetCryptoOptions() {
7256 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7257 // after it has been removed.
7258 return configuration_.crypto_options.has_value()
7259 ? *configuration_.crypto_options
7260 : factory_->options().crypto_options;
7261}
7262
Harald Alvestrand89061872018-01-02 14:08:34 +01007263void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007264 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007265 if (stats_collector_) {
7266 stats_collector_->ClearCachedStatsReport();
7267 }
7268}
7269
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007270void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007271 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7272 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007273}
7274
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007275void PeerConnection::UpdateNegotiationNeeded() {
7276 RTC_DCHECK_RUN_ON(signaling_thread());
7277 if (!IsUnifiedPlan()) {
7278 Observer()->OnRenegotiationNeeded();
7279 return;
7280 }
7281
7282 // If connection's [[IsClosed]] slot is true, abort these steps.
7283 if (IsClosed())
7284 return;
7285
7286 // If connection's signaling state is not "stable", abort these steps.
7287 if (signaling_state() != kStable)
7288 return;
7289
7290 // NOTE
7291 // The negotiation-needed flag will be updated once the state transitions to
7292 // "stable", as part of the steps for setting an RTCSessionDescription.
7293
7294 // If the result of checking if negotiation is needed is false, clear the
7295 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7296 // to false, and abort these steps.
7297 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7298 if (!is_negotiation_needed) {
7299 is_negotiation_needed_ = false;
7300 return;
7301 }
7302
7303 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7304 // steps.
7305 if (is_negotiation_needed_)
7306 return;
7307
7308 // Set connection's [[NegotiationNeeded]] slot to true.
7309 is_negotiation_needed_ = true;
7310
7311 // Queue a task that runs the following steps:
7312 // If connection's [[IsClosed]] slot is true, abort these steps.
7313 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7314 // Fire an event named negotiationneeded at connection.
7315 Observer()->OnRenegotiationNeeded();
7316}
7317
7318bool PeerConnection::CheckIfNegotiationIsNeeded() {
7319 RTC_DCHECK_RUN_ON(signaling_thread());
7320 // 1. If any implementation-specific negotiation is required, as described at
7321 // the start of this section, return true.
7322
7323 // 2. Let description be connection.[[CurrentLocalDescription]].
7324 const SessionDescriptionInterface* description = current_local_description();
7325 if (!description)
7326 return true;
7327
7328 // 3. If connection has created any RTCDataChannels, and no m= section in
7329 // description has been negotiated yet for data, return true.
7330 if (!sctp_data_channels_.empty()) {
7331 if (!cricket::GetFirstDataContent(description->description()->contents()))
7332 return true;
7333 }
7334
7335 // 4. For each transceiver in connection's set of transceivers, perform the
7336 // following checks:
7337 for (const auto& transceiver : transceivers_) {
7338 const ContentInfo* current_local_msection =
7339 FindTransceiverMSection(transceiver.get(), description);
7340
7341 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7342 transceiver.get(), current_remote_description());
7343
7344 // 4.3 If transceiver is stopped and is associated with an m= section,
7345 // but the associated m= section is not yet rejected in
7346 // connection.[[CurrentLocalDescription]] or
7347 // connection.[[CurrentRemoteDescription]], return true.
7348 if (transceiver->stopped()) {
7349 if (current_local_msection && !current_local_msection->rejected &&
7350 ((current_remote_msection && !current_remote_msection->rejected) ||
7351 !current_remote_msection)) {
7352 return true;
7353 }
7354 continue;
7355 }
7356
7357 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7358 // section in description, return true.
7359 if (!current_local_msection)
7360 return true;
7361
7362 const MediaContentDescription* current_local_media_description =
7363 current_local_msection->media_description();
7364 // 4.2 If transceiver isn't stopped and is associated with an m= section
7365 // in description then perform the following checks:
7366
7367 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7368 // associated m= section in description either doesn't contain a single
7369 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7370 // m= section, or the MSID values themselves, differ from what is in
7371 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7372 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7373 if (current_local_media_description->streams().size() == 0)
7374 return true;
7375
7376 std::vector<std::string> msection_msids;
7377 for (const auto& stream : current_local_media_description->streams()) {
7378 for (const std::string& msid : stream.stream_ids())
7379 msection_msids.push_back(msid);
7380 }
7381
7382 std::vector<std::string> transceiver_msids =
7383 transceiver->sender()->stream_ids();
7384 if (msection_msids.size() != transceiver_msids.size())
7385 return true;
7386
7387 absl::c_sort(transceiver_msids);
7388 absl::c_sort(msection_msids);
7389 if (transceiver_msids != msection_msids)
7390 return true;
7391 }
7392
7393 // 4.2.2 If description is of type "offer", and the direction of the
7394 // associated m= section in neither connection.[[CurrentLocalDescription]]
7395 // nor connection.[[CurrentRemoteDescription]] matches
7396 // transceiver.[[Direction]], return true.
7397 if (description->GetType() == SdpType::kOffer) {
7398 if (!current_remote_description())
7399 return true;
7400
7401 if (!current_remote_msection)
7402 return true;
7403
7404 RtpTransceiverDirection current_local_direction =
7405 current_local_media_description->direction();
7406 RtpTransceiverDirection current_remote_direction =
7407 current_remote_msection->media_description()->direction();
7408 if (transceiver->direction() != current_local_direction &&
7409 transceiver->direction() !=
7410 RtpTransceiverDirectionReversed(current_remote_direction)) {
7411 return true;
7412 }
7413 }
7414
7415 // 4.2.3 If description is of type "answer", and the direction of the
7416 // associated m= section in the description does not match
7417 // transceiver.[[Direction]] intersected with the offered direction (as
7418 // described in [JSEP] (section 5.3.1.)), return true.
7419 if (description->GetType() == SdpType::kAnswer) {
7420 if (!remote_description())
7421 return true;
7422
7423 const ContentInfo* offered_remote_msection =
7424 FindTransceiverMSection(transceiver.get(), remote_description());
7425
7426 RtpTransceiverDirection offered_direction =
7427 offered_remote_msection
7428 ? offered_remote_msection->media_description()->direction()
7429 : RtpTransceiverDirection::kInactive;
7430
7431 if (current_local_media_description->direction() !=
7432 (RtpTransceiverDirectionIntersection(
7433 transceiver->direction(),
7434 RtpTransceiverDirectionReversed(offered_direction)))) {
7435 return true;
7436 }
7437 }
7438 }
7439
7440 // If all the preceding checks were performed and true was not returned,
7441 // nothing remains to be negotiated; return false.
7442 return false;
7443}
7444
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007445} // namespace webrtc