blob: e677e5d4dfb4b02c0c64076e82743e694b057bee [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
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700110// Field trials.
111// Controls datagram transport support.
112const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
113
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800114// UMA metric names.
115const char kSimulcastVersionApplyLocalDescription[] =
116 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
117const char kSimulcastVersionApplyRemoteDescription[] =
118 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
119const char kSimulcastNumberOfEncodings[] =
120 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
121const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
122
Seth Hampson845e8782018-03-02 11:34:10 -0800123static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800124static const char kDefaultAudioSenderId[] = "defaulta0";
125static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700126
zhihuang8f65cdf2016-05-06 18:40:30 -0700127// The length of RTCP CNAMEs.
128static const int kRtcpCnameLength = 16;
129
Steve Antonad182762018-09-05 20:22:40 +0000130enum {
131 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
132 MSG_SET_SESSIONDESCRIPTION_FAILED,
133 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
134 MSG_GETSTATS,
135 MSG_FREE_DATACHANNELS,
136 MSG_REPORT_USAGE_PATTERN,
137};
138
Harald Alvestrand19793842018-06-25 12:03:50 +0200139static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
140
Steve Antonad182762018-09-05 20:22:40 +0000141struct SetSessionDescriptionMsg : public rtc::MessageData {
142 explicit SetSessionDescriptionMsg(
143 webrtc::SetSessionDescriptionObserver* observer)
144 : observer(observer) {}
145
146 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
147 RTCError error;
148};
149
150struct CreateSessionDescriptionMsg : public rtc::MessageData {
151 explicit CreateSessionDescriptionMsg(
152 webrtc::CreateSessionDescriptionObserver* observer)
153 : observer(observer) {}
154
155 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
156 RTCError error;
157};
158
159struct GetStatsMsg : public rtc::MessageData {
160 GetStatsMsg(webrtc::StatsObserver* observer,
161 webrtc::MediaStreamTrackInterface* track)
162 : observer(observer), track(track) {}
163 rtc::scoped_refptr<webrtc::StatsObserver> observer;
164 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
165};
166
deadbeefab9b2d12015-10-14 11:33:11 -0700167// Check if we can send |new_stream| on a PeerConnection.
168bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
169 webrtc::MediaStreamInterface* new_stream) {
170 if (!new_stream || !current_streams) {
171 return false;
172 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700173 if (current_streams->find(new_stream->id()) != nullptr) {
174 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100175 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700176 return false;
177 }
178 return true;
179}
180
deadbeef5e97fb52015-10-15 12:49:08 -0700181// If the direction is "recvonly" or "inactive", treat the description
182// as containing no streams.
183// See: https://code.google.com/p/webrtc/issues/detail?id=5054
184std::vector<cricket::StreamParams> GetActiveStreams(
185 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800186 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700187 ? desc->streams()
188 : std::vector<cricket::StreamParams>();
189}
190
deadbeefab9b2d12015-10-14 11:33:11 -0700191bool IsValidOfferToReceiveMedia(int value) {
192 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
193 return (value >= Options::kUndefined) &&
194 (value <= Options::kMaxOfferToReceiveMedia);
195}
196
zhihuang1c378ed2017-08-17 14:10:50 -0700197// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800198void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700199 const std::vector<rtc::scoped_refptr<
200 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700201 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200202 cricket::MediaDescriptionOptions* video_media_description_options,
203 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700204 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
206 if (audio_media_description_options) {
207 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700208 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700209 }
210 } else {
211 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
212 if (video_media_description_options) {
213 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800214 sender->id(), sender->internal()->stream_ids(), {},
215 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700216 }
217 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700218 }
zhihuang1c378ed2017-08-17 14:10:50 -0700219}
olka3c747662017-08-17 06:50:32 -0700220
zhihuang1c378ed2017-08-17 14:10:50 -0700221// Add options to |session_options| from |rtp_data_channels|.
222void AddRtpDataChannelOptions(
223 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
224 rtp_data_channels,
225 cricket::MediaDescriptionOptions* data_media_description_options) {
226 if (!data_media_description_options) {
227 return;
228 }
deadbeefab9b2d12015-10-14 11:33:11 -0700229 // Check for data channels.
230 for (const auto& kv : rtp_data_channels) {
231 const DataChannel* channel = kv.second;
232 if (channel->state() == DataChannel::kConnecting ||
233 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700234 // Legacy RTP data channels are signaled with the track/stream ID set to
235 // the data channel's label.
236 data_media_description_options->AddRtpDataChannel(channel->label(),
237 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700238 }
239 }
240}
241
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700242uint32_t ConvertIceTransportTypeToCandidateFilter(
243 PeerConnectionInterface::IceTransportsType type) {
244 switch (type) {
245 case PeerConnectionInterface::kNone:
246 return cricket::CF_NONE;
247 case PeerConnectionInterface::kRelay:
248 return cricket::CF_RELAY;
249 case PeerConnectionInterface::kNoHost:
250 return (cricket::CF_ALL & ~cricket::CF_HOST);
251 case PeerConnectionInterface::kAll:
252 return cricket::CF_ALL;
253 default:
nissec80e7412017-01-11 05:56:46 -0800254 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700255 }
256 return cricket::CF_NONE;
257}
258
deadbeef293e9262017-01-11 12:28:30 -0800259// Helper to set an error and return from a method.
260bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
261 if (error) {
262 error->set_type(type);
263 }
264 return type == webrtc::RTCErrorType::NONE;
265}
266
Steve Anton038834f2017-07-14 15:59:59 -0700267bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700269 if (error_out) {
270 *error_out = std::move(error);
271 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700272 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700273}
274
Steve Antonba818672017-11-06 10:21:57 -0800275std::string GetSignalingStateString(
276 PeerConnectionInterface::SignalingState state) {
277 switch (state) {
278 case PeerConnectionInterface::kStable:
279 return "kStable";
280 case PeerConnectionInterface::kHaveLocalOffer:
281 return "kHaveLocalOffer";
282 case PeerConnectionInterface::kHaveLocalPrAnswer:
283 return "kHavePrAnswer";
284 case PeerConnectionInterface::kHaveRemoteOffer:
285 return "kHaveRemoteOffer";
286 case PeerConnectionInterface::kHaveRemotePrAnswer:
287 return "kHaveRemotePrAnswer";
288 case PeerConnectionInterface::kClosed:
289 return "kClosed";
290 }
291 RTC_NOTREACHED();
292 return "";
293}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700294
Steve Anton75737c02017-11-06 10:37:17 -0800295IceCandidatePairType GetIceCandidatePairCounter(
296 const cricket::Candidate& local,
297 const cricket::Candidate& remote) {
298 const auto& l = local.type();
299 const auto& r = remote.type();
300 const auto& host = LOCAL_PORT_TYPE;
301 const auto& srflx = STUN_PORT_TYPE;
302 const auto& relay = RELAY_PORT_TYPE;
303 const auto& prflx = PRFLX_PORT_TYPE;
304 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800305 bool local_hostname =
306 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
307 bool remote_hostname = !remote.address().hostname().empty() &&
308 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800309 bool local_private = IPIsPrivate(local.address().ipaddr());
310 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800311 if (local_hostname) {
312 if (remote_hostname) {
313 return kIceCandidatePairHostNameHostName;
314 } else if (remote_private) {
315 return kIceCandidatePairHostNameHostPrivate;
316 } else {
317 return kIceCandidatePairHostNameHostPublic;
318 }
319 } else if (local_private) {
320 if (remote_hostname) {
321 return kIceCandidatePairHostPrivateHostName;
322 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800323 return kIceCandidatePairHostPrivateHostPrivate;
324 } else {
325 return kIceCandidatePairHostPrivateHostPublic;
326 }
327 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800328 if (remote_hostname) {
329 return kIceCandidatePairHostPublicHostName;
330 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800331 return kIceCandidatePairHostPublicHostPrivate;
332 } else {
333 return kIceCandidatePairHostPublicHostPublic;
334 }
335 }
336 }
337 if (l == host && r == srflx)
338 return kIceCandidatePairHostSrflx;
339 if (l == host && r == relay)
340 return kIceCandidatePairHostRelay;
341 if (l == host && r == prflx)
342 return kIceCandidatePairHostPrflx;
343 if (l == srflx && r == host)
344 return kIceCandidatePairSrflxHost;
345 if (l == srflx && r == srflx)
346 return kIceCandidatePairSrflxSrflx;
347 if (l == srflx && r == relay)
348 return kIceCandidatePairSrflxRelay;
349 if (l == srflx && r == prflx)
350 return kIceCandidatePairSrflxPrflx;
351 if (l == relay && r == host)
352 return kIceCandidatePairRelayHost;
353 if (l == relay && r == srflx)
354 return kIceCandidatePairRelaySrflx;
355 if (l == relay && r == relay)
356 return kIceCandidatePairRelayRelay;
357 if (l == relay && r == prflx)
358 return kIceCandidatePairRelayPrflx;
359 if (l == prflx && r == host)
360 return kIceCandidatePairPrflxHost;
361 if (l == prflx && r == srflx)
362 return kIceCandidatePairPrflxSrflx;
363 if (l == prflx && r == relay)
364 return kIceCandidatePairPrflxRelay;
365 return kIceCandidatePairMax;
366}
367
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368// Logic to decide if an m= section can be recycled. This means that the new
369// m= section is not rejected, but the old local or remote m= section is
370// rejected. |old_content_one| and |old_content_two| refer to the m= section
371// of the old remote and old local descriptions in no particular order.
372// We need to check both the old local and remote because either
373// could be the most current from the latest negotation.
374bool IsMediaSectionBeingRecycled(SdpType type,
375 const ContentInfo& content,
376 const ContentInfo* old_content_one,
377 const ContentInfo* old_content_two) {
378 return type == SdpType::kOffer && !content.rejected &&
379 ((old_content_one && old_content_one->rejected) ||
380 (old_content_two && old_content_two->rejected));
381}
382
Steve Anton75737c02017-11-06 10:37:17 -0800383// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800384// |current_desc|. The number of m= sections in |new_desc| should be no
385// less than |current_desc|. In the case of checking an answer's
386// |new_desc|, the |current_desc| is the last offer that was set as the
387// local or remote. In the case of checking an offer's |new_desc| we
388// check against the local and remote descriptions stored from the last
389// negotiation, because either of these could be the most up to date for
390// possible rejected m sections. These are the |current_desc| and
391// |secondary_current_desc|.
392bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
393 const SessionDescription* secondary_current_desc,
394 const SessionDescription& new_desc,
395 const SdpType type) {
396 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800400 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
401 const cricket::ContentInfo* secondary_content_info = nullptr;
402 if (secondary_current_desc &&
403 i < secondary_current_desc->contents().size()) {
404 secondary_content_info = &secondary_current_desc->contents()[i];
405 }
406 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
407 &current_desc.contents()[i],
408 secondary_content_info)) {
409 // For new offer descriptions, if the media section can be recycled, it's
410 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800411 continue;
412 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800414 return false;
415 }
416 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800417 new_desc.contents()[i].media_description();
418 const MediaContentDescription* current_desc_mdesc =
419 current_desc.contents()[i].media_description();
420 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800421 return false;
422 }
423 }
424 return true;
425}
426
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800427bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
428 const SessionDescription& desc2) {
429 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800430}
431
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700432void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
433 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200434 // Array of structs needed to map {KeyExchangeProtocolType,
435 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
436 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
437 static constexpr struct {
438 KeyExchangeProtocolType protocol_type;
439 cricket::MediaType media_type;
440 KeyExchangeProtocolMedia protocol_media;
441 } kEnumCounterKeyProtocolMediaMap[] = {
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
443 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
444 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
445 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
446 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
447 kEnumCounterKeyProtocolMediaTypeDtlsData},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
449 kEnumCounterKeyProtocolMediaTypeSdesAudio},
450 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
451 kEnumCounterKeyProtocolMediaTypeSdesVideo},
452 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
453 kEnumCounterKeyProtocolMediaTypeSdesData},
454 };
455
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700456 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
457 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100458
Mirko Bonadeiab499822018-09-11 10:43:20 +0200459 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
460 if (i.protocol_type == protocol_type && i.media_type == media_type) {
461 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
462 i.protocol_media,
463 kEnumCounterKeyProtocolMediaTypeMax);
464 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100465 }
466}
467
Harald Alvestrand76829d72018-07-18 23:24:36 +0200468void NoteAddIceCandidateResult(int result) {
469 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
470 kAddIceCandidateMax);
471}
472
Steve Anton75737c02017-11-06 10:37:17 -0800473// Checks that each non-rejected content has SDES crypto keys or a DTLS
474// fingerprint, unless it's in a BUNDLE group, in which case only the
475// BUNDLE-tag section (first media section/description in the BUNDLE group)
476// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
477// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
478// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700479RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 const cricket::ContentGroup* bundle =
481 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800482 for (const cricket::ContentInfo& content_info : desc->contents()) {
483 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800484 continue;
485 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100486 // Note what media is used with each crypto protocol, for all sections.
487 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
488 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700489 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800490 const std::string& mid = content_info.name;
491 if (bundle && bundle->HasContentName(mid) &&
492 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 // This isn't the first media section in the BUNDLE group, so it's not
494 // required to have crypto attributes, since only the crypto attributes
495 // from the first section actually get used.
496 continue;
497 }
498
499 // If the content isn't rejected or bundled into another m= section, crypto
500 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800501 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800502 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800503 if (!media || !tinfo) {
504 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800506 }
507 if (dtls_enabled) {
508 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_WARNING)
510 << "Session description must have DTLS fingerprint if "
511 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800512 return RTCError(RTCErrorType::INVALID_PARAMETER,
513 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800514 }
515 } else {
516 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100517 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800518 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800520 }
521 }
522 }
Steve Anton8a006912017-12-04 15:25:56 -0800523 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800524}
525
526// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
527// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
528// media section/description in the BUNDLE group) needs a ufrag and pwd.
529bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
530 const cricket::ContentGroup* bundle =
531 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800532 for (const cricket::ContentInfo& content_info : desc->contents()) {
533 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800534 continue;
535 }
Steve Anton8a006912017-12-04 15:25:56 -0800536 const std::string& mid = content_info.name;
537 if (bundle && bundle->HasContentName(mid) &&
538 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800539 // This isn't the first media section in the BUNDLE group, so it's not
540 // required to have ufrag/password, since only the ufrag/password from
541 // the first section actually get used.
542 continue;
543 }
544
545 // If the content isn't rejected or bundled into another m= section,
546 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800547 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800548 if (!tinfo) {
549 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100550 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800551 return false;
552 }
553 if (tinfo->description.ice_ufrag.empty() ||
554 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100555 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800556 return false;
557 }
558 }
559 return true;
560}
561
Steve Anton75737c02017-11-06 10:37:17 -0800562// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
563bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
564 const SessionDescriptionInterface* new_desc,
565 const std::string& content_name) {
566 if (!old_desc) {
567 return false;
568 }
569 const SessionDescription* new_sd = new_desc->description();
570 const SessionDescription* old_sd = old_desc->description();
571 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
572 if (!cinfo || cinfo->rejected) {
573 return false;
574 }
575 // If the content isn't rejected, check if ufrag and password has changed.
576 const cricket::TransportDescription* new_transport_desc =
577 new_sd->GetTransportDescriptionByName(content_name);
578 const cricket::TransportDescription* old_transport_desc =
579 old_sd->GetTransportDescriptionByName(content_name);
580 if (!new_transport_desc || !old_transport_desc) {
581 // No transport description exists. This is not an ICE restart.
582 return false;
583 }
584 if (cricket::IceCredentialsChanged(
585 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
586 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100587 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
588 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800589 return true;
590 }
591 return false;
592}
593
Steve Anton80dd7b52018-02-16 17:08:42 -0800594// Generates a string error message for SetLocalDescription/SetRemoteDescription
595// from an RTCError.
596std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
597 SdpType type,
598 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200599 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800600 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
601 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200602 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800603}
604
Seth Hampson5b4f0752018-04-02 16:31:36 -0700605std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
606 std::string output = "streams=[";
607 const char* separator = "";
608 for (const auto& stream_id : stream_ids) {
609 output.append(separator).append(stream_id);
610 separator = ", ";
611 }
612 output.append("]");
613 return output;
614}
615
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 int rtc_configuration_parameter) {
618 if (rtc_configuration_parameter ==
619 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200620 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700621 }
622 return rtc_configuration_parameter;
623}
624
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800625cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
626 switch (type) {
627 case DataMessageType::kText:
628 return cricket::DMT_TEXT;
629 case DataMessageType::kBinary:
630 return cricket::DMT_BINARY;
631 case DataMessageType::kControl:
632 return cricket::DMT_CONTROL;
633 default:
634 return cricket::DMT_NONE;
635 }
636 return cricket::DMT_NONE;
637}
638
639DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
640 switch (type) {
641 case cricket::DMT_TEXT:
642 return DataMessageType::kText;
643 case cricket::DMT_BINARY:
644 return DataMessageType::kBinary;
645 case cricket::DMT_CONTROL:
646 return DataMessageType::kControl;
647 case cricket::DMT_NONE:
648 default:
649 RTC_NOTREACHED();
650 }
651 return DataMessageType::kControl;
652}
653
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800654void ReportSimulcastApiVersion(const char* name,
655 const SessionDescription& session) {
656 bool has_legacy = false;
657 bool has_spec_compliant = false;
658 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200659 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800660 continue;
661 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200662 has_spec_compliant |= content.media_description()->HasSimulcast();
663 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800664 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
665 }
666 }
667
668 if (has_legacy) {
669 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
670 kSimulcastApiVersionMax);
671 }
672 if (has_spec_compliant) {
673 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
674 kSimulcastApiVersionMax);
675 }
676 if (!has_legacy && !has_spec_compliant) {
677 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
678 kSimulcastApiVersionMax);
679 }
680}
681
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200682const ContentInfo* FindTransceiverMSection(
683 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
684 const SessionDescriptionInterface* session_description) {
685 return transceiver->mid()
686 ? session_description->description()->GetContentByName(
687 *transceiver->mid())
688 : nullptr;
689}
690
Steve Anton75737c02017-11-06 10:37:17 -0800691} // namespace
692
Henrik Boström31638672017-11-23 17:48:32 +0100693// Upon completion, posts a task to execute the callback of the
694// SetSessionDescriptionObserver asynchronously on the same thread. At this
695// point, the state of the peer connection might no longer reflect the effects
696// of the SetRemoteDescription operation, as the peer connection could have been
697// modified during the post.
698// TODO(hbos): Remove this class once we remove the version of
699// PeerConnectionInterface::SetRemoteDescription() that takes a
700// SetSessionDescriptionObserver as an argument.
701class PeerConnection::SetRemoteDescriptionObserverAdapter
702 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
703 public:
704 SetRemoteDescriptionObserverAdapter(
705 rtc::scoped_refptr<PeerConnection> pc,
706 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
707 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
708
709 // SetRemoteDescriptionObserverInterface implementation.
710 void OnSetRemoteDescriptionComplete(RTCError error) override {
711 if (error.ok())
712 pc_->PostSetSessionDescriptionSuccess(wrapper_);
713 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100714 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100715 }
716
717 private:
718 rtc::scoped_refptr<PeerConnection> pc_;
719 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
720};
721
deadbeef293e9262017-01-11 12:28:30 -0800722bool PeerConnectionInterface::RTCConfiguration::operator==(
723 const PeerConnectionInterface::RTCConfiguration& o) const {
724 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700725 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800726 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000727 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700728 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800729 BundlePolicy bundle_policy;
730 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700731 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
732 int ice_candidate_pool_size;
733 bool disable_ipv6;
734 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700735 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100736 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700737 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200738 absl::optional<int> screencast_min_bitrate;
739 absl::optional<bool> combined_audio_video_bwe;
740 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800741 TcpCandidatePolicy tcp_candidate_policy;
742 CandidateNetworkPolicy candidate_network_policy;
743 int audio_jitter_buffer_max_packets;
744 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100745 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100746 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800747 int ice_connection_receiving_timeout;
748 int ice_backup_candidate_pair_ping_interval;
749 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800750 bool prioritize_most_likely_ice_candidate_pairs;
751 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800752 bool prune_turn_ports;
753 bool presume_writable_when_fully_relayed;
754 bool enable_ice_renomination;
755 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700756 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200757 absl::optional<int> ice_check_interval_strong_connectivity;
758 absl::optional<int> ice_check_interval_weak_connectivity;
759 absl::optional<int> ice_check_min_interval;
760 absl::optional<int> ice_unwritable_timeout;
761 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800762 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<int> stun_candidate_keepalive_interval;
764 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200765 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800766 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200767 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700768 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700769 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700770 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700771 absl::optional<bool> use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700772 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100773 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800774 };
775 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
776 "Did you add something to RTCConfiguration and forget to "
777 "update operator==?");
778 return type == o.type && servers == o.servers &&
779 bundle_policy == o.bundle_policy &&
780 rtcp_mux_policy == o.rtcp_mux_policy &&
781 tcp_candidate_policy == o.tcp_candidate_policy &&
782 candidate_network_policy == o.candidate_network_policy &&
783 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
784 audio_jitter_buffer_fast_accelerate ==
785 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100786 audio_jitter_buffer_min_delay_ms ==
787 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100788 audio_jitter_buffer_enable_rtx_handling ==
789 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800790 ice_connection_receiving_timeout ==
791 o.ice_connection_receiving_timeout &&
792 ice_backup_candidate_pair_ping_interval ==
793 o.ice_backup_candidate_pair_ping_interval &&
794 continual_gathering_policy == o.continual_gathering_policy &&
795 certificates == o.certificates &&
796 prioritize_most_likely_ice_candidate_pairs ==
797 o.prioritize_most_likely_ice_candidate_pairs &&
798 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800799 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700800 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100801 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800802 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800803 screencast_min_bitrate == o.screencast_min_bitrate &&
804 combined_audio_video_bwe == o.combined_audio_video_bwe &&
805 enable_dtls_srtp == o.enable_dtls_srtp &&
806 ice_candidate_pool_size == o.ice_candidate_pool_size &&
807 prune_turn_ports == o.prune_turn_ports &&
808 presume_writable_when_fully_relayed ==
809 o.presume_writable_when_fully_relayed &&
810 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800811 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700812 surface_ice_candidates_on_ice_transport_type_changed ==
813 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800814 ice_check_interval_strong_connectivity ==
815 o.ice_check_interval_strong_connectivity &&
816 ice_check_interval_weak_connectivity ==
817 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700818 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700819 ice_unwritable_timeout == o.ice_unwritable_timeout &&
820 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800821 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800822 stun_candidate_keepalive_interval ==
823 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200824 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800825 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800826 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700827 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700828 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700829 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700830 use_media_transport_for_data_channels ==
831 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700832 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100833 crypto_options == o.crypto_options &&
834 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800835}
836
837bool PeerConnectionInterface::RTCConfiguration::operator!=(
838 const PeerConnectionInterface::RTCConfiguration& o) const {
839 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800840}
841
zhihuang8f65cdf2016-05-06 18:40:30 -0700842// Generate a RTCP CNAME when a PeerConnection is created.
843std::string GenerateRtcpCname() {
844 std::string cname;
845 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100846 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800847 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700848 }
849 return cname;
850}
851
zhihuang1c378ed2017-08-17 14:10:50 -0700852bool ValidateOfferAnswerOptions(
853 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
854 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
855 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700856}
857
zhihuang1c378ed2017-08-17 14:10:50 -0700858// From |rtc_options|, fill parts of |session_options| shared by all generated
859// m= sections (in other words, nothing that involves a map/array).
860void ExtractSharedMediaSessionOptions(
861 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
862 cricket::MediaSessionOptions* session_options) {
863 session_options->vad_enabled = rtc_options.voice_activity_detection;
864 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200865 session_options->raw_packetization_for_video =
866 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700867}
zhihuanga77e6bb2017-08-14 18:17:48 -0700868
zhihuang38ede132017-06-15 12:52:32 -0700869PeerConnection::PeerConnection(PeerConnectionFactory* factory,
870 std::unique_ptr<RtcEventLog> event_log,
871 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700873 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100874 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700875 datagram_transport_config_(
876 field_trial::FindFullName(kDatagramTransportFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700877 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700878 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700879 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100880 call_(std::move(call)),
881 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882
883PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100884 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800885 RTC_DCHECK_RUN_ON(signaling_thread());
886
Steve Anton8af21862017-12-15 11:20:13 -0800887 // Need to stop transceivers before destroying the stats collector because
888 // AudioRtpSender has a reference to the StatsCollector it will update when
889 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100890 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800891 transceiver->Stop();
892 }
Steve Anton4171afb2017-11-20 10:20:22 -0800893
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700894 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800895 if (stats_collector_) {
896 stats_collector_->WaitForPendingRequest();
897 stats_collector_ = nullptr;
898 }
Steve Anton75737c02017-11-06 10:37:17 -0800899
Steve Anton8af21862017-12-15 11:20:13 -0800900 // Don't destroy BaseChannels until after stats has been cleaned up so that
901 // the last stats request can still read from the channels.
902 DestroyAllChannels();
903
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800905
906 webrtc_session_desc_factory_.reset();
907 sctp_invoker_.reset();
908 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800909 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800910 transport_controller_.reset();
911
deadbeef91dd5672016-05-18 16:55:30 -0700912 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100913 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
914 RTC_DCHECK_RUN_ON(network_thread());
915 port_allocator_.reset();
916 });
eladalon248fd4f2017-09-06 05:18:15 -0700917 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700918 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100919 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700920 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800921 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700922 event_log_.reset();
923 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924}
925
Steve Anton8af21862017-12-15 11:20:13 -0800926void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800927 // Destroy video channels first since they may have a pointer to a voice
928 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100929 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800930 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800931 DestroyTransceiverChannel(transceiver);
932 }
933 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100934 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800935 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800936 DestroyTransceiverChannel(transceiver);
937 }
938 }
939 DestroyDataChannel();
940}
941
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000943 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700944 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100945 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100946 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100947 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700948
949 RTCError config_error = ValidateConfiguration(configuration);
950 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100951 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700952 return false;
953 }
954
Benjamin Wrightcab58882018-05-02 15:12:47 -0700955 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100956 RTC_LOG(LS_ERROR)
957 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100958 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800959 return false;
960 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200961
Benjamin Wrightcab58882018-05-02 15:12:47 -0700962 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800963 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100964 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100965 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800966 return false;
967 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700968
Benjamin Wrightcab58882018-05-02 15:12:47 -0700969 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700970 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700971 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700972 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800973
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200974 cricket::ServerAddresses stun_servers;
975 std::vector<cricket::RelayServerConfig> turn_servers;
976
977 RTCErrorType parse_error =
978 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
979 if (parse_error != RTCErrorType::NONE) {
980 return false;
981 }
982
deadbeef91dd5672016-05-18 16:55:30 -0700983 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700984 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100985 const auto pa_result =
986 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200987 RTC_FROM_HERE,
988 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100989 stun_servers, turn_servers, configuration));
990
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200991 // If initialization was successful, note if STUN or TURN servers
992 // were supplied.
993 if (!stun_servers.empty()) {
994 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
995 }
996 if (!turn_servers.empty()) {
997 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
998 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001000 // Send information about IPv4/IPv6 status.
1001 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001002 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001003 address_family = kPeerConnection_IPv6;
1004 } else {
1005 address_family = kPeerConnection_IPv4;
1006 }
1007 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1008 kPeerConnectionAddressFamilyCounter_Max);
1009
Zhi Huange830e682018-03-30 10:48:35 -07001010 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1011
Steve Anton75737c02017-11-06 10:37:17 -08001012 // RFC 3264: The numeric value of the session id and version in the
1013 // o line MUST be representable with a "64 bit signed integer".
1014 // Due to this constraint session id |session_id_| is max limited to
1015 // LLONG_MAX.
1016 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001017 JsepTransportController::Config config;
1018 config.redetermine_role_on_ice_restart =
1019 configuration.redetermine_role_on_ice_restart;
1020 config.ssl_max_version = factory_->options().ssl_max_version;
1021 config.disable_encryption = options.disable_encryption;
1022 config.bundle_policy = configuration.bundle_policy;
1023 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001024 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1025 // stub.
1026 config.crypto_options = configuration.crypto_options.has_value()
1027 ? *configuration.crypto_options
1028 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001029 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001030 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001031#if defined(ENABLE_EXTERNAL_AUTH)
1032 config.enable_external_auth = true;
1033#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001034 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001035
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001036 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001037 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001038 datagram_transport_config_.default_value);
1039 if (use_datagram_transport_ || configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001040 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001041 if (!factory_->media_transport_factory()) {
1042 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001043 << "PeerConnecton is initialized with use_media_transport = true or "
1044 << "use_media_transport_for_data_channels = true "
1045 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001046 return false;
1047 }
1048
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001049 if (configuration.use_media_transport ||
1050 configuration.use_media_transport_for_data_channels) {
1051 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1052 // RTP media transport is introduced. But until then, we require SDES to
1053 // be enabled.
1054 if (configuration.enable_dtls_srtp.has_value() &&
1055 configuration.enable_dtls_srtp.value()) {
1056 RTC_LOG(LS_WARNING)
1057 << "When media transport is used, SDES must be enabled. Set "
1058 "configuration.enable_dtls_srtp to false. use_media_transport="
1059 << configuration.use_media_transport
1060 << ", use_media_transport_for_data_channels="
1061 << configuration.use_media_transport_for_data_channels;
1062 return false;
1063 }
1064 }
1065
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001066 config.use_media_transport_for_media = configuration.use_media_transport;
1067 config.use_media_transport_for_data_channels =
1068 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001069 config.use_datagram_transport = use_datagram_transport_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001070 config.media_transport_factory = factory_->media_transport_factory();
1071 }
1072
Zhi Huange830e682018-03-30 10:48:35 -07001073 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001074 signaling_thread(), network_thread(), port_allocator_.get(),
1075 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001076 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001077 this, &PeerConnection::OnTransportControllerConnectionState);
1078 transport_controller_->SignalStandardizedIceConnectionState.connect(
1079 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001080 transport_controller_->SignalConnectionState.connect(
1081 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001082 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001083 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001084 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001085 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001086 transport_controller_->SignalIceCandidateError.connect(
1087 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001088 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001089 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1090 transport_controller_->SignalDtlsHandshakeError.connect(
1091 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1092
1093 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001094
deadbeefab9b2d12015-10-14 11:33:11 -07001095 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001096 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001097
Steve Antonba818672017-11-06 10:21:57 -08001098 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001099 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001100
Steve Anton75737c02017-11-06 10:37:17 -08001101 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1102 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1103 if (!configuration.certificates.empty()) {
1104 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1105 // just picking the first one. The decision should be made based on the DTLS
1106 // handshake. The DTLS negotiations need to know about all certificates.
1107 certificate = configuration.certificates[0];
1108 }
1109
Steve Antond25da372017-11-06 14:50:29 -08001110 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001111
1112 if (options.disable_encryption) {
1113 dtls_enabled_ = false;
1114 } else {
1115 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001116 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001117 // |configuration| can override the default |dtls_enabled_| value.
1118 if (configuration.enable_dtls_srtp) {
1119 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1120 }
1121 }
1122
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001123 if (configuration.use_media_transport_for_data_channels) {
1124 if (configuration.enable_rtp_data_channel) {
1125 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1126 "use_media_transport_for_data_channels are "
1127 "incompatible and cannot both be set to true";
1128 return false;
1129 }
1130 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1131 } else if (configuration.enable_rtp_data_channel) {
1132 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1133 // set. It takes precendence over the disable_sctp_data_channels
1134 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001135 data_channel_type_ = cricket::DCT_RTP;
1136 } else {
1137 // DTLS has to be enabled to use SCTP.
1138 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1139 data_channel_type_ = cricket::DCT_SCTP;
1140 }
1141 }
1142
1143 video_options_.screencast_min_bitrate_kbps =
1144 configuration.screencast_min_bitrate;
1145 audio_options_.combined_audio_video_bwe =
1146 configuration.combined_audio_video_bwe;
1147
1148 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001149 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001150
1151 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001152 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001153
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001154 audio_options_.audio_jitter_buffer_min_delay_ms =
1155 configuration.audio_jitter_buffer_min_delay_ms;
1156
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001157 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1158 configuration.audio_jitter_buffer_enable_rtx_handling;
1159
Steve Anton75737c02017-11-06 10:37:17 -08001160 // Whether the certificate generator/certificate is null or not determines
1161 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1162 // the right instructions by clearing the variables if needed.
1163 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001164 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001165 certificate = nullptr;
1166 } else if (certificate) {
1167 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001168 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001169 }
1170
1171 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1172 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001173 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001174 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1175 this, &PeerConnection::OnCertificateReady);
1176
1177 if (options.disable_encryption) {
1178 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1179 }
1180
1181 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001182 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001183 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184
Steve Anton4171afb2017-11-20 10:20:22 -08001185 // Add default audio/video transceivers for Plan B SDP.
1186 if (!IsUnifiedPlan()) {
1187 transceivers_.push_back(
1188 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1189 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1190 transceivers_.push_back(
1191 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1192 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1193 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001194 int delay_ms =
1195 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001196 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1197 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001198
1199 if (dependencies.video_bitrate_allocator_factory) {
1200 video_bitrate_allocator_factory_ =
1201 std::move(dependencies.video_bitrate_allocator_factory);
1202 } else {
1203 video_bitrate_allocator_factory_ =
1204 CreateBuiltinVideoBitrateAllocatorFactory();
1205 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 return true;
1207}
1208
Steve Anton038834f2017-07-14 15:59:59 -07001209RTCError PeerConnection::ValidateConfiguration(
1210 const RTCConfiguration& config) const {
1211 if (config.ice_regather_interval_range &&
1212 config.continual_gathering_policy == GATHER_ONCE) {
1213 return RTCError(RTCErrorType::INVALID_PARAMETER,
1214 "ice_regather_interval_range specified but continual "
1215 "gathering policy is GATHER_ONCE");
1216 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001217 auto result =
1218 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1219 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001220}
1221
Yves Gerey665174f2018-06-19 15:03:05 +02001222rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_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()) << "local_streams is not available with Unified "
1225 "Plan SdpSemantics. Please use GetSenders "
1226 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001227 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228}
1229
Yves Gerey665174f2018-06-19 15:03:05 +02001230rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001231 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001232 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1233 "Plan SdpSemantics. Please use GetReceivers "
1234 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001235 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236}
1237
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001238bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001239 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001240 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1241 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001242 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243 if (IsClosed()) {
1244 return false;
1245 }
deadbeefab9b2d12015-10-14 11:33:11 -07001246 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247 return false;
1248 }
deadbeefab9b2d12015-10-14 11:33:11 -07001249
1250 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001251 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1252 observer->SignalAudioTrackAdded.connect(this,
1253 &PeerConnection::OnAudioTrackAdded);
1254 observer->SignalAudioTrackRemoved.connect(
1255 this, &PeerConnection::OnAudioTrackRemoved);
1256 observer->SignalVideoTrackAdded.connect(this,
1257 &PeerConnection::OnVideoTrackAdded);
1258 observer->SignalVideoTrackRemoved.connect(
1259 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001260 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001261
deadbeefab9b2d12015-10-14 11:33:11 -07001262 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001263 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001264 }
1265 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001266 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001267 }
1268
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001269 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001270 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271 return true;
1272}
1273
1274void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001275 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001276 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1277 "Plan SdpSemantics. Please use RemoveTrack "
1278 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001279 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001280 if (!IsClosed()) {
1281 for (const auto& track : local_stream->GetAudioTracks()) {
1282 RemoveAudioTrack(track.get(), local_stream);
1283 }
1284 for (const auto& track : local_stream->GetVideoTracks()) {
1285 RemoveVideoTrack(track.get(), local_stream);
1286 }
deadbeefab9b2d12015-10-14 11:33:11 -07001287 }
deadbeefab9b2d12015-10-14 11:33:11 -07001288 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001289 stream_observers_.erase(
1290 std::remove_if(
1291 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001292 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001293 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001294 }),
1295 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001296
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 if (IsClosed()) {
1298 return;
1299 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001300 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301}
1302
Steve Anton2d6c76a2018-01-05 17:10:52 -08001303RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001304 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001305 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001306 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001307 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001308 if (!track) {
1309 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1310 }
1311 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1312 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1314 "Track has invalid kind: " + track->kind());
1315 }
Steve Antonf9381f02017-12-14 10:23:57 -08001316 if (IsClosed()) {
1317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1318 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001319 }
Steve Anton4171afb2017-11-20 10:20:22 -08001320 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001321 LOG_AND_RETURN_ERROR(
1322 RTCErrorType::INVALID_PARAMETER,
1323 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001324 }
Steve Antonf9381f02017-12-14 10:23:57 -08001325 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001326 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1327 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001328 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001329 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001330 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001331 }
1332 return sender_or_error;
1333}
deadbeefe1f9d832016-01-14 15:35:42 -08001334
Steve Antonf9381f02017-12-14 10:23:57 -08001335RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1336PeerConnection::AddTrackPlanB(
1337 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001338 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001339 if (stream_ids.size() > 1u) {
1340 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1341 "AddTrack with more than one stream is not "
1342 "supported with Plan B semantics.");
1343 }
1344 std::vector<std::string> adjusted_stream_ids = stream_ids;
1345 if (adjusted_stream_ids.empty()) {
1346 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1347 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001348 cricket::MediaType media_type =
1349 (track->kind() == MediaStreamTrackInterface::kAudioKind
1350 ? cricket::MEDIA_TYPE_AUDIO
1351 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001352 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001353 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001354 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001355 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001356 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001357 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001358 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001359 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001360 if (sender_info) {
1361 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001362 }
Steve Antonf9381f02017-12-14 10:23:57 -08001363 } else {
1364 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001365 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001366 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001367 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001368 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001369 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001370 if (sender_info) {
1371 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001372 }
deadbeefe1f9d832016-01-14 15:35:42 -08001373 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001374 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001375}
deadbeefe1f9d832016-01-14 15:35:42 -08001376
Steve Antonf9381f02017-12-14 10:23:57 -08001377RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1378PeerConnection::AddTrackUnifiedPlan(
1379 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001380 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001381 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1382 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001383 RTC_LOG(LS_INFO) << "Reusing an existing "
1384 << cricket::MediaTypeToString(transceiver->media_type())
1385 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001386 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001387 transceiver->internal()->set_direction(
1388 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001389 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001390 transceiver->internal()->set_direction(
1391 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001392 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001393 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001394 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001395 } else {
1396 cricket::MediaType media_type =
1397 (track->kind() == MediaStreamTrackInterface::kAudioKind
1398 ? cricket::MEDIA_TYPE_AUDIO
1399 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001400 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1401 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001402 std::string sender_id = track->id();
1403 // Avoid creating a sender with an existing ID by generating a random ID.
1404 // This can happen if this is the second time AddTrack has created a sender
1405 // for this track.
1406 if (FindSenderById(sender_id)) {
1407 sender_id = rtc::CreateRandomUuid();
1408 }
Florent Castelli892acf02018-10-01 22:47:20 +02001409 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001410 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1411 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001412 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001413 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001414 }
Steve Antonf9381f02017-12-14 10:23:57 -08001415 return transceiver->sender();
1416}
1417
1418rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1419PeerConnection::FindFirstTransceiverForAddedTrack(
1420 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1421 RTC_DCHECK(track);
1422 for (auto transceiver : transceivers_) {
1423 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001424 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001425 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001426 !transceiver->internal()->has_ever_been_used_to_send() &&
1427 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001428 return transceiver;
1429 }
1430 }
1431 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001432}
1433
1434bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1435 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001436 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001437}
1438
Steve Anton24db5732018-07-23 10:27:33 -07001439RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001440 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001441 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001442 if (!sender) {
1443 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1444 }
deadbeefe1f9d832016-01-14 15:35:42 -08001445 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001446 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1447 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001448 }
Steve Antonf9381f02017-12-14 10:23:57 -08001449 if (IsUnifiedPlan()) {
1450 auto transceiver = FindTransceiverBySender(sender);
1451 if (!transceiver || !sender->track()) {
1452 return RTCError::OK();
1453 }
1454 sender->SetTrack(nullptr);
1455 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001456 transceiver->internal()->set_direction(
1457 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001458 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001459 transceiver->internal()->set_direction(
1460 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001461 }
Steve Anton4171afb2017-11-20 10:20:22 -08001462 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001463 bool removed;
1464 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1465 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1466 } else {
1467 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1468 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1469 }
1470 if (!removed) {
1471 LOG_AND_RETURN_ERROR(
1472 RTCErrorType::INVALID_PARAMETER,
1473 "Couldn't find sender " + sender->id() + " to remove.");
1474 }
Steve Anton4171afb2017-11-20 10:20:22 -08001475 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001476 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001477 return RTCError::OK();
1478}
1479
1480rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1481PeerConnection::FindTransceiverBySender(
1482 rtc::scoped_refptr<RtpSenderInterface> sender) {
1483 for (auto transceiver : transceivers_) {
1484 if (transceiver->sender() == sender) {
1485 return transceiver;
1486 }
1487 }
1488 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001489}
1490
Steve Anton9158ef62017-11-27 13:01:52 -08001491RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1492PeerConnection::AddTransceiver(
1493 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1494 return AddTransceiver(track, RtpTransceiverInit());
1495}
1496
1497RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1498PeerConnection::AddTransceiver(
1499 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1500 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001501 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001502 RTC_CHECK(IsUnifiedPlan())
1503 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001504 if (!track) {
1505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1506 }
1507 cricket::MediaType media_type;
1508 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1509 media_type = cricket::MEDIA_TYPE_AUDIO;
1510 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1511 media_type = cricket::MEDIA_TYPE_VIDEO;
1512 } else {
1513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1514 "Track kind is not audio or video");
1515 }
1516 return AddTransceiver(media_type, track, init);
1517}
1518
1519RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1520PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1521 return AddTransceiver(media_type, RtpTransceiverInit());
1522}
1523
1524RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1525PeerConnection::AddTransceiver(cricket::MediaType media_type,
1526 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001527 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001528 RTC_CHECK(IsUnifiedPlan())
1529 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001530 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1531 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1533 "media type is not audio or video");
1534 }
1535 return AddTransceiver(media_type, nullptr, init);
1536}
1537
1538RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1539PeerConnection::AddTransceiver(
1540 cricket::MediaType media_type,
1541 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001542 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001543 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001544 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1545 media_type == cricket::MEDIA_TYPE_VIDEO));
1546 if (track) {
1547 RTC_DCHECK_EQ(media_type,
1548 (track->kind() == MediaStreamTrackInterface::kAudioKind
1549 ? cricket::MEDIA_TYPE_AUDIO
1550 : cricket::MEDIA_TYPE_VIDEO));
1551 }
1552
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001553 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1554 init.send_encodings.size(), 0, 7, 8);
1555
Amit Hilbuchaa584152019-02-06 17:09:52 -08001556 size_t num_rids = absl::c_count_if(init.send_encodings,
1557 [](const RtpEncodingParameters& encoding) {
1558 return !encoding.rid.empty();
1559 });
1560 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001561 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001562 RTCErrorType::INVALID_PARAMETER,
1563 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001564 }
1565
Amit Hilbuchf4770402019-04-08 14:11:57 -07001566 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1567 [](const RtpEncodingParameters& encoding) {
1568 return !IsLegalRsidName(encoding.rid);
1569 })) {
1570 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1571 "Invalid RID value provided.");
1572 }
1573
Amit Hilbuchaa584152019-02-06 17:09:52 -08001574 if (absl::c_any_of(init.send_encodings,
1575 [](const RtpEncodingParameters& encoding) {
1576 return encoding.ssrc.has_value();
1577 })) {
1578 LOG_AND_RETURN_ERROR(
1579 RTCErrorType::UNSUPPORTED_PARAMETER,
1580 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001581 }
1582
1583 RtpParameters parameters;
1584 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001585
1586 // Encodings are dropped from the tail if too many are provided.
1587 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1588 parameters.encodings.erase(
1589 parameters.encodings.begin() + kMaxSimulcastStreams,
1590 parameters.encodings.end());
1591 }
1592
1593 // Single RID should be removed.
1594 if (parameters.encodings.size() == 1 &&
1595 !parameters.encodings[0].rid.empty()) {
1596 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1597 parameters.encodings[0].rid.clear();
1598 }
1599
1600 // If RIDs were not provided, they are generated for simulcast scenario.
1601 if (parameters.encodings.size() > 1 && num_rids == 0) {
1602 rtc::UniqueStringGenerator rid_generator;
1603 for (RtpEncodingParameters& encoding : parameters.encodings) {
1604 encoding.rid = rid_generator();
1605 }
1606 }
1607
Florent Castelli892acf02018-10-01 22:47:20 +02001608 if (UnimplementedRtpParameterHasValue(parameters)) {
1609 LOG_AND_RETURN_ERROR(
1610 RTCErrorType::UNSUPPORTED_PARAMETER,
1611 "Attempted to set an unimplemented parameter of RtpParameters.");
1612 }
Steve Anton9158ef62017-11-27 13:01:52 -08001613
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001614 auto result = cricket::CheckRtpParametersValues(parameters);
1615 if (!result.ok()) {
1616 LOG_AND_RETURN_ERROR(result.type(), result.message());
1617 }
1618
Steve Anton3d954a62018-04-02 11:27:23 -07001619 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1620 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001621 // Set the sender ID equal to the track ID if the track is specified unless
1622 // that sender ID is already in use.
1623 std::string sender_id =
1624 (track && !FindSenderById(track->id()) ? track->id()
1625 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001626 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001627 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001628 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1629 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1630 transceiver->internal()->set_direction(init.direction);
1631
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001632 if (update_negotiation_needed) {
1633 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001634 }
Steve Antonf9381f02017-12-14 10:23:57 -08001635
1636 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1637}
1638
Steve Anton02ee47c2018-01-10 16:26:06 -08001639rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1640PeerConnection::CreateSender(
1641 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001642 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001643 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001644 const std::vector<std::string>& stream_ids,
1645 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001646 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001647 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001648 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1649 RTC_DCHECK(!track ||
1650 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1651 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1652 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001653 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001654 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001655 } else {
1656 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1657 RTC_DCHECK(!track ||
1658 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1659 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001660 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001661 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001662 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001663 bool set_track_succeeded = sender->SetTrack(track);
1664 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001665 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001666 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001667 return sender;
1668}
1669
1670rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1671PeerConnection::CreateReceiver(cricket::MediaType media_type,
1672 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001673 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1674 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001675 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001676 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001677 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1678 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001679 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001680 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001681 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001682 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001683 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1684 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001685 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001686 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001687 return receiver;
1688}
1689
1690rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1691PeerConnection::CreateAndAddTransceiver(
1692 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1693 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1694 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001695 // Ensure that the new sender does not have an ID that is already in use by
1696 // another sender.
1697 // Allow receiver IDs to conflict since those come from remote SDP (which
1698 // could be invalid, but should not cause a crash).
1699 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001700 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001701 signaling_thread(),
1702 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001703 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001704 transceiver->internal()->SignalNegotiationNeeded.connect(
1705 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001706 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001707}
1708
Steve Anton52d86772018-02-20 15:48:12 -08001709void PeerConnection::OnNegotiationNeeded() {
1710 RTC_DCHECK_RUN_ON(signaling_thread());
1711 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001712 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001713}
1714
deadbeeffac06552015-11-25 11:26:01 -08001715rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001716 const std::string& kind,
1717 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001718 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001719 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1720 "Plan SdpSemantics. Please use AddTransceiver "
1721 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001722 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001723 if (IsClosed()) {
1724 return nullptr;
1725 }
Steve Anton4171afb2017-11-20 10:20:22 -08001726
Seth Hampson5b4f0752018-04-02 16:31:36 -07001727 // Internally we need to have one stream with Plan B semantics, so we
1728 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001729 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001730 if (stream_id.empty()) {
1731 stream_ids.push_back(rtc::CreateRandomUuid());
1732 RTC_LOG(LS_INFO)
1733 << "No stream_id specified for sender. Generated stream ID: "
1734 << stream_ids[0];
1735 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001736 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001737 }
1738
Steve Anton4171afb2017-11-20 10:20:22 -08001739 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001740 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001741 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001742 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001743 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001744 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001745 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001746 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001747 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001748 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001749 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001750 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001751 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001752 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001753 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001754 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001755 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001756 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001757 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001758 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001759 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001760
deadbeefe1f9d832016-01-14 15:35:42 -08001761 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001762}
1763
deadbeef70ab1a12015-09-28 16:53:55 -07001764std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1765 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001766 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001767 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001768 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001769 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001770 }
1771 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001772}
1773
Steve Anton4171afb2017-11-20 10:20:22 -08001774std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1775PeerConnection::GetSendersInternal() const {
1776 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1777 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001778 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001779 auto senders = transceiver->internal()->senders();
1780 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1781 }
1782 return all_senders;
1783}
1784
deadbeef70ab1a12015-09-28 16:53:55 -07001785std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1786PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001787 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001788 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001789 for (const auto& receiver : GetReceiversInternal()) {
1790 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001791 }
1792 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001793}
1794
Steve Anton4171afb2017-11-20 10:20:22 -08001795std::vector<
1796 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1797PeerConnection::GetReceiversInternal() const {
1798 std::vector<
1799 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1800 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001801 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001802 auto receivers = transceiver->internal()->receivers();
1803 all_receivers.insert(all_receivers.end(), receivers.begin(),
1804 receivers.end());
1805 }
1806 return all_receivers;
1807}
1808
Steve Anton9158ef62017-11-27 13:01:52 -08001809std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1810PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001811 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001812 RTC_CHECK(IsUnifiedPlan())
1813 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001814 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001815 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001816 all_transceivers.push_back(transceiver);
1817 }
1818 return all_transceivers;
1819}
1820
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001822 MediaStreamTrackInterface* track,
1823 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001824 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001825 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001826 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001828 return false;
1829 }
1830
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001831 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001832 // The StatsCollector is used to tell if a track is valid because it may
1833 // remember tracks that the PeerConnection previously removed.
1834 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001835 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1836 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001837 return false;
1838 }
Steve Antonad182762018-09-05 20:22:40 +00001839 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1840 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841 return true;
1842}
1843
hbos74e1a4f2016-09-15 23:33:01 -07001844void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001845 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001846 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001847 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001848 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001849 stats_collector_->GetStatsReport(callback);
1850}
1851
Henrik Boström1df1bf82018-03-20 13:24:20 +01001852void PeerConnection::GetStats(
1853 rtc::scoped_refptr<RtpSenderInterface> selector,
1854 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1855 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001856 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001857 RTC_DCHECK(callback);
1858 RTC_DCHECK(stats_collector_);
1859 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1860 if (selector) {
1861 for (const auto& proxy_transceiver : transceivers_) {
1862 for (const auto& proxy_sender :
1863 proxy_transceiver->internal()->senders()) {
1864 if (proxy_sender == selector) {
1865 internal_sender = proxy_sender->internal();
1866 break;
1867 }
1868 }
1869 if (internal_sender)
1870 break;
1871 }
1872 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001873 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001874 // belong to the PeerConnection (in Plan B, senders can be removed from the
1875 // PeerConnection). This means that "all the stats objects representing the
1876 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1877 // produces an empty stats report.
1878 stats_collector_->GetStatsReport(internal_sender, callback);
1879}
1880
1881void PeerConnection::GetStats(
1882 rtc::scoped_refptr<RtpReceiverInterface> selector,
1883 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1884 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001885 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001886 RTC_DCHECK(callback);
1887 RTC_DCHECK(stats_collector_);
1888 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1889 if (selector) {
1890 for (const auto& proxy_transceiver : transceivers_) {
1891 for (const auto& proxy_receiver :
1892 proxy_transceiver->internal()->receivers()) {
1893 if (proxy_receiver == selector) {
1894 internal_receiver = proxy_receiver->internal();
1895 break;
1896 }
1897 }
1898 if (internal_receiver)
1899 break;
1900 }
1901 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001902 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001903 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1904 // the PeerConnection). This means that "all the stats objects representing
1905 // the selector" is an empty set. Invoking GetStatsReport() with a null
1906 // selector produces an empty stats report.
1907 stats_collector_->GetStatsReport(internal_receiver, callback);
1908}
1909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001911 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912 return signaling_state_;
1913}
1914
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915PeerConnectionInterface::IceConnectionState
1916PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001917 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 return ice_connection_state_;
1919}
1920
Alex Loiko9289eda2018-11-23 16:18:59 +00001921PeerConnectionInterface::IceConnectionState
1922PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001923 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001924 return standardized_ice_connection_state_;
1925}
1926
Jonas Olsson635474e2018-10-18 15:58:17 +02001927PeerConnectionInterface::PeerConnectionState
1928PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001929 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001930 return connection_state_;
1931}
1932
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933PeerConnectionInterface::IceGatheringState
1934PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001935 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 return ice_gathering_state_;
1937}
1938
Yves Gerey665174f2018-06-19 15:03:05 +02001939rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001940 const std::string& label,
1941 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001942 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001943 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001944
deadbeefab9b2d12015-10-14 11:33:11 -07001945 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001946
kwibergd1fe2812016-04-27 06:47:29 -07001947 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001948 if (config) {
1949 internal_config.reset(new InternalDataChannelInit(*config));
1950 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001951 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001952 InternalCreateDataChannel(label, internal_config.get()));
1953 if (!channel.get()) {
1954 return nullptr;
1955 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001956
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001957 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1958 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001959 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001960 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001961 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001962 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001963 return DataChannelProxy::Create(signaling_thread(), channel.get());
1964}
1965
1966void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001967 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001968 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001969 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001970
nisse7ce109a2017-01-31 00:57:56 -08001971 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001973 return;
1974 }
deadbeefab9b2d12015-10-14 11:33:11 -07001975
Steve Anton8d3444d2017-10-20 15:30:51 -07001976 if (IsClosed()) {
1977 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001978 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001979 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001980 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001981 return;
1982 }
1983
Steve Anton25ca0ac2019-06-25 10:40:48 -07001984 // If a session error has occurred the PeerConnection is in a possibly
1985 // inconsistent state so fail right away.
1986 if (session_error() != SessionError::kNone) {
1987 std::string error_message = GetSessionErrorMsg();
1988 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
1989 PostCreateSessionDescriptionFailure(
1990 observer,
1991 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
1992 return;
1993 }
1994
zhihuang1c378ed2017-08-17 14:10:50 -07001995 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001996 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001997 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001998 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001999 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002000 return;
2001 }
2002
Steve Anton22da89f2018-01-25 13:58:07 -08002003 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2004 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2005 if (IsUnifiedPlan()) {
2006 RTCError error = HandleLegacyOfferOptions(options);
2007 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002008 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002009 return;
2010 }
2011 }
2012
zhihuang1c378ed2017-08-17 14:10:50 -07002013 cricket::MediaSessionOptions session_options;
2014 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002015 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016}
2017
Steve Anton22da89f2018-01-25 13:58:07 -08002018RTCError PeerConnection::HandleLegacyOfferOptions(
2019 const RTCOfferAnswerOptions& options) {
2020 RTC_DCHECK(IsUnifiedPlan());
2021
2022 if (options.offer_to_receive_audio == 0) {
2023 RemoveRecvDirectionFromReceivingTransceiversOfType(
2024 cricket::MEDIA_TYPE_AUDIO);
2025 } else if (options.offer_to_receive_audio == 1) {
2026 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2027 } else if (options.offer_to_receive_audio > 1) {
2028 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2029 "offer_to_receive_audio > 1 is not supported.");
2030 }
2031
2032 if (options.offer_to_receive_video == 0) {
2033 RemoveRecvDirectionFromReceivingTransceiversOfType(
2034 cricket::MEDIA_TYPE_VIDEO);
2035 } else if (options.offer_to_receive_video == 1) {
2036 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2037 } else if (options.offer_to_receive_video > 1) {
2038 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2039 "offer_to_receive_video > 1 is not supported.");
2040 }
2041
2042 return RTCError::OK();
2043}
2044
2045void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2046 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002047 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002048 RtpTransceiverDirection new_direction =
2049 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2050 if (new_direction != transceiver->direction()) {
2051 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2052 << " transceiver (MID="
2053 << transceiver->mid().value_or("<not set>") << ") from "
2054 << RtpTransceiverDirectionToString(
2055 transceiver->direction())
2056 << " to "
2057 << RtpTransceiverDirectionToString(new_direction)
2058 << " since CreateOffer specified offer_to_receive=0";
2059 transceiver->internal()->set_direction(new_direction);
2060 }
Steve Anton22da89f2018-01-25 13:58:07 -08002061 }
2062}
2063
2064void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2065 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002066 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002067 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002068 RTC_LOG(LS_INFO)
2069 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2070 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002071 RtpTransceiverInit init;
2072 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002073 AddTransceiver(media_type, nullptr, init,
2074 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002075 }
2076}
2077
2078std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2079PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2080 std::vector<
2081 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2082 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002083 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002084 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002085 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2086 receiving_transceivers.push_back(transceiver);
2087 }
2088 }
2089 return receiving_transceivers;
2090}
2091
htaa2a49d92016-03-04 02:51:39 -08002092void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2093 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002094 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002095 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002096 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002097 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002098 return;
2099 }
2100
Steve Anton25ca0ac2019-06-25 10:40:48 -07002101 // If a session error has occurred the PeerConnection is in a possibly
2102 // inconsistent state so fail right away.
2103 if (session_error() != SessionError::kNone) {
2104 std::string error_message = GetSessionErrorMsg();
2105 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2106 PostCreateSessionDescriptionFailure(
2107 observer,
2108 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2109 return;
2110 }
2111
Steve Antondffead82018-02-06 10:31:29 -08002112 if (!(signaling_state_ == kHaveRemoteOffer ||
2113 signaling_state_ == kHaveLocalPrAnswer)) {
2114 std::string error =
2115 "PeerConnection cannot create an answer in a state other than "
2116 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002117 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002118 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002119 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002120 return;
2121 }
2122
Steve Antondffead82018-02-06 10:31:29 -08002123 // The remote description should be set if we're in the right state.
2124 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002125
Steve Anton22da89f2018-01-25 13:58:07 -08002126 if (IsUnifiedPlan()) {
2127 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2128 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2129 "supported with Unified Plan semantics. Use the "
2130 "RtpTransceiver API instead.";
2131 }
2132 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2133 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2134 "supported with Unified Plan semantics. Use the "
2135 "RtpTransceiver API instead.";
2136 }
2137 }
2138
htaa2a49d92016-03-04 02:51:39 -08002139 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002140 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002141
Steve Antond25da372017-11-06 14:50:29 -08002142 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002143}
2144
2145void PeerConnection::SetLocalDescription(
2146 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002147 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002148 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002149 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002150
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 // The SetLocalDescription contract is that we take ownership of the session
2152 // description regardless of the outcome, so wrap it in a unique_ptr right
2153 // away. Ideally, SetLocalDescription's signature will be changed to take the
2154 // description as a unique_ptr argument to formalize this agreement.
2155 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2156
nisse7ce109a2017-01-31 00:57:56 -08002157 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002158 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002159 return;
2160 }
Steve Anton8a006912017-12-04 15:25:56 -08002161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002163 PostSetSessionDescriptionFailure(
2164 observer,
2165 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 return;
2167 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002168
Steve Anton80dd7b52018-02-16 17:08:42 -08002169 // If a session error has occurred the PeerConnection is in a possibly
2170 // inconsistent state so fail right away.
2171 if (session_error() != SessionError::kNone) {
2172 std::string error_message = GetSessionErrorMsg();
2173 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002174 PostSetSessionDescriptionFailure(
2175 observer,
2176 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002177 return;
2178 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002179
Steve Anton80dd7b52018-02-16 17:08:42 -08002180 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2181 if (!error.ok()) {
2182 std::string error_message = GetSetDescriptionErrorMessage(
2183 cricket::CS_LOCAL, desc->GetType(), error);
2184 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002185 PostSetSessionDescriptionFailure(
2186 observer,
2187 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002188 return;
2189 }
2190
2191 // Grab the description type before moving ownership to ApplyLocalDescription,
2192 // which may destroy it before returning.
2193 const SdpType type = desc->GetType();
2194
2195 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002196 // |desc| may be destroyed at this point.
2197
2198 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002199 // If ApplyLocalDescription fails, the PeerConnection could be in an
2200 // inconsistent state, so act conservatively here and set the session error
2201 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2202 SetSessionError(SessionError::kContent, error.message());
2203 std::string error_message =
2204 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2205 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002206 PostSetSessionDescriptionFailure(
2207 observer,
2208 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002209 return;
2210 }
Steve Anton8a006912017-12-04 15:25:56 -08002211 RTC_DCHECK(local_description());
2212
2213 PostSetSessionDescriptionSuccess(observer);
2214
Steve Antonad182762018-09-05 20:22:40 +00002215 // MaybeStartGathering needs to be called after posting
2216 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2217 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002218 transport_controller_->MaybeStartGathering();
2219
Steve Antona3a92c22017-12-07 10:27:41 -08002220 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002221 // TODO(deadbeef): We already had to hop to the network thread for
2222 // MaybeStartGathering...
2223 network_thread()->Invoke<void>(
2224 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2225 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002226 // Make UMA notes about what was agreed to.
2227 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002228 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002229
2230 if (IsUnifiedPlan()) {
2231 bool was_negotiation_needed = is_negotiation_needed_;
2232 UpdateNegotiationNeeded();
2233 if (signaling_state() == kStable && was_negotiation_needed &&
2234 is_negotiation_needed_) {
2235 Observer()->OnRenegotiationNeeded();
2236 }
2237 }
2238
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002239 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002240}
2241
2242RTCError PeerConnection::ApplyLocalDescription(
2243 std::unique_ptr<SessionDescriptionInterface> desc) {
2244 RTC_DCHECK_RUN_ON(signaling_thread());
2245 RTC_DCHECK(desc);
2246
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002247 // Update stats here so that we have the most recent stats for tracks and
2248 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002249 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002250
Steve Antondcc3c022017-12-22 16:02:54 -08002251 // Take a reference to the old local description since it's used below to
2252 // compare against the new local description. When setting the new local
2253 // description, grab ownership of the replaced session description in case it
2254 // is the same as |old_local_description|, to keep it alive for the duration
2255 // of the method.
2256 const SessionDescriptionInterface* old_local_description =
2257 local_description();
2258 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002259 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002260 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002261 replaced_local_description = pending_local_description_
2262 ? std::move(pending_local_description_)
2263 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002264 current_local_description_ = std::move(desc);
2265 pending_local_description_ = nullptr;
2266 current_remote_description_ = std::move(pending_remote_description_);
2267 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002268 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002269 pending_local_description_ = std::move(desc);
2270 }
2271 // The session description to apply now must be accessed by
2272 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002273 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002274
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002275 // Report statistics about any use of simulcast.
2276 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2277 *local_description()->description());
2278
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002279 if (!is_caller_) {
2280 if (remote_description()) {
2281 // Remote description was applied first, so this PC is the callee.
2282 is_caller_ = false;
2283 } else {
2284 // Local description is applied first, so this PC is the caller.
2285 is_caller_ = true;
2286 }
2287 }
2288
Zhi Huange830e682018-03-30 10:48:35 -07002289 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2290 if (!error.ok()) {
2291 return error;
2292 }
2293
Steve Antondcc3c022017-12-22 16:02:54 -08002294 if (IsUnifiedPlan()) {
2295 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002296 cricket::CS_LOCAL, *local_description(), old_local_description,
2297 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002298 if (!error.ok()) {
2299 return error;
2300 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002301 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2302 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002303 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002304 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2305 // Note that code paths that don't set MID won't be able to use
2306 // information about DTLS transports.
2307 if (transceiver->mid()) {
2308 auto dtls_transport =
2309 LookupDtlsTransportByMidInternal(*transceiver->mid());
2310 transceiver->internal()->sender_internal()->set_transport(
2311 dtls_transport);
2312 transceiver->internal()->receiver_internal()->set_transport(
2313 dtls_transport);
2314 }
2315
Steve Antondcc3c022017-12-22 16:02:54 -08002316 const ContentInfo* content =
2317 FindMediaSectionForTransceiver(transceiver, local_description());
2318 if (!content) {
2319 continue;
2320 }
2321 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002322 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2323 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002324 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002325 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2326 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2327 // "recvonly", process the removal of a remote track for the media
2328 // description, given transceiver, removeList, and muteTracks.
2329 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2330 (transceiver->internal()->fired_direction() &&
2331 RtpTransceiverDirectionHasRecv(
2332 *transceiver->internal()->fired_direction()))) {
2333 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2334 &removed_streams);
2335 }
2336 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2337 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002338 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002339 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002340 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002341 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002342 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002343 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002344 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002345 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002346 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002347 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002348 }
2349 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002350 // Media channels will be created only when offer is set. These may use new
2351 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002352 if (type == SdpType::kOffer) {
2353 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2354 // description is applied. Restore back to old description.
2355 RTCError error = CreateChannels(*local_description()->description());
2356 if (!error.ok()) {
2357 return error;
2358 }
2359 }
Steve Antondcc3c022017-12-22 16:02:54 -08002360 // Remove unused channels if MediaContentDescription is rejected.
2361 RemoveUnusedChannels(local_description()->description());
2362 }
Steve Anton8a006912017-12-04 15:25:56 -08002363
Zhi Huange830e682018-03-30 10:48:35 -07002364 error = UpdateSessionState(type, cricket::CS_LOCAL,
2365 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002366 if (!error.ok()) {
2367 return error;
2368 }
Steve Antondcc3c022017-12-22 16:02:54 -08002369
Steve Anton8a006912017-12-04 15:25:56 -08002370 if (remote_description()) {
2371 // Now that we have a local description, we can push down remote candidates.
2372 UseCandidatesInSessionDescription(remote_description());
2373 }
2374
2375 pending_ice_restarts_.clear();
2376 if (session_error() != SessionError::kNone) {
2377 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2378 }
2379
deadbeefab9b2d12015-10-14 11:33:11 -07002380 // If setting the description decided our SSL role, allocate any necessary
2381 // SCTP sids.
2382 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002383 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002384 AllocateSctpSids(role);
2385 }
2386
Steve Antond3679212018-01-17 17:41:02 -08002387 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002388 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002389 const ContentInfo* content =
2390 FindMediaSectionForTransceiver(transceiver, local_description());
2391 if (!content) {
2392 continue;
2393 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002394 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2395 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002396 // 0 is a special value meaning "this sender has no associated send
2397 // stream". Need to call this so the sender won't attempt to configure
2398 // a no longer existing stream and run into DCHECKs in the lower
2399 // layers.
2400 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002401 } else {
2402 // Get the StreamParams from the channel which could generate SSRCs.
2403 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002404 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002405 streams[0].stream_ids());
2406 transceiver->internal()->sender_internal()->SetSsrc(
2407 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002408 }
2409 }
2410 } else {
2411 // Plan B semantics.
2412
Steve Antondcc3c022017-12-22 16:02:54 -08002413 // Update state and SSRC of local MediaStreams and DataChannels based on the
2414 // local session description.
2415 const cricket::ContentInfo* audio_content =
2416 GetFirstAudioContent(local_description()->description());
2417 if (audio_content) {
2418 if (audio_content->rejected) {
2419 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2420 } else {
2421 const cricket::AudioContentDescription* audio_desc =
2422 audio_content->media_description()->as_audio();
2423 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2424 }
deadbeeffaac4972015-11-12 15:33:07 -08002425 }
deadbeefab9b2d12015-10-14 11:33:11 -07002426
Steve Antondcc3c022017-12-22 16:02:54 -08002427 const cricket::ContentInfo* video_content =
2428 GetFirstVideoContent(local_description()->description());
2429 if (video_content) {
2430 if (video_content->rejected) {
2431 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2432 } else {
2433 const cricket::VideoContentDescription* video_desc =
2434 video_content->media_description()->as_video();
2435 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2436 }
deadbeeffaac4972015-11-12 15:33:07 -08002437 }
deadbeefab9b2d12015-10-14 11:33:11 -07002438 }
2439
2440 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002441 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002442 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002443 const cricket::RtpDataContentDescription* rtp_data_desc =
2444 data_content->media_description()->as_rtp_data();
2445 // rtp_data_desc will be null if this is an SCTP description.
2446 if (rtp_data_desc) {
2447 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002448 }
2449 }
2450
Steve Anton8a006912017-12-04 15:25:56 -08002451 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002452}
2453
Steve Anton06817cd2018-12-18 15:55:30 -08002454// The SDP parser used to populate these values by default for the 'content
2455// name' if an a=mid line was absent.
2456static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2457 switch (media_type) {
2458 case cricket::MEDIA_TYPE_AUDIO:
2459 return cricket::CN_AUDIO;
2460 case cricket::MEDIA_TYPE_VIDEO:
2461 return cricket::CN_VIDEO;
2462 case cricket::MEDIA_TYPE_DATA:
2463 return cricket::CN_DATA;
2464 }
2465 RTC_NOTREACHED();
2466 return "";
2467}
2468
2469void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002470 cricket::SessionDescription* new_remote_description) {
2471 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002472 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002473 const cricket::ContentInfos& local_contents =
2474 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002475 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002476 const cricket::ContentInfos& remote_contents =
2477 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002478 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002479 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2480 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002481 if (!content.name.empty()) {
2482 continue;
2483 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002484 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002485 absl::string_view source_explanation;
2486 if (IsUnifiedPlan()) {
2487 if (i < local_contents.size()) {
2488 new_mid = local_contents[i].name;
2489 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002490 } else if (i < remote_contents.size()) {
2491 new_mid = remote_contents[i].name;
2492 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002493 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002494 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002495 source_explanation = "generated just now";
2496 }
2497 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002498 new_mid = std::string(
2499 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002500 source_explanation = "to match pre-existing behavior";
2501 }
Steve Antond7180cc2019-02-07 10:44:53 -08002502 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002503 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002504 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002505 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2506 << " is missing an a=mid line. Filling in the value '"
2507 << new_mid << "' " << source_explanation << ".";
2508 }
2509}
2510
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002511void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002512 SetSessionDescriptionObserver* observer,
2513 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002514 SetRemoteDescription(
2515 std::unique_ptr<SessionDescriptionInterface>(desc),
2516 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2517 new SetRemoteDescriptionObserverAdapter(this, observer)));
2518}
2519
2520void PeerConnection::SetRemoteDescription(
2521 std::unique_ptr<SessionDescriptionInterface> desc,
2522 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002523 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002524 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002525
nisse7ce109a2017-01-31 00:57:56 -08002526 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002527 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528 return;
2529 }
Steve Anton8a006912017-12-04 15:25:56 -08002530
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002532 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002533 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534 return;
2535 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002536
Steve Anton80dd7b52018-02-16 17:08:42 -08002537 // If a session error has occurred the PeerConnection is in a possibly
2538 // inconsistent state so fail right away.
2539 if (session_error() != SessionError::kNone) {
2540 std::string error_message = GetSessionErrorMsg();
2541 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2542 observer->OnSetRemoteDescriptionComplete(
2543 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2544 return;
2545 }
Steve Anton71439a62018-02-15 11:53:06 -08002546
Steve Antonba42e992018-04-09 14:10:01 -07002547 if (desc->GetType() == SdpType::kOffer) {
2548 // Report to UMA the format of the received offer.
2549 ReportSdpFormatReceived(*desc);
2550 }
2551
Steve Anton06817cd2018-12-18 15:55:30 -08002552 // Handle remote descriptions missing a=mid lines for interop with legacy end
2553 // points.
2554 FillInMissingRemoteMids(desc->description());
2555
Steve Anton80dd7b52018-02-16 17:08:42 -08002556 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002557 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002558 std::string error_message = GetSetDescriptionErrorMessage(
2559 cricket::CS_REMOTE, desc->GetType(), error);
2560 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002561 observer->OnSetRemoteDescriptionComplete(
2562 RTCError(error.type(), std::move(error_message)));
2563 return;
2564 }
Steve Anton71439a62018-02-15 11:53:06 -08002565
Steve Anton80dd7b52018-02-16 17:08:42 -08002566 // Grab the description type before moving ownership to
2567 // ApplyRemoteDescription, which may destroy it before returning.
2568 const SdpType type = desc->GetType();
2569
2570 error = ApplyRemoteDescription(std::move(desc));
2571 // |desc| may be destroyed at this point.
2572
2573 if (!error.ok()) {
2574 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2575 // inconsistent state, so act conservatively here and set the session error
2576 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2577 SetSessionError(SessionError::kContent, error.message());
2578 std::string error_message =
2579 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2580 RTC_LOG(LS_ERROR) << error_message;
2581 observer->OnSetRemoteDescriptionComplete(
2582 RTCError(error.type(), std::move(error_message)));
2583 return;
2584 }
2585 RTC_DCHECK(remote_description());
2586
2587 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002588 // TODO(deadbeef): We already had to hop to the network thread for
2589 // MaybeStartGathering...
2590 network_thread()->Invoke<void>(
2591 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2592 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002593 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002594 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002595 }
2596
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002597 if (IsUnifiedPlan()) {
2598 bool was_negotiation_needed = is_negotiation_needed_;
2599 UpdateNegotiationNeeded();
2600 if (signaling_state() == kStable && was_negotiation_needed &&
2601 is_negotiation_needed_) {
2602 Observer()->OnRenegotiationNeeded();
2603 }
2604 }
2605
Steve Anton8a006912017-12-04 15:25:56 -08002606 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002607 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002608}
2609
2610RTCError PeerConnection::ApplyRemoteDescription(
2611 std::unique_ptr<SessionDescriptionInterface> desc) {
2612 RTC_DCHECK_RUN_ON(signaling_thread());
2613 RTC_DCHECK(desc);
2614
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615 // Update stats here so that we have the most recent stats for tracks and
2616 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002617 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002618
Steve Antondcc3c022017-12-22 16:02:54 -08002619 // Take a reference to the old remote description since it's used below to
2620 // compare against the new remote description. When setting the new remote
2621 // description, grab ownership of the replaced session description in case it
2622 // is the same as |old_remote_description|, to keep it alive for the duration
2623 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002624 const SessionDescriptionInterface* old_remote_description =
2625 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002626 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002627 SdpType type = desc->GetType();
2628 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002629 replaced_remote_description = pending_remote_description_
2630 ? std::move(pending_remote_description_)
2631 : std::move(current_remote_description_);
2632 current_remote_description_ = std::move(desc);
2633 pending_remote_description_ = nullptr;
2634 current_local_description_ = std::move(pending_local_description_);
2635 } else {
2636 replaced_remote_description = std::move(pending_remote_description_);
2637 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638 }
Steve Anton8a006912017-12-04 15:25:56 -08002639 // The session description to apply now must be accessed by
2640 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002641 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002643 // Report statistics about any use of simulcast.
2644 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2645 *remote_description()->description());
2646
Zhi Huange830e682018-03-30 10:48:35 -07002647 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2648 if (!error.ok()) {
2649 return error;
2650 }
Steve Anton8a006912017-12-04 15:25:56 -08002651 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002652 if (IsUnifiedPlan()) {
2653 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002654 cricket::CS_REMOTE, *remote_description(), local_description(),
2655 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002656 if (!error.ok()) {
2657 return error;
2658 }
Steve Antondcc3c022017-12-22 16:02:54 -08002659 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002660 // Media channels will be created only when offer is set. These may use new
2661 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002662 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002663 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002664 // description is applied. Restore back to old description.
2665 RTCError error = CreateChannels(*remote_description()->description());
2666 if (!error.ok()) {
2667 return error;
2668 }
2669 }
Steve Antondcc3c022017-12-22 16:02:54 -08002670 // Remove unused channels if MediaContentDescription is rejected.
2671 RemoveUnusedChannels(remote_description()->description());
2672 }
Steve Anton8a006912017-12-04 15:25:56 -08002673
Zhi Huange830e682018-03-30 10:48:35 -07002674 // NOTE: Candidates allocation will be initiated only when
2675 // SetLocalDescription is called.
2676 error = UpdateSessionState(type, cricket::CS_REMOTE,
2677 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002678 if (!error.ok()) {
2679 return error;
2680 }
2681
2682 if (local_description() &&
2683 !UseCandidatesInSessionDescription(remote_description())) {
2684 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2685 }
2686
2687 if (old_remote_description) {
2688 for (const cricket::ContentInfo& content :
2689 old_remote_description->description()->contents()) {
2690 // Check if this new SessionDescription contains new ICE ufrag and
2691 // password that indicates the remote peer requests an ICE restart.
2692 // TODO(deadbeef): When we start storing both the current and pending
2693 // remote description, this should reset pending_ice_restarts and compare
2694 // against the current description.
2695 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2696 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002697 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002698 pending_ice_restarts_.insert(content.name);
2699 }
2700 } else {
2701 // We retain all received candidates only if ICE is not restarted.
2702 // When ICE is restarted, all previous candidates belong to an old
2703 // generation and should not be kept.
2704 // TODO(deadbeef): This goes against the W3C spec which says the remote
2705 // description should only contain candidates from the last set remote
2706 // description plus any candidates added since then. We should remove
2707 // this once we're sure it won't break anything.
2708 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2709 old_remote_description, content.name, mutable_remote_description());
2710 }
2711 }
2712 }
2713
2714 if (session_error() != SessionError::kNone) {
2715 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2716 }
2717
2718 // Set the the ICE connection state to connecting since the connection may
2719 // become writable with peer reflexive candidates before any remote candidate
2720 // is signaled.
2721 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2722 // is to have a new signal the indicates a change in checking state from the
2723 // transport and expose a new checking() member from transport that can be
2724 // read to determine the current checking state. The existing SignalConnecting
2725 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002726 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002727 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002728 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2729 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2730 }
2731
deadbeefab9b2d12015-10-14 11:33:11 -07002732 // If setting the description decided our SSL role, allocate any necessary
2733 // SCTP sids.
2734 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002735 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002736 AllocateSctpSids(role);
2737 }
2738
Steve Antondcc3c022017-12-22 16:02:54 -08002739 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002740 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002741 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002742 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002743 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002744 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002745 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002746 const ContentInfo* content =
2747 FindMediaSectionForTransceiver(transceiver, remote_description());
2748 if (!content) {
2749 continue;
2750 }
2751 const MediaContentDescription* media_desc = content->media_description();
2752 RtpTransceiverDirection local_direction =
2753 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002754 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2755 // RTCSessionDescription: Set the associated remote streams given
2756 // transceiver.[[Receiver]], msids, addList, and removeList".
2757 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2758 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2759 std::vector<std::string> stream_ids;
2760 if (!media_desc->streams().empty()) {
2761 // The remote description has signaled the stream IDs.
2762 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002763 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002764 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2765 << " (" << GetStreamIdsString(stream_ids) << ").";
2766 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2767 stream_ids, &added_streams,
2768 &removed_streams);
2769 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2770 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2771 // and transceiver's current direction is neither sendrecv nor recvonly,
2772 // process the addition of a remote track for the media description.
2773 if (!transceiver->fired_direction() ||
2774 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2775 RTC_LOG(LS_INFO)
2776 << "Processing the addition of a remote track for MID="
2777 << content->name << ".";
2778 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002779 }
Steve Antondcc3c022017-12-22 16:02:54 -08002780 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002781 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002782 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2783 // removal of a remote track for the media description, given transceiver,
2784 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002785 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002786 (transceiver->fired_direction() &&
2787 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2788 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2789 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002790 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002791 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002792 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002793 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002794 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002795 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002796 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002797 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002798 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002799 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2800 if (transceiver->mid()) {
2801 auto dtls_transport =
2802 LookupDtlsTransportByMidInternal(*transceiver->mid());
2803 transceiver->internal()->sender_internal()->set_transport(
2804 dtls_transport);
2805 transceiver->internal()->receiver_internal()->set_transport(
2806 dtls_transport);
2807 }
Steve Antondcc3c022017-12-22 16:02:54 -08002808 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002809 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002810 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002811 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002812 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2813 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002814 transceiver->Stop();
2815 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002816 if (!content->rejected &&
2817 RtpTransceiverDirectionHasRecv(local_direction)) {
2818 // Set ssrc to 0 in the case of an unsignalled ssrc.
2819 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002820 if (!media_desc->streams().empty() &&
2821 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002822 ssrc = media_desc->streams()[0].first_ssrc();
2823 }
2824 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002825 }
Steve Antondcc3c022017-12-22 16:02:54 -08002826 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002827 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002828 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002829 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002830 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002831 observer->OnTrack(transceiver);
2832 observer->OnAddTrack(transceiver->receiver(),
2833 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002834 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002835 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002836 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002837 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002838 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002839 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002840 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002841 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002842 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002843 }
Steve Antondcc3c022017-12-22 16:02:54 -08002844 }
2845
Henrik Boströmfdb92012017-11-09 19:55:44 +01002846 const cricket::ContentInfo* audio_content =
2847 GetFirstAudioContent(remote_description()->description());
2848 const cricket::ContentInfo* video_content =
2849 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002850 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002851 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002852 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002853 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002854 const cricket::RtpDataContentDescription* rtp_data_desc =
2855 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002856
2857 // Check if the descriptions include streams, just in case the peer supports
2858 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002859 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002860 (audio_desc && !audio_desc->streams().empty()) ||
2861 (video_desc && !video_desc->streams().empty())) {
2862 remote_peer_supports_msid_ = true;
2863 }
deadbeefab9b2d12015-10-14 11:33:11 -07002864
2865 // We wait to signal new streams until we finish processing the description,
2866 // since only at that point will new streams have all their tracks.
2867 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2868
Steve Antondcc3c022017-12-22 16:02:54 -08002869 if (!IsUnifiedPlan()) {
2870 // TODO(steveanton): When removing RTP senders/receivers in response to a
2871 // rejected media section, there is some cleanup logic that expects the
2872 // voice/ video channel to still be set. But in this method the voice/video
2873 // channel would have been destroyed by the SetRemoteDescription caller
2874 // above so the cleanup that relies on them fails to run. The RemoveSenders
2875 // calls should be moved to right before the DestroyChannel calls to fix
2876 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002877
Steve Antondcc3c022017-12-22 16:02:54 -08002878 // Find all audio rtp streams and create corresponding remote AudioTracks
2879 // and MediaStreams.
2880 if (audio_content) {
2881 if (audio_content->rejected) {
2882 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2883 } else {
2884 bool default_audio_track_needed =
2885 !remote_peer_supports_msid_ &&
2886 RtpTransceiverDirectionHasSend(audio_desc->direction());
2887 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2888 default_audio_track_needed, audio_desc->type(),
2889 new_streams);
2890 }
deadbeeffaac4972015-11-12 15:33:07 -08002891 }
deadbeefab9b2d12015-10-14 11:33:11 -07002892
Steve Antondcc3c022017-12-22 16:02:54 -08002893 // Find all video rtp streams and create corresponding remote VideoTracks
2894 // and MediaStreams.
2895 if (video_content) {
2896 if (video_content->rejected) {
2897 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2898 } else {
2899 bool default_video_track_needed =
2900 !remote_peer_supports_msid_ &&
2901 RtpTransceiverDirectionHasSend(video_desc->direction());
2902 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2903 default_video_track_needed, video_desc->type(),
2904 new_streams);
2905 }
deadbeeffaac4972015-11-12 15:33:07 -08002906 }
deadbeefab9b2d12015-10-14 11:33:11 -07002907
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002908 // If this is an RTP data transport, update the DataChannels with the
2909 // information from the remote peer.
2910 if (rtp_data_desc) {
2911 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002912 }
deadbeefab9b2d12015-10-14 11:33:11 -07002913
Steve Antondcc3c022017-12-22 16:02:54 -08002914 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002915 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002916 for (size_t i = 0; i < new_streams->count(); ++i) {
2917 MediaStreamInterface* new_stream = new_streams->at(i);
2918 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002919 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002920 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2921 }
deadbeefab9b2d12015-10-14 11:33:11 -07002922
Steve Antondcc3c022017-12-22 16:02:54 -08002923 UpdateEndedRemoteMediaStreams();
2924 }
deadbeefab9b2d12015-10-14 11:33:11 -07002925
Steve Anton8a006912017-12-04 15:25:56 -08002926 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002927}
2928
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002929void PeerConnection::SetAssociatedRemoteStreams(
2930 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2931 const std::vector<std::string>& stream_ids,
2932 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2933 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2934 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2935 for (const std::string& stream_id : stream_ids) {
2936 rtc::scoped_refptr<MediaStreamInterface> stream =
2937 remote_streams_->find(stream_id);
2938 if (!stream) {
2939 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2940 MediaStream::Create(stream_id));
2941 remote_streams_->AddStream(stream);
2942 added_streams->push_back(stream);
2943 }
2944 media_streams.push_back(stream);
2945 }
2946 // Special case: "a=msid" missing, use random stream ID.
2947 if (media_streams.empty() &&
2948 !(remote_description()->description()->msid_signaling() &
2949 cricket::kMsidSignalingMediaSection)) {
2950 if (!missing_msid_default_stream_) {
2951 missing_msid_default_stream_ = MediaStreamProxy::Create(
2952 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2953 added_streams->push_back(missing_msid_default_stream_);
2954 }
2955 media_streams.push_back(missing_msid_default_stream_);
2956 }
2957 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2958 receiver->streams();
2959 // SetStreams() will add/remove the receiver's track to/from the streams. This
2960 // differs from the spec - the spec uses an "addList" and "removeList" to
2961 // update the stream-track relationships in a later step. We do this earlier,
2962 // changing the order of things, but the end-result is the same.
2963 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2964 // instead. https://crbug.com/webrtc/9480
2965 receiver->SetStreams(media_streams);
2966 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2967}
2968
Steve Anton0f5400a2018-07-17 14:25:36 -07002969void PeerConnection::ProcessRemovalOfRemoteTrack(
2970 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2971 transceiver,
2972 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2973 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2974 RTC_DCHECK(transceiver->mid());
2975 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2976 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002977 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002978 transceiver->internal()->receiver_internal()->streams();
2979 // This will remove the remote track from the streams.
2980 transceiver->internal()->receiver_internal()->set_stream_ids({});
2981 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002982 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2983}
2984
2985void PeerConnection::RemoveRemoteStreamsIfEmpty(
2986 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2987 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2988 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2989 // streams, see if the stream was removed by checking if this was the last
2990 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002991 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002992 if (remote_stream->GetAudioTracks().empty() &&
2993 remote_stream->GetVideoTracks().empty()) {
2994 remote_streams_->RemoveStream(remote_stream);
2995 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002996 }
2997 }
2998}
2999
Steve Antondcc3c022017-12-22 16:02:54 -08003000RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3001 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003002 const SessionDescriptionInterface& new_session,
3003 const SessionDescriptionInterface* old_local_description,
3004 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003005 RTC_DCHECK(IsUnifiedPlan());
3006
Steve Anton7464fca2018-01-19 11:10:37 -08003007 const cricket::ContentGroup* bundle_group = nullptr;
3008 if (new_session.GetType() == SdpType::kOffer) {
3009 auto bundle_group_or_error =
3010 GetEarlyBundleGroup(*new_session.description());
3011 if (!bundle_group_or_error.ok()) {
3012 return bundle_group_or_error.MoveError();
3013 }
3014 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003015 }
Steve Antondcc3c022017-12-22 16:02:54 -08003016
Steve Antondcc3c022017-12-22 16:02:54 -08003017 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003018 for (size_t i = 0; i < new_contents.size(); ++i) {
3019 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003020 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003021 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003022 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3023 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003024 const cricket::ContentInfo* old_local_content = nullptr;
3025 if (old_local_description &&
3026 i < old_local_description->description()->contents().size()) {
3027 old_local_content =
3028 &old_local_description->description()->contents()[i];
3029 }
3030 const cricket::ContentInfo* old_remote_content = nullptr;
3031 if (old_remote_description &&
3032 i < old_remote_description->description()->contents().size()) {
3033 old_remote_content =
3034 &old_remote_description->description()->contents()[i];
3035 }
Steve Antondcc3c022017-12-22 16:02:54 -08003036 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003037 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3038 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003039 if (!transceiver_or_error.ok()) {
3040 return transceiver_or_error.MoveError();
3041 }
3042 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003043 RTCError error =
3044 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3045 if (!error.ok()) {
3046 return error;
3047 }
3048 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003049 if (GetDataMid() && new_content.name != *GetDataMid()) {
3050 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003051 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3052 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003053 continue;
3054 }
3055 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3056 if (!error.ok()) {
3057 return error;
3058 }
Steve Antondcc3c022017-12-22 16:02:54 -08003059 } else {
3060 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3061 "Unknown section type.");
3062 }
3063 }
3064
3065 return RTCError::OK();
3066}
3067
3068RTCError PeerConnection::UpdateTransceiverChannel(
3069 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3070 transceiver,
3071 const cricket::ContentInfo& content,
3072 const cricket::ContentGroup* bundle_group) {
3073 RTC_DCHECK(IsUnifiedPlan());
3074 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003075 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003076 if (content.rejected) {
3077 if (channel) {
3078 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003079 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003080 }
3081 } else {
3082 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003083 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003084 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003085 } else {
Steve Anton69470252018-02-09 11:43:08 -08003086 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003087 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003088 }
3089 if (!channel) {
3090 LOG_AND_RETURN_ERROR(
3091 RTCErrorType::INTERNAL_ERROR,
3092 "Failed to create channel for mid=" + content.name);
3093 }
3094 transceiver->internal()->SetChannel(channel);
3095 }
3096 }
3097 return RTCError::OK();
3098}
3099
Steve Antonfa2260d2017-12-28 16:38:23 -08003100RTCError PeerConnection::UpdateDataChannel(
3101 cricket::ContentSource source,
3102 const cricket::ContentInfo& content,
3103 const cricket::ContentGroup* bundle_group) {
3104 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003105 // If data channels are disabled, ignore this media section. CreateAnswer
3106 // will take care of rejecting it.
3107 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003108 }
3109 if (content.rejected) {
3110 DestroyDataChannel();
3111 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003112 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003113 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003114 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3115 "Failed to create data channel.");
3116 }
3117 }
3118 if (source == cricket::CS_REMOTE) {
3119 const MediaContentDescription* data_desc = content.media_description();
3120 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3121 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3122 }
3123 }
3124 }
3125 return RTCError::OK();
3126}
3127
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003128// This method will extract any send encodings that were sent by the remote
3129// connection. This is currently only relevant for Simulcast scenario (where
3130// the number of layers may be communicated by the server).
3131static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3132 const MediaContentDescription& desc) {
3133 if (!desc.HasSimulcast()) {
3134 return {};
3135 }
3136 std::vector<RtpEncodingParameters> result;
3137 const SimulcastDescription& simulcast = desc.simulcast_description();
3138
3139 // This is a remote description, the parameters we are after should appear
3140 // as receive streams.
3141 for (const auto& alternatives : simulcast.receive_layers()) {
3142 RTC_DCHECK(!alternatives.empty());
3143 // There is currently no way to specify or choose from alternatives.
3144 // We will always use the first alternative, which is the most preferred.
3145 const SimulcastLayer& layer = alternatives[0];
3146 RtpEncodingParameters parameters;
3147 parameters.rid = layer.rid;
3148 parameters.active = !layer.is_paused;
3149 result.push_back(parameters);
3150 }
3151
3152 return result;
3153}
3154
3155static RTCError UpdateSimulcastLayerStatusInSender(
3156 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003157 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003158 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003159 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003160 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003161
3162 // The simulcast envelope cannot be changed, only the status of the streams.
3163 // So we will iterate over the send encodings rather than the layers.
3164 for (RtpEncodingParameters& encoding : parameters.encodings) {
3165 auto iter = std::find_if(layers.begin(), layers.end(),
3166 [&encoding](const SimulcastLayer& layer) {
3167 return layer.rid == encoding.rid;
3168 });
3169 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003170 if (iter == layers.end()) {
3171 disabled_layers.push_back(encoding.rid);
3172 continue;
3173 }
3174
3175 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003176 }
3177
Amit Hilbuch619b2942019-02-26 15:55:19 -08003178 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003179 if (result.ok()) {
3180 result = sender->DisableEncodingLayers(disabled_layers);
3181 }
3182
3183 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003184}
3185
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003186static bool SimulcastIsRejected(
3187 const ContentInfo* local_content,
3188 const MediaContentDescription& answer_media_desc) {
3189 bool simulcast_offered = local_content &&
3190 local_content->media_description() &&
3191 local_content->media_description()->HasSimulcast();
3192 bool simulcast_answered = answer_media_desc.HasSimulcast();
3193 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3194 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3195 return simulcast_offered && (!simulcast_answered || !rids_supported);
3196}
3197
Amit Hilbuch2297d332019-02-19 12:49:22 -08003198static RTCError DisableSimulcastInSender(
3199 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003200 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003201 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003202 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003203 return RTCError::OK();
3204 }
3205
Amit Hilbuch2297d332019-02-19 12:49:22 -08003206 std::vector<std::string> disabled_layers;
3207 std::transform(
3208 parameters.encodings.begin() + 1, parameters.encodings.end(),
3209 std::back_inserter(disabled_layers),
3210 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3211 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003212}
3213
Steve Antondcc3c022017-12-22 16:02:54 -08003214RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3215PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003216 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003217 size_t mline_index,
3218 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003219 const ContentInfo* old_local_content,
3220 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003221 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003222 // If this is an offer then the m= section might be recycled. If the m=
3223 // section is being recycled (defined as: rejected in the current local or
3224 // remote description and not rejected in new description), dissociate the
3225 // currently associated RtpTransceiver by setting its mid property to null,
3226 // and discard the mapping between the transceiver and its m= section index.
3227 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3228 old_remote_content)) {
3229 // We want to dissociate the transceiver that has the rejected mid.
3230 const std::string& old_mid =
3231 (old_local_content && old_local_content->rejected)
3232 ? old_local_content->name
3233 : old_remote_content->name;
3234 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003235 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003236 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3237 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003238 old_transceiver->internal()->set_mid(absl::nullopt);
3239 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003240 }
3241 }
3242 const MediaContentDescription* media_desc = content.media_description();
3243 auto transceiver = GetAssociatedTransceiver(content.name);
3244 if (source == cricket::CS_LOCAL) {
3245 // Find the RtpTransceiver that corresponds to this m= section, using the
3246 // mapping between transceivers and m= section indices established when
3247 // creating the offer.
3248 if (!transceiver) {
3249 transceiver = GetTransceiverByMLineIndex(mline_index);
3250 }
3251 if (!transceiver) {
3252 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3253 "Unknown transceiver");
3254 }
3255 } else {
3256 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3257 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3258 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003259 // When simulcast is requested, a transceiver cannot be associated because
3260 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003261 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003262 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3263 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003264 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3265 }
3266 // If no RtpTransceiver was found in the previous step, create one with a
3267 // recvonly direction.
3268 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003269 RTC_LOG(LS_INFO) << "Adding "
3270 << cricket::MediaTypeToString(media_desc->type())
3271 << " transceiver for MID=" << content.name
3272 << " at i=" << mline_index
3273 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003274 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003275 std::vector<RtpEncodingParameters> send_encodings =
3276 GetSendEncodingsFromRemoteDescription(*media_desc);
3277 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3278 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003279 std::string receiver_id;
3280 if (!media_desc->streams().empty()) {
3281 receiver_id = media_desc->streams()[0].id;
3282 } else {
3283 receiver_id = rtc::CreateRandomUuid();
3284 }
3285 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003286 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003287 transceiver->internal()->set_direction(
3288 RtpTransceiverDirection::kRecvOnly);
3289 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003290
3291 // Check if the offer indicated simulcast but the answer rejected it.
3292 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003293 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003294 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003295 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003296 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003297 if (!error.ok()) {
3298 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3299 return std::move(error);
3300 }
3301 }
Steve Antondcc3c022017-12-22 16:02:54 -08003302 }
3303 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003304 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003305 LOG_AND_RETURN_ERROR(
3306 RTCErrorType::INVALID_PARAMETER,
3307 "Transceiver type does not match media description type.");
3308 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003309 if (media_desc->HasSimulcast()) {
3310 std::vector<SimulcastLayer> layers =
3311 source == cricket::CS_LOCAL
3312 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3313 : media_desc->simulcast_description()
3314 .receive_layers()
3315 .GetAllLayers();
3316 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003317 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003318 if (!error.ok()) {
3319 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3320 return std::move(error);
3321 }
3322 }
Steve Antondcc3c022017-12-22 16:02:54 -08003323 // Associate the found or created RtpTransceiver with the m= section by
3324 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3325 // section, and establish a mapping between the transceiver and the index of
3326 // the m= section.
3327 transceiver->internal()->set_mid(content.name);
3328 transceiver->internal()->set_mline_index(mline_index);
3329 return std::move(transceiver);
3330}
3331
3332rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3333PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3334 RTC_DCHECK(IsUnifiedPlan());
3335 for (auto transceiver : transceivers_) {
3336 if (transceiver->mid() == mid) {
3337 return transceiver;
3338 }
3339 }
3340 return nullptr;
3341}
3342
3343rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3344PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3345 RTC_DCHECK(IsUnifiedPlan());
3346 for (auto transceiver : transceivers_) {
3347 if (transceiver->internal()->mline_index() == mline_index) {
3348 return transceiver;
3349 }
3350 }
3351 return nullptr;
3352}
3353
3354rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3355PeerConnection::FindAvailableTransceiverToReceive(
3356 cricket::MediaType media_type) const {
3357 RTC_DCHECK(IsUnifiedPlan());
3358 // From JSEP section 5.10 (Applying a Remote Description):
3359 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3360 // the same type that were added to the PeerConnection by addTrack and are not
3361 // associated with any m= section and are not stopped, find the first such
3362 // RtpTransceiver.
3363 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003364 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003365 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3366 !transceiver->stopped()) {
3367 return transceiver;
3368 }
3369 }
3370 return nullptr;
3371}
3372
Steve Antoned10bd92017-12-05 10:52:59 -08003373const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3374 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3375 transceiver,
3376 const SessionDescriptionInterface* sdesc) const {
3377 RTC_DCHECK(transceiver);
3378 RTC_DCHECK(sdesc);
3379 if (IsUnifiedPlan()) {
3380 if (!transceiver->internal()->mid()) {
3381 // This transceiver is not associated with a media section yet.
3382 return nullptr;
3383 }
3384 return sdesc->description()->GetContentByName(
3385 *transceiver->internal()->mid());
3386 } else {
3387 // Plan B only allows at most one audio and one video section, so use the
3388 // first media section of that type.
3389 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003390 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003391 }
3392}
3393
deadbeef46c73892016-11-16 19:42:04 -08003394PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003395 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003396 return configuration_;
3397}
3398
deadbeef293e9262017-01-11 12:28:30 -08003399bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3400 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003401 RTC_DCHECK_RUN_ON(signaling_thread());
3402 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003403 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003404 if (IsClosed()) {
3405 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3406 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3407 }
3408
Qingsi Wanga2d60672018-04-11 16:57:45 -07003409 // According to JSEP, after setLocalDescription, changing the candidate pool
3410 // size is not allowed, and changing the set of ICE servers will not result
3411 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003412 if (local_description() && configuration.ice_candidate_pool_size !=
3413 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003414 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3415 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003416 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003417 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003418
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003419 if (local_description() &&
3420 configuration.use_media_transport != configuration_.use_media_transport) {
3421 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3422 "SetLocalDescription.";
3423 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3424 }
3425
3426 if (remote_description() &&
3427 configuration.use_media_transport != configuration_.use_media_transport) {
3428 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3429 "SetRemoteDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003433 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003434 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 SetLocalDescription.";
3438 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3439 }
3440
3441 if (remote_description() &&
3442 configuration.use_media_transport_for_data_channels !=
3443 configuration_.use_media_transport_for_data_channels) {
3444 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3445 "after calling SetRemoteDescription.";
3446 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3447 }
3448
3449 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003450 configuration.crypto_options != configuration_.crypto_options) {
3451 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3452 "SetLocalDescription.";
3453 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3454 }
3455
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003456 if (local_description() && configuration.use_datagram_transport !=
3457 configuration_.use_datagram_transport) {
3458 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3459 "after calling SetLocalDescription.";
3460 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3461 }
3462
3463 if (remote_description() && configuration.use_datagram_transport !=
3464 configuration_.use_datagram_transport) {
3465 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3466 "after calling SetRemoteDescription.";
3467 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3468 }
3469
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003470 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003471 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003472 (configuration.use_datagram_transport &&
3473 *configuration.use_datagram_transport)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003474 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3475 << "Media transport requires MaxBundle policy.";
3476 }
3477
deadbeef293e9262017-01-11 12:28:30 -08003478 // The simplest (and most future-compatible) way to tell if the config was
3479 // modified in an invalid way is to copy each property we do support
3480 // modifying, then use operator==. There are far more properties we don't
3481 // support modifying than those we do, and more could be added.
3482 RTCConfiguration modified_config = configuration_;
3483 modified_config.servers = configuration.servers;
3484 modified_config.type = configuration.type;
3485 modified_config.ice_candidate_pool_size =
3486 configuration.ice_candidate_pool_size;
3487 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003488 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3489 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003490 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003491 modified_config.ice_check_interval_strong_connectivity =
3492 configuration.ice_check_interval_strong_connectivity;
3493 modified_config.ice_check_interval_weak_connectivity =
3494 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003495 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3496 modified_config.ice_unwritable_min_checks =
3497 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003498 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003499 modified_config.stun_candidate_keepalive_interval =
3500 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003501 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003502 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003503 modified_config.active_reset_srtp_params =
3504 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003505 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003506 modified_config.use_media_transport_for_data_channels =
3507 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003508 modified_config.use_datagram_transport = configuration.use_datagram_transport;
deadbeef293e9262017-01-11 12:28:30 -08003509 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003510 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003511 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3512 }
3513
Steve Anton038834f2017-07-14 15:59:59 -07003514 // Validate the modified configuration.
3515 RTCError validate_error = ValidateConfiguration(modified_config);
3516 if (!validate_error.ok()) {
3517 return SafeSetError(std::move(validate_error), error);
3518 }
3519
deadbeef293e9262017-01-11 12:28:30 -08003520 // Note that this isn't possible through chromium, since it's an unsigned
3521 // short in WebIDL.
3522 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003523 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003524 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3525 }
3526
3527 // Parse ICE servers before hopping to network thread.
3528 cricket::ServerAddresses stun_servers;
3529 std::vector<cricket::RelayServerConfig> turn_servers;
3530 RTCErrorType parse_error =
3531 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3532 if (parse_error != RTCErrorType::NONE) {
3533 return SafeSetError(parse_error, error);
3534 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003535 // Note if STUN or TURN servers were supplied.
3536 if (!stun_servers.empty()) {
3537 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3538 }
3539 if (!turn_servers.empty()) {
3540 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3541 }
deadbeef293e9262017-01-11 12:28:30 -08003542
3543 // In theory this shouldn't fail.
3544 if (!network_thread()->Invoke<bool>(
3545 RTC_FROM_HERE,
3546 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3547 stun_servers, turn_servers, modified_config.type,
3548 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003549 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003550 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003551 modified_config.stun_candidate_keepalive_interval,
3552 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003553 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003554 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3555 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003556
deadbeefd1a38b52016-12-10 13:15:33 -08003557 // As described in JSEP, calling setConfiguration with new ICE servers or
3558 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3559 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003560 if (modified_config.servers != configuration_.servers ||
3561 modified_config.type != configuration_.type ||
3562 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003563 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003564 }
skvladd1f5fda2017-02-03 16:54:05 -08003565
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003566 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003567
3568 use_datagram_transport_ = datagram_transport_config_.enabled &&
3569 modified_config.use_datagram_transport.value_or(
3570 datagram_transport_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003571 transport_controller_->SetMediaTransportSettings(
3572 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003573 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003574 use_datagram_transport_);
skvladd1f5fda2017-02-03 16:54:05 -08003575
Zhi Huangb57e1692018-06-12 11:41:11 -07003576 if (configuration_.active_reset_srtp_params !=
3577 modified_config.active_reset_srtp_params) {
3578 transport_controller_->SetActiveResetSrtpParams(
3579 modified_config.active_reset_srtp_params);
3580 }
3581
deadbeef293e9262017-01-11 12:28:30 -08003582 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003583 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003584 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003585}
3586
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003587bool PeerConnection::AddIceCandidate(
3588 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003589 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003590 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003591 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003592 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003593 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003594 return false;
3595 }
Steve Antond25da372017-11-06 14:50:29 -08003596
3597 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003598 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003599 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003600 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003601 return false;
3602 }
3603
3604 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003605 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003606 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003607 return false;
3608 }
3609
3610 bool valid = false;
3611 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3612 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003613 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003614 return false;
3615 }
3616
3617 // Add this candidate to the remote session description.
3618 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003619 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003620 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003621 return false;
3622 }
3623
3624 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003625 bool result = UseCandidate(ice_candidate);
3626 if (result) {
3627 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003628 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3629 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3630 }
3631 if (ice_candidate->candidate().address().IsPrivateIP()) {
3632 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3633 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003634 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3635 } else {
3636 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3637 }
3638 return result;
Steve Antond25da372017-11-06 14:50:29 -08003639 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003640 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003641 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003642 return true;
3643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003644}
3645
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003646bool PeerConnection::RemoveIceCandidates(
3647 const std::vector<cricket::Candidate>& candidates) {
3648 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003649 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003650 if (IsClosed()) {
3651 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3652 return false;
3653 }
3654
Steve Antond25da372017-11-06 14:50:29 -08003655 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003656 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3657 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003658 return false;
3659 }
3660
3661 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003662 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003663 return false;
3664 }
3665
3666 size_t number_removed =
3667 mutable_remote_description()->RemoveCandidates(candidates);
3668 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003669 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003670 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003671 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003672 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003673 }
3674
3675 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003676 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3677 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003678 RTC_LOG(LS_ERROR)
3679 << "RemoveIceCandidates: Error when removing remote candidates: "
3680 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003681 }
3682 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003683}
3684
Niels Möller0c4f7be2018-05-07 14:01:37 +02003685RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003686 if (!worker_thread()->IsCurrent()) {
3687 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003688 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003689 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003690 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003691
Niels Möller0c4f7be2018-05-07 14:01:37 +02003692 const bool has_min = bitrate.min_bitrate_bps.has_value();
3693 const bool has_start = bitrate.start_bitrate_bps.has_value();
3694 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003695 if (has_min && *bitrate.min_bitrate_bps < 0) {
3696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3697 "min_bitrate_bps <= 0");
3698 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003699 if (has_start) {
3700 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003701 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003702 "start_bitrate_bps < min_bitrate_bps");
3703 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3705 "curent_bitrate_bps < 0");
3706 }
3707 }
3708 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003709 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003710 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003711 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003712 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3713 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3714 "max_bitrate_bps < min_bitrate_bps");
3715 } else if (*bitrate.max_bitrate_bps < 0) {
3716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3717 "max_bitrate_bps < 0");
3718 }
3719 }
3720
zstein4b979802017-06-02 14:37:37 -07003721 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003722 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003723
3724 return RTCError::OK();
3725}
3726
henrika5f6bf242017-11-01 11:06:56 +01003727void PeerConnection::SetAudioPlayout(bool playout) {
3728 if (!worker_thread()->IsCurrent()) {
3729 worker_thread()->Invoke<void>(
3730 RTC_FROM_HERE,
3731 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3732 return;
3733 }
3734 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003735 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003736 audio_state->SetPlayout(playout);
3737}
3738
3739void PeerConnection::SetAudioRecording(bool recording) {
3740 if (!worker_thread()->IsCurrent()) {
3741 worker_thread()->Invoke<void>(
3742 RTC_FROM_HERE,
3743 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3744 return;
3745 }
3746 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003747 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003748 audio_state->SetRecording(recording);
3749}
3750
Steve Anton8c0f7a72017-10-03 10:03:10 -07003751std::unique_ptr<rtc::SSLCertificate>
3752PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003753 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3754 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003755 return nullptr;
3756 }
Steve Antonf25303e2018-10-16 15:23:31 -07003757 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003758}
3759
Zhi Huang70b820f2018-01-27 14:16:15 -08003760std::unique_ptr<rtc::SSLCertChain>
3761PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003762 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003763 auto audio_transceiver = GetFirstAudioTransceiver();
3764 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003765 return nullptr;
3766 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003767 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003768 audio_transceiver->internal()->channel()->transport_name());
3769}
3770
3771rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3772PeerConnection::GetFirstAudioTransceiver() const {
3773 for (auto transceiver : transceivers_) {
3774 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3775 return transceiver;
3776 }
3777 }
3778 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003779}
3780
Bjorn Tereliusde939432017-11-20 17:38:14 +01003781bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3782 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003783 // TODO(eladalon): In C++14, this can be done with a lambda.
3784 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003785 bool operator()() {
3786 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3787 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003788 PeerConnection* const pc;
3789 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003790 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003791 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003792 return worker_thread()->Invoke<bool>(
3793 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003794}
3795
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003796bool PeerConnection::StartRtcEventLog(
3797 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003798 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3799 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3800 output_period_ms = 5000;
3801 }
3802 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003803}
3804
ivoc14d5dbe2016-07-04 07:06:55 -07003805void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003806 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003807 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3808}
3809
Harald Alvestrandad88c882018-11-28 16:47:46 +01003810rtc::scoped_refptr<DtlsTransportInterface>
3811PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003812 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003813 return transport_controller_->LookupDtlsTransportByMid(mid);
3814}
3815
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003816rtc::scoped_refptr<DtlsTransport>
3817PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003818 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003819 return transport_controller_->LookupDtlsTransportByMid(mid);
3820}
3821
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003822rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3823 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003824 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003825 return sctp_transport_;
3826}
3827
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003828const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003829 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003830 return pending_local_description_ ? pending_local_description_.get()
3831 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003832}
3833
3834const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003835 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003836 return pending_remote_description_ ? pending_remote_description_.get()
3837 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003838}
3839
deadbeeffe4a8a42016-12-20 17:56:17 -08003840const SessionDescriptionInterface* PeerConnection::current_local_description()
3841 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003842 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003843 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003844}
3845
3846const SessionDescriptionInterface* PeerConnection::current_remote_description()
3847 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003848 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003849 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003850}
3851
3852const SessionDescriptionInterface* PeerConnection::pending_local_description()
3853 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003854 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003855 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003856}
3857
3858const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3859 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003860 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003861 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003862}
3863
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003864void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003865 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003866 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003867 // Update stats here so that we have the most recent stats for tracks and
3868 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003869 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003870
Steve Anton75737c02017-11-06 10:37:17 -08003871 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003872 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003873
Mirko Bonadei739baf02019-01-27 17:29:42 +01003874 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003875 transceiver->Stop();
3876 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003877
3878 // Ensure that all asynchronous stats requests are completed before destroying
3879 // the transport controller below.
3880 if (stats_collector_) {
3881 stats_collector_->WaitForPendingRequest();
3882 }
3883
3884 // Don't destroy BaseChannels until after stats has been cleaned up so that
3885 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003886 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003887
Qingsi Wang93a84392018-01-30 17:13:09 -08003888 // The event log is used in the transport controller, which must be outlived
3889 // by the former. CreateOffer by the peer connection is implemented
3890 // asynchronously and if the peer connection is closed without resetting the
3891 // WebRTC session description factory, the session description factory would
3892 // call the transport controller.
3893 webrtc_session_desc_factory_.reset();
3894 transport_controller_.reset();
3895
deadbeef42a42632017-03-10 15:18:00 -08003896 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003897 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3898 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003899
Steve Anton978b8762017-09-29 12:15:02 -07003900 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003901 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003902 call_.reset();
3903 // The event log must outlive call (and any other object that uses it).
3904 event_log_.reset();
3905 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003906 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003907 // The .h file says that observer can be discarded after close() returns.
3908 // Make sure this is true.
3909 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003910}
3911
Steve Antonad182762018-09-05 20:22:40 +00003912void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003913 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003914 switch (msg->message_id) {
3915 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3916 SetSessionDescriptionMsg* param =
3917 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3918 param->observer->OnSuccess();
3919 delete param;
3920 break;
3921 }
3922 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3923 SetSessionDescriptionMsg* param =
3924 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3925 param->observer->OnFailure(std::move(param->error));
3926 delete param;
3927 break;
3928 }
3929 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3930 CreateSessionDescriptionMsg* param =
3931 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3932 param->observer->OnFailure(std::move(param->error));
3933 delete param;
3934 break;
3935 }
3936 case MSG_GETSTATS: {
3937 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3938 StatsReports reports;
3939 stats_->GetStats(param->track, &reports);
3940 param->observer->OnComplete(reports);
3941 delete param;
3942 break;
3943 }
3944 case MSG_FREE_DATACHANNELS: {
3945 sctp_data_channels_to_free_.clear();
3946 break;
3947 }
3948 case MSG_REPORT_USAGE_PATTERN: {
3949 ReportUsagePattern();
3950 break;
3951 }
3952 default:
3953 RTC_NOTREACHED() << "Not implemented";
3954 break;
3955 }
3956}
3957
Steve Antonafb0bb72018-02-20 11:35:37 -08003958cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3959 RTC_DCHECK(!IsUnifiedPlan());
3960 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3961 GetAudioTransceiver()->internal()->channel());
3962 if (voice_channel) {
3963 return voice_channel->media_channel();
3964 } else {
3965 return nullptr;
3966 }
3967}
3968
3969cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3970 RTC_DCHECK(!IsUnifiedPlan());
3971 auto* video_channel = static_cast<cricket::VideoChannel*>(
3972 GetVideoTransceiver()->internal()->channel());
3973 if (video_channel) {
3974 return video_channel->media_channel();
3975 } else {
3976 return nullptr;
3977 }
3978}
3979
Steve Anton4171afb2017-11-20 10:20:22 -08003980void PeerConnection::CreateAudioReceiver(
3981 MediaStreamInterface* stream,
3982 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003983 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3984 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003985 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3986 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003987 auto* audio_receiver = new AudioRtpReceiver(
3988 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003989 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003990 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3991 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3992 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003993 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003994 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003995 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003996}
3997
Steve Anton4171afb2017-11-20 10:20:22 -08003998void PeerConnection::CreateVideoReceiver(
3999 MediaStreamInterface* stream,
4000 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004001 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4002 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004003 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4004 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004005 auto* video_receiver = new VideoRtpReceiver(
4006 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004007 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004008 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4009 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4010 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004011 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004012 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004013 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004014}
4015
deadbeef70ab1a12015-09-28 16:53:55 -07004016// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4017// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004018rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004019 const RtpSenderInfo& remote_sender_info) {
4020 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4021 if (!receiver) {
4022 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4023 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004024 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004025 }
Steve Anton4171afb2017-11-20 10:20:22 -08004026 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4027 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4028 } else {
4029 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4030 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004031 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004032}
4033
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004034void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4035 MediaStreamInterface* stream) {
4036 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004037 RTC_DCHECK(track);
4038 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004039 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004040 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004041 // We already have a sender for this track, so just change the stream_id
4042 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004043 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004044 return;
4045 }
4046
4047 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004048 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004049 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004050 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004051 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004052 // If the sender has already been configured in SDP, we call SetSsrc,
4053 // which will connect the sender to the underlying transport. This can
4054 // occur if a local session description that contains the ID of the sender
4055 // is set before AddStream is called. It can also occur if the local
4056 // session description is not changed and RemoveStream is called, and
4057 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004058 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004059 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004060 if (sender_info) {
4061 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004062 }
4063}
4064
4065// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4066// indefinitely, when we have unified plan SDP.
4067void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4068 MediaStreamInterface* stream) {
4069 RTC_DCHECK(!IsClosed());
4070 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004071 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004072 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4073 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004074 return;
4075 }
Steve Anton4171afb2017-11-20 10:20:22 -08004076 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004077}
4078
4079void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4080 MediaStreamInterface* stream) {
4081 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004082 RTC_DCHECK(track);
4083 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004084 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004085 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004086 // We already have a sender for this track, so just change the stream_id
4087 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004088 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004089 return;
4090 }
4091
4092 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004093 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004094 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004095 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004096 GetVideoTransceiver()->internal()->AddSender(new_sender);
4097 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004098 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004099 if (sender_info) {
4100 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004101 }
4102}
4103
4104void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4105 MediaStreamInterface* stream) {
4106 RTC_DCHECK(!IsClosed());
4107 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004108 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4110 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004111 return;
4112 }
Steve Anton4171afb2017-11-20 10:20:22 -08004113 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004114}
4115
Steve Antonba818672017-11-06 10:21:57 -08004116void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004117 if (ice_connection_state_ == new_state) {
4118 return;
4119 }
4120
deadbeefcbecd352015-09-23 11:50:27 -07004121 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004122 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004123 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004124 return;
4125 }
Steve Antonba818672017-11-06 10:21:57 -08004126
Mirko Bonadei675513b2017-11-09 11:09:25 +01004127 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4128 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004129 RTC_DCHECK(ice_connection_state_ !=
4130 PeerConnectionInterface::kIceConnectionClosed);
4131
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004132 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004133 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004134}
4135
Alex Loiko9289eda2018-11-23 16:18:59 +00004136void PeerConnection::SetStandardizedIceConnectionState(
4137 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004138 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004139 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004140 }
4141
4142 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004143 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004144 }
4145
4146 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4147 << standardized_ice_connection_state_ << " => " << new_state;
4148
Alex Loiko9289eda2018-11-23 16:18:59 +00004149 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004150 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004151}
4152
Jonas Olsson635474e2018-10-18 15:58:17 +02004153void PeerConnection::SetConnectionState(
4154 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004155 if (connection_state_ == new_state)
4156 return;
4157 if (IsClosed())
4158 return;
4159 connection_state_ = new_state;
4160 Observer()->OnConnectionChange(new_state);
4161}
4162
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004163void PeerConnection::OnIceGatheringChange(
4164 PeerConnectionInterface::IceGatheringState new_state) {
4165 if (IsClosed()) {
4166 return;
4167 }
4168 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004169 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004170}
4171
jbauch81bf7b02017-03-25 08:31:12 -07004172void PeerConnection::OnIceCandidate(
4173 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004174 if (IsClosed()) {
4175 return;
4176 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004177 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004178 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4179 candidate->candidate().address().IsPrivateIP()) {
4180 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4181 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004182 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4183 candidate->candidate().address().IsUnresolvedIP()) {
4184 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4185 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004186 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004187}
4188
Eldar Relloda13ea22019-06-01 12:23:43 +03004189void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4190 const std::string& url,
4191 int error_code,
4192 const std::string& error_text) {
4193 if (IsClosed()) {
4194 return;
4195 }
4196 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4197}
4198
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004199void PeerConnection::OnIceCandidatesRemoved(
4200 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004201 if (IsClosed()) {
4202 return;
4203 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004204 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004205}
4206
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004207void PeerConnection::ChangeSignalingState(
4208 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004209 if (signaling_state_ == signaling_state) {
4210 return;
4211 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004212 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4213 << GetSignalingStateString(signaling_state_)
4214 << " New state: "
4215 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004216 signaling_state_ = signaling_state;
4217 if (signaling_state == kClosed) {
4218 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004219 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004220 standardized_ice_connection_state_ =
4221 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004222 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4223 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004224 if (ice_gathering_state_ != kIceGatheringComplete) {
4225 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004226 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004227 }
4228 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004229 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004230}
4231
deadbeefeb459812015-12-15 19:24:43 -08004232void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4233 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004234 if (IsClosed()) {
4235 return;
4236 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004237 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004238 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004239}
4240
deadbeefeb459812015-12-15 19:24:43 -08004241void PeerConnection::OnAudioTrackRemoved(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 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004247 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004248}
4249
4250void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4251 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004252 if (IsClosed()) {
4253 return;
4254 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004255 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004256 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004257}
4258
4259void PeerConnection::OnVideoTrackRemoved(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 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004265 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004266}
4267
Henrik Boström31638672017-11-23 17:48:32 +01004268void PeerConnection::PostSetSessionDescriptionSuccess(
4269 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004270 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4271 signaling_thread()->Post(RTC_FROM_HERE, this,
4272 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004273}
4274
deadbeefab9b2d12015-10-14 11:33:11 -07004275void PeerConnection::PostSetSessionDescriptionFailure(
4276 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004277 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004278 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004279 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4280 msg->error = std::move(error);
4281 signaling_thread()->Post(RTC_FROM_HERE, this,
4282 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004283}
4284
4285void PeerConnection::PostCreateSessionDescriptionFailure(
4286 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004287 RTCError error) {
4288 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004289 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4290 msg->error = std::move(error);
4291 signaling_thread()->Post(RTC_FROM_HERE, this,
4292 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004293}
4294
zhihuang1c378ed2017-08-17 14:10:50 -07004295void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004296 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004297 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004298 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004299
Steve Antondcc3c022017-12-22 16:02:54 -08004300 if (IsUnifiedPlan()) {
4301 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4302 } else {
4303 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4304 }
4305
Steve Antonfa2260d2017-12-28 16:38:23 -08004306 // Intentionally unset the data channel type for RTP data channel with the
4307 // second condition. Otherwise the RTP data channels would be successfully
4308 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4309 // when building with chromium. We want to leave RTP data channels broken, so
4310 // people won't try to use them.
4311 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4312 session_options->data_channel_type = data_channel_type();
4313 }
4314
Steve Antondcc3c022017-12-22 16:02:54 -08004315 // Apply ICE restart flag and renomination flag.
4316 for (auto& options : session_options->media_description_options) {
4317 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4318 options.transport_options.enable_ice_renomination =
4319 configuration_.enable_ice_renomination;
4320 }
4321
4322 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004323 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004324 session_options->pooled_ice_credentials =
4325 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4326 RTC_FROM_HERE,
4327 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4328 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004329 session_options->offer_extmap_allow_mixed =
4330 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004331
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004332 if (configuration_.use_media_transport ||
4333 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004334 session_options->media_transport_settings =
4335 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4336 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004337
4338 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004339 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004340 for (auto& options : session_options->media_description_options) {
4341 options.transport_options.opaque_parameters =
4342 transport_controller_->GetTransportParameters(options.mid);
4343 }
4344 }
4345
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004346 // Allow fallback for using obsolete SCTP syntax.
4347 // Note that the default in |session_options| is true, while
4348 // the default in |options| is false.
4349 session_options->use_obsolete_sctp_sdp =
4350 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004351}
4352
4353void PeerConnection::GetOptionsForPlanBOffer(
4354 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4355 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004356 // Figure out transceiver directional preferences.
4357 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4358 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4359
4360 // By default, generate sendrecv/recvonly m= sections.
4361 bool recv_audio = true;
4362 bool recv_video = true;
4363
4364 // By default, only offer a new m= section if we have media to send with it.
4365 bool offer_new_audio_description = send_audio;
4366 bool offer_new_video_description = send_video;
4367 bool offer_new_data_description = HasDataChannels();
4368
4369 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004370 if (offer_answer_options.offer_to_receive_audio !=
4371 RTCOfferAnswerOptions::kUndefined) {
4372 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004373 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004374 offer_new_audio_description ||
4375 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004376 }
Steve Antondcc3c022017-12-22 16:02:54 -08004377 if (offer_answer_options.offer_to_receive_video !=
4378 RTCOfferAnswerOptions::kUndefined) {
4379 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004380 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004381 offer_new_video_description ||
4382 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004383 }
4384
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004385 absl::optional<size_t> audio_index;
4386 absl::optional<size_t> video_index;
4387 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004388 // If a current description exists, generate m= sections in the same order,
4389 // using the first audio/video/data section that appears and rejecting
4390 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004391 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004392 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004393 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004394 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4395 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4396 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004397 }
4398
zhihuang1c378ed2017-08-17 14:10:50 -07004399 // Add audio/video/data m= sections to the end if needed.
4400 if (!audio_index && offer_new_audio_description) {
4401 session_options->media_description_options.push_back(
4402 cricket::MediaDescriptionOptions(
4403 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004404 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4405 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004406 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004407 }
zhihuang1c378ed2017-08-17 14:10:50 -07004408 if (!video_index && offer_new_video_description) {
4409 session_options->media_description_options.push_back(
4410 cricket::MediaDescriptionOptions(
4411 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004412 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4413 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004414 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004415 }
zhihuang1c378ed2017-08-17 14:10:50 -07004416 if (!data_index && offer_new_data_description) {
4417 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004418 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004419 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004420 }
4421
4422 cricket::MediaDescriptionOptions* audio_media_description_options =
4423 !audio_index ? nullptr
4424 : &session_options->media_description_options[*audio_index];
4425 cricket::MediaDescriptionOptions* video_media_description_options =
4426 !video_index ? nullptr
4427 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004428
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004429 AddPlanBRtpSenderOptions(GetSendersInternal(),
4430 audio_media_description_options,
4431 video_media_description_options,
4432 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004433}
4434
Steve Antondcc3c022017-12-22 16:02:54 -08004435static cricket::MediaDescriptionOptions
4436GetMediaDescriptionOptionsForTransceiver(
4437 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4438 transceiver,
4439 const std::string& mid) {
4440 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004441 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004442 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004443 media_description_options.codec_preferences =
4444 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004445 // This behavior is specified in JSEP. The gist is that:
4446 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4447 // sendrecv.
4448 // 2. If the MSID is included, then it must be included in any subsequent
4449 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004450 if (transceiver->stopped() ||
4451 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4452 !transceiver->internal()->has_ever_been_used_to_send())) {
4453 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004454 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004455
4456 cricket::SenderOptions sender_options;
4457 sender_options.track_id = transceiver->sender()->id();
4458 sender_options.stream_ids = transceiver->sender()->stream_ids();
4459
4460 // The following sets up RIDs and Simulcast.
4461 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004462 RtpParameters send_parameters =
4463 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004464 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4465 send_parameters.encodings.end(),
4466 [](const RtpEncodingParameters& encoding) {
4467 return !encoding.rid.empty();
4468 });
4469
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004470 std::vector<RidDescription> send_rids;
4471 SimulcastLayerList send_layers;
4472 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4473 if (encoding.rid.empty()) {
4474 continue;
4475 }
4476 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4477 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4478 }
4479
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004480 if (has_rids) {
4481 sender_options.rids = send_rids;
4482 }
4483
4484 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004485 // When RIDs are configured, we must set num_sim_layers to 0 to.
4486 // Otherwise, num_sim_layers must be 1 because either there is no
4487 // simulcast, or simulcast is acheived by munging the SDP.
4488 sender_options.num_sim_layers = has_rids ? 0 : 1;
4489 media_description_options.sender_options.push_back(sender_options);
4490
Steve Antondcc3c022017-12-22 16:02:54 -08004491 return media_description_options;
4492}
4493
Steve Anton5c72e712018-12-10 14:25:30 -08004494// Returns the ContentInfo at mline index |i|, or null if none exists.
4495static const ContentInfo* GetContentByIndex(
4496 const SessionDescriptionInterface* sdesc,
4497 size_t i) {
4498 if (!sdesc) {
4499 return nullptr;
4500 }
4501 const ContentInfos& contents = sdesc->description()->contents();
4502 return (i < contents.size() ? &contents[i] : nullptr);
4503}
4504
Steve Antondcc3c022017-12-22 16:02:54 -08004505void PeerConnection::GetOptionsForUnifiedPlanOffer(
4506 const RTCOfferAnswerOptions& offer_answer_options,
4507 cricket::MediaSessionOptions* session_options) {
4508 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4509 // Offers) and 5.2.2 (Subsequent Offers).
4510 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004511 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004512 const ContentInfos& local_contents =
4513 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004514 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004515 const ContentInfos& remote_contents =
4516 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004517 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004518 // The mline indices that can be recycled. New transceivers should reuse these
4519 // slots first.
4520 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004521 // First, go through each media section that exists in either the local or
4522 // remote description and generate a media section in this offer for the
4523 // associated transceiver. If a media section can be recycled, generate a
4524 // default, rejected media section here that can be later overwritten.
4525 for (size_t i = 0;
4526 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4527 // Either |local_content| or |remote_content| is non-null.
4528 const ContentInfo* local_content =
4529 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004530 const ContentInfo* current_local_content =
4531 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004532 const ContentInfo* remote_content =
4533 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004534 const ContentInfo* current_remote_content =
4535 GetContentByIndex(current_remote_description(), i);
4536 bool had_been_rejected =
4537 (current_local_content && current_local_content->rejected) ||
4538 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004539 const std::string& mid =
4540 (local_content ? local_content->name : remote_content->name);
4541 cricket::MediaType media_type =
4542 (local_content ? local_content->media_description()->type()
4543 : remote_content->media_description()->type());
4544 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4545 media_type == cricket::MEDIA_TYPE_VIDEO) {
4546 auto transceiver = GetAssociatedTransceiver(mid);
4547 RTC_CHECK(transceiver);
4548 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004549 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004550 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004551 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004552 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4553 RtpTransceiverDirection::kInactive,
4554 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004555 recycleable_mline_indices.push(i);
4556 } else {
4557 session_options->media_description_options.push_back(
4558 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4559 // CreateOffer shouldn't really cause any state changes in
4560 // PeerConnection, but we need a way to match new transceivers to new
4561 // media sections in SetLocalDescription and JSEP specifies this is done
4562 // by recording the index of the media section generated for the
4563 // transceiver in the offer.
4564 transceiver->internal()->set_mline_index(i);
4565 }
4566 } else {
4567 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004568 RTC_CHECK(GetDataMid());
4569 if (had_been_rejected || mid != *GetDataMid()) {
4570 session_options->media_description_options.push_back(
4571 GetMediaDescriptionOptionsForRejectedData(mid));
4572 } else {
4573 session_options->media_description_options.push_back(
4574 GetMediaDescriptionOptionsForActiveData(mid));
4575 }
Steve Antondcc3c022017-12-22 16:02:54 -08004576 }
4577 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004578
Steve Antondcc3c022017-12-22 16:02:54 -08004579 // Next, look for transceivers that are newly added (that is, are not stopped
4580 // and not associated). Reuse media sections marked as recyclable first,
4581 // otherwise append to the end of the offer. New media sections should be
4582 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004583 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004584 if (transceiver->mid() || transceiver->stopped()) {
4585 continue;
4586 }
4587 size_t mline_index;
4588 if (!recycleable_mline_indices.empty()) {
4589 mline_index = recycleable_mline_indices.front();
4590 recycleable_mline_indices.pop();
4591 session_options->media_description_options[mline_index] =
4592 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004593 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004594 } else {
4595 mline_index = session_options->media_description_options.size();
4596 session_options->media_description_options.push_back(
4597 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004598 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004599 }
4600 // See comment above for why CreateOffer changes the transceiver's state.
4601 transceiver->internal()->set_mline_index(mline_index);
4602 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004603 // Lastly, add a m-section if we have local data channels and an m section
4604 // does not already exist.
4605 if (!GetDataMid() && HasDataChannels()) {
4606 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004607 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004608 }
Steve Antondcc3c022017-12-22 16:02:54 -08004609}
4610
4611void PeerConnection::GetOptionsForAnswer(
4612 const RTCOfferAnswerOptions& offer_answer_options,
4613 cricket::MediaSessionOptions* session_options) {
4614 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4615
4616 if (IsUnifiedPlan()) {
4617 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4618 } else {
4619 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4620 }
4621
Steve Antonfa2260d2017-12-28 16:38:23 -08004622 // Intentionally unset the data channel type for RTP data channel. Otherwise
4623 // the RTP data channels would be successfully negotiated by default and the
4624 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4625 // We want to leave RTP data channels broken, so people won't try to use them.
4626 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4627 session_options->data_channel_type = data_channel_type();
4628 }
4629
Steve Antondcc3c022017-12-22 16:02:54 -08004630 // Apply ICE renomination flag.
4631 for (auto& options : session_options->media_description_options) {
4632 options.transport_options.enable_ice_renomination =
4633 configuration_.enable_ice_renomination;
4634 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004635
4636 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004637 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004638 session_options->pooled_ice_credentials =
4639 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4640 RTC_FROM_HERE,
4641 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4642 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004643
4644 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004645 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004646 for (auto& options : session_options->media_description_options) {
4647 options.transport_options.opaque_parameters =
4648 transport_controller_->GetTransportParameters(options.mid);
4649 }
4650 }
deadbeefab9b2d12015-10-14 11:33:11 -07004651}
4652
Steve Antondcc3c022017-12-22 16:02:54 -08004653void PeerConnection::GetOptionsForPlanBAnswer(
4654 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004655 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004656 // Figure out transceiver directional preferences.
4657 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4658 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4659
4660 // By default, generate sendrecv/recvonly m= sections. The direction is also
4661 // restricted by the direction in the offer.
4662 bool recv_audio = true;
4663 bool recv_video = true;
4664
4665 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004666 if (offer_answer_options.offer_to_receive_audio !=
4667 RTCOfferAnswerOptions::kUndefined) {
4668 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004669 }
Steve Antondcc3c022017-12-22 16:02:54 -08004670 if (offer_answer_options.offer_to_receive_video !=
4671 RTCOfferAnswerOptions::kUndefined) {
4672 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004673 }
4674
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004675 absl::optional<size_t> audio_index;
4676 absl::optional<size_t> video_index;
4677 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004678
4679 // Generate m= sections that match those in the offer.
4680 // Note that mediasession.cc will handle intersection our preferred
4681 // direction with the offered direction.
4682 GenerateMediaDescriptionOptions(
4683 remote_description(),
4684 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4685 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4686 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004687
4688 cricket::MediaDescriptionOptions* audio_media_description_options =
4689 !audio_index ? nullptr
4690 : &session_options->media_description_options[*audio_index];
4691 cricket::MediaDescriptionOptions* video_media_description_options =
4692 !video_index ? nullptr
4693 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004694
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004695 AddPlanBRtpSenderOptions(GetSendersInternal(),
4696 audio_media_description_options,
4697 video_media_description_options,
4698 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004699}
zhihuangaf388472016-11-02 16:49:48 -07004700
Steve Antondcc3c022017-12-22 16:02:54 -08004701void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4702 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4703 cricket::MediaSessionOptions* session_options) {
4704 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4705 // Answers) and 5.3.2 (Subsequent Answers).
4706 RTC_DCHECK(remote_description());
4707 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4708 for (const ContentInfo& content :
4709 remote_description()->description()->contents()) {
4710 cricket::MediaType media_type = content.media_description()->type();
4711 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4712 media_type == cricket::MEDIA_TYPE_VIDEO) {
4713 auto transceiver = GetAssociatedTransceiver(content.name);
4714 RTC_CHECK(transceiver);
4715 session_options->media_description_options.push_back(
4716 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4717 } else {
4718 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004719 // Reject all data sections if data channels are disabled.
4720 // Reject a data section if it has already been rejected.
4721 // Reject all data sections except for the first one.
4722 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4723 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004724 session_options->media_description_options.push_back(
4725 GetMediaDescriptionOptionsForRejectedData(content.name));
4726 } else {
4727 session_options->media_description_options.push_back(
4728 GetMediaDescriptionOptionsForActiveData(content.name));
4729 }
Steve Antondcc3c022017-12-22 16:02:54 -08004730 }
4731 }
htaa2a49d92016-03-04 02:51:39 -08004732}
4733
zhihuang1c378ed2017-08-17 14:10:50 -07004734void PeerConnection::GenerateMediaDescriptionOptions(
4735 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004736 RtpTransceiverDirection audio_direction,
4737 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004738 absl::optional<size_t>* audio_index,
4739 absl::optional<size_t>* video_index,
4740 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004741 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004742 for (const cricket::ContentInfo& content :
4743 session_desc->description()->contents()) {
4744 if (IsAudioContent(&content)) {
4745 // If we already have an audio m= section, reject this extra one.
4746 if (*audio_index) {
4747 session_options->media_description_options.push_back(
4748 cricket::MediaDescriptionOptions(
4749 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004750 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004751 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004752 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004753 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004754 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4755 content.name, audio_direction,
4756 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004757 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004758 }
4759 } else if (IsVideoContent(&content)) {
4760 // If we already have an video m= section, reject this extra one.
4761 if (*video_index) {
4762 session_options->media_description_options.push_back(
4763 cricket::MediaDescriptionOptions(
4764 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004765 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004766 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004767 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004768 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004769 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4770 content.name, video_direction,
4771 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004772 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004773 }
4774 } else {
4775 RTC_DCHECK(IsDataContent(&content));
4776 // If we already have an data m= section, reject this extra one.
4777 if (*data_index) {
4778 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004779 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004780 } else {
4781 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004782 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004783 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004784 }
4785 }
htaa2a49d92016-03-04 02:51:39 -08004786 }
deadbeefab9b2d12015-10-14 11:33:11 -07004787}
4788
Steve Antonfa2260d2017-12-28 16:38:23 -08004789cricket::MediaDescriptionOptions
4790PeerConnection::GetMediaDescriptionOptionsForActiveData(
4791 const std::string& mid) const {
4792 // Direction for data sections is meaningless, but legacy endpoints might
4793 // expect sendrecv.
4794 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4795 RtpTransceiverDirection::kSendRecv,
4796 /*stopped=*/false);
4797 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4798 return options;
4799}
4800
4801cricket::MediaDescriptionOptions
4802PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4803 const std::string& mid) const {
4804 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4805 RtpTransceiverDirection::kInactive,
4806 /*stopped=*/true);
4807 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4808 return options;
4809}
4810
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004811absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004812 switch (data_channel_type_) {
4813 case cricket::DCT_RTP:
4814 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004815 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004816 }
4817 return rtp_data_channel_->content_name();
4818 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004819 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004820 case cricket::DCT_MEDIA_TRANSPORT:
4821 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004822 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004823 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004824 }
4825}
4826
Steve Anton4171afb2017-11-20 10:20:22 -08004827void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4828 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4829 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004830 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004831}
4832
Steve Anton4171afb2017-11-20 10:20:22 -08004833void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004834 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004835 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004836 cricket::MediaType media_type,
4837 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004838 RTC_DCHECK(!IsUnifiedPlan());
4839
Steve Anton4171afb2017-11-20 10:20:22 -08004840 std::vector<RtpSenderInfo>* current_senders =
4841 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004842
Steve Anton4171afb2017-11-20 10:20:22 -08004843 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004844 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004845 for (auto sender_it = current_senders->begin();
4846 sender_it != current_senders->end();
4847 /* incremented manually */) {
4848 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004849 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004850 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004851 std::string params_stream_id;
4852 if (params) {
4853 params_stream_id =
4854 (!params->first_stream_id().empty() ? params->first_stream_id()
4855 : kDefaultStreamId);
4856 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004857 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004858 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004859 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004860 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004861 sender_exists) {
4862 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004863 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004864 OnRemoteSenderRemoved(info, media_type);
4865 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004866 }
4867 }
4868
Steve Anton4171afb2017-11-20 10:20:22 -08004869 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004870 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004871 if (!params.has_ssrcs()) {
4872 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4873 // sender, this means it is coming from a Unified Plan endpoint,so we just
4874 // create a default.
4875 default_sender_needed = true;
4876 break;
4877 }
4878
Seth Hampson845e8782018-03-02 11:34:10 -08004879 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004880 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004881 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4882 // not supported in Plan B, we just take the first here and create the
4883 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004884 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004885 (!params.first_stream_id().empty() ? params.first_stream_id()
4886 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004887 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004888 uint32_t ssrc = params.first_ssrc();
4889
4890 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004891 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004892 if (!stream) {
4893 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004894 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004895 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004896 remote_streams_->AddStream(stream);
4897 new_streams->AddStream(stream);
4898 }
4899
Steve Anton4171afb2017-11-20 10:20:22 -08004900 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004901 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004902 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004903 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004904 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004905 }
4906 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004907
Steve Anton4171afb2017-11-20 10:20:22 -08004908 // Add default sender if necessary.
4909 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004910 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004911 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004912 if (!default_stream) {
4913 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004914 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004915 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004916 remote_streams_->AddStream(default_stream);
4917 new_streams->AddStream(default_stream);
4918 }
Steve Anton4171afb2017-11-20 10:20:22 -08004919 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4920 ? kDefaultAudioSenderId
4921 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004922 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004923 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004924 if (!default_sender_info) {
4925 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004926 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004927 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004928 }
4929 }
deadbeefab9b2d12015-10-14 11:33:11 -07004930}
4931
Steve Anton4171afb2017-11-20 10:20:22 -08004932void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4933 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004934 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4935 << " receiver for track_id=" << sender_info.sender_id
4936 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004937
Steve Anton3d954a62018-04-02 11:27:23 -07004938 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004939 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004940 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004941 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004942 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004943 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004944 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004945 }
4946}
4947
Steve Anton4171afb2017-11-20 10:20:22 -08004948void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4949 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004950 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4951 << " receiver for track_id=" << sender_info.sender_id
4952 << " and stream_id=" << sender_info.stream_id;
4953
Seth Hampson845e8782018-03-02 11:34:10 -08004954 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004955
Henrik Boström933d8b02017-10-10 10:05:16 -07004956 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004957 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004958 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4959 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004960 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004961 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004962 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004963 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004964 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004965 }
4966 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004967 // Stopping or destroying a VideoRtpReceiver will end the
4968 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004969 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004970 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004971 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004972 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004973 // There's no guarantee the track is still available, e.g. the track may
4974 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004975 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004976 }
4977 } else {
nisseede5da42017-01-12 05:15:36 -08004978 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004979 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004980 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004981 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004982 }
deadbeefab9b2d12015-10-14 11:33:11 -07004983}
4984
4985void PeerConnection::UpdateEndedRemoteMediaStreams() {
4986 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4987 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4988 MediaStreamInterface* stream = remote_streams_->at(i);
4989 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4990 streams_to_remove.push_back(stream);
4991 }
4992 }
4993
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004994 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004995 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004996 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004997 }
4998}
4999
Steve Anton4171afb2017-11-20 10:20:22 -08005000void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005001 const std::vector<cricket::StreamParams>& streams,
5002 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005003 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005004
Seth Hampson845e8782018-03-02 11:34:10 -08005005 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005006 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005007 for (auto sender_it = current_senders->begin();
5008 sender_it != current_senders->end();
5009 /* incremented manually */) {
5010 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005011 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005012 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5013 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005014 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005015 OnLocalSenderRemoved(info, media_type);
5016 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005017 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005018 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005019 }
5020 }
5021
Steve Anton4171afb2017-11-20 10:20:22 -08005022 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005023 for (const cricket::StreamParams& params : streams) {
5024 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005025 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005026 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005027 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005028 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005029 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005030 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005031 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005032 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005033 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005034 }
5035 }
5036}
5037
Steve Anton4171afb2017-11-20 10:20:22 -08005038void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5039 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005040 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005041 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005042 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005043 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5044 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005045 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005046 return;
5047 }
5048
deadbeeffac06552015-11-25 11:26:01 -08005049 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005050 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005051 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005052 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005053 }
deadbeeffac06552015-11-25 11:26:01 -08005054
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005055 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005056 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005057}
5058
Steve Anton4171afb2017-11-20 10:20:22 -08005059void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5060 cricket::MediaType media_type) {
5061 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005062 if (!sender) {
5063 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005064 // SessionDescriptions has been renegotiated.
5065 return;
5066 }
deadbeeffac06552015-11-25 11:26:01 -08005067
5068 // A sender has been removed from the SessionDescription but it's still
5069 // associated with the PeerConnection. This only occurs if the SDP doesn't
5070 // match with the calls to CreateSender, AddStream and RemoveStream.
5071 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005072 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005073 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005074 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005075 }
deadbeeffac06552015-11-25 11:26:01 -08005076
Steve Anton4171afb2017-11-20 10:20:22 -08005077 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005078}
5079
5080void PeerConnection::UpdateLocalRtpDataChannels(
5081 const cricket::StreamParamsVec& streams) {
5082 std::vector<std::string> existing_channels;
5083
5084 // Find new and active data channels.
5085 for (const cricket::StreamParams& params : streams) {
5086 // |it->sync_label| is actually the data channel label. The reason is that
5087 // we use the same naming of data channels as we do for
5088 // MediaStreams and Tracks.
5089 // For MediaStreams, the sync_label is the MediaStream label and the
5090 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005091 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005092 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005093 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005094 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005095 continue;
5096 }
5097 // Set the SSRC the data channel should use for sending.
5098 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5099 existing_channels.push_back(data_channel_it->first);
5100 }
5101
5102 UpdateClosingRtpDataChannels(existing_channels, true);
5103}
5104
5105void PeerConnection::UpdateRemoteRtpDataChannels(
5106 const cricket::StreamParamsVec& streams) {
5107 std::vector<std::string> existing_channels;
5108
5109 // Find new and active data channels.
5110 for (const cricket::StreamParams& params : streams) {
5111 // The data channel label is either the mslabel or the SSRC if the mslabel
5112 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005113 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005114 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005115 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005116 auto data_channel_it = rtp_data_channels_.find(label);
5117 if (data_channel_it == rtp_data_channels_.end()) {
5118 // This is a new data channel.
5119 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5120 } else {
5121 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5122 }
5123 existing_channels.push_back(label);
5124 }
5125
5126 UpdateClosingRtpDataChannels(existing_channels, false);
5127}
5128
5129void PeerConnection::UpdateClosingRtpDataChannels(
5130 const std::vector<std::string>& active_channels,
5131 bool is_local_update) {
5132 auto it = rtp_data_channels_.begin();
5133 while (it != rtp_data_channels_.end()) {
5134 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005135 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005136 ++it;
5137 continue;
5138 }
5139
5140 if (is_local_update) {
5141 data_channel->SetSendSsrc(0);
5142 } else {
5143 data_channel->RemotePeerRequestClose();
5144 }
5145
5146 if (data_channel->state() == DataChannel::kClosed) {
5147 rtp_data_channels_.erase(it);
5148 it = rtp_data_channels_.begin();
5149 } else {
5150 ++it;
5151 }
5152 }
5153}
5154
5155void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5156 uint32_t remote_ssrc) {
5157 rtc::scoped_refptr<DataChannel> channel(
5158 InternalCreateDataChannel(label, nullptr));
5159 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005161 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005162 return;
5163 }
5164 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005165 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5166 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005167 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005168}
5169
5170rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5171 const std::string& label,
5172 const InternalDataChannelInit* config) {
5173 if (IsClosed()) {
5174 return nullptr;
5175 }
Steve Anton75737c02017-11-06 10:37:17 -08005176 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005177 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005178 << "InternalCreateDataChannel: Data is not supported in this call.";
5179 return nullptr;
5180 }
5181 InternalDataChannelInit new_config =
5182 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005183 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005184 if (new_config.id < 0) {
5185 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005186 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005187 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005188 RTC_LOG(LS_ERROR)
5189 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005190 return nullptr;
5191 }
5192 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005193 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005194 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005195 return nullptr;
5196 }
5197 }
5198
Steve Anton75737c02017-11-06 10:37:17 -08005199 rtc::scoped_refptr<DataChannel> channel(
5200 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005201 if (!channel) {
5202 sid_allocator_.ReleaseSid(new_config.id);
5203 return nullptr;
5204 }
5205
5206 if (channel->data_channel_type() == cricket::DCT_RTP) {
5207 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005208 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5209 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005210 return nullptr;
5211 }
5212 rtp_data_channels_[channel->label()] = channel;
5213 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005214 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005215 sctp_data_channels_.push_back(channel);
5216 channel->SignalClosed.connect(this,
5217 &PeerConnection::OnSctpDataChannelClosed);
5218 }
5219
Steve Anton2d8609c2018-01-23 16:38:46 -08005220 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005221 return channel;
5222}
5223
5224bool PeerConnection::HasDataChannels() const {
5225 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5226}
5227
5228void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005229 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005230 for (const auto& channel : sctp_data_channels_) {
5231 if (channel->id() < 0) {
5232 int sid;
5233 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005234 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5235 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005236 continue;
5237 }
5238 channel->SetSctpSid(sid);
5239 }
5240 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005241 // Since closing modifies the list of channels, we have to do the actual
5242 // closing outside the loop.
5243 for (const auto& channel : channels_to_close) {
5244 channel->CloseAbruptly();
5245 }
deadbeefab9b2d12015-10-14 11:33:11 -07005246}
5247
5248void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005249 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005250 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5251 ++it) {
5252 if (it->get() == channel) {
5253 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005254 // After the closing procedure is done, it's safe to use this ID for
5255 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005256 sid_allocator_.ReleaseSid(channel->id());
5257 }
deadbeefbd292462015-12-14 18:15:29 -08005258 // Since this method is triggered by a signal from the DataChannel,
5259 // we can't free it directly here; we need to free it asynchronously.
5260 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005261 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005262 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5263 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005264 return;
5265 }
5266 }
5267}
5268
deadbeefab9b2d12015-10-14 11:33:11 -07005269void PeerConnection::OnDataChannelDestroyed() {
5270 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5271 // DataChannel may callback to us and try to modify the list.
5272 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5273 temp_rtp_dcs.swap(rtp_data_channels_);
5274 for (const auto& kv : temp_rtp_dcs) {
5275 kv.second->OnTransportChannelDestroyed();
5276 }
5277
5278 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5279 temp_sctp_dcs.swap(sctp_data_channels_);
5280 for (const auto& channel : temp_sctp_dcs) {
5281 channel->OnTransportChannelDestroyed();
5282 }
5283}
5284
5285void PeerConnection::OnDataChannelOpenMessage(
5286 const std::string& label,
5287 const InternalDataChannelInit& config) {
5288 rtc::scoped_refptr<DataChannel> channel(
5289 InternalCreateDataChannel(label, &config));
5290 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005291 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005292 return;
5293 }
5294
deadbeefa601f5c2016-06-06 14:27:39 -07005295 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5296 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005297 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005298 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005299}
5300
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005301bool PeerConnection::HandleOpenMessage_s(
5302 const cricket::ReceiveDataParams& params,
5303 const rtc::CopyOnWriteBuffer& buffer) {
5304 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5305 // Received OPEN message; parse and signal that a new data channel should
5306 // be created.
5307 std::string label;
5308 InternalDataChannelInit config;
5309 config.id = params.ssrc;
5310 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5311 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5312 << params.ssrc;
5313 return true;
5314 }
5315 config.open_handshake_role = InternalDataChannelInit::kAcker;
5316 OnDataChannelOpenMessage(label, config);
5317 return true;
5318 }
5319 return false;
5320}
5321
Steve Anton4171afb2017-11-20 10:20:22 -08005322rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5323PeerConnection::GetAudioTransceiver() const {
5324 // This method only works with Plan B SDP, where there is a single
5325 // audio/video transceiver.
5326 RTC_DCHECK(!IsUnifiedPlan());
5327 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005328 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005329 return transceiver;
5330 }
5331 }
5332 RTC_NOTREACHED();
5333 return nullptr;
5334}
5335
5336rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5337PeerConnection::GetVideoTransceiver() const {
5338 // This method only works with Plan B SDP, where there is a single
5339 // audio/video transceiver.
5340 RTC_DCHECK(!IsUnifiedPlan());
5341 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005342 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005343 return transceiver;
5344 }
5345 }
5346 RTC_NOTREACHED();
5347 return nullptr;
5348}
5349
5350// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5351// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005352bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005353 switch (type) {
5354 case cricket::MEDIA_TYPE_AUDIO:
5355 return !GetAudioTransceiver()->internal()->senders().empty();
5356 case cricket::MEDIA_TYPE_VIDEO:
5357 return !GetVideoTransceiver()->internal()->senders().empty();
5358 case cricket::MEDIA_TYPE_DATA:
5359 return false;
5360 }
5361 RTC_NOTREACHED();
5362 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005363}
5364
Steve Anton4171afb2017-11-20 10:20:22 -08005365rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5366PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005367 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005368 for (auto sender : transceiver->internal()->senders()) {
5369 if (sender->track() == track) {
5370 return sender;
5371 }
5372 }
5373 }
5374 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005375}
5376
Steve Anton4171afb2017-11-20 10:20:22 -08005377rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5378PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005379 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005380 for (auto sender : transceiver->internal()->senders()) {
5381 if (sender->id() == sender_id) {
5382 return sender;
5383 }
5384 }
5385 }
5386 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005387}
5388
Steve Anton4171afb2017-11-20 10:20:22 -08005389rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5390PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005391 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005392 for (auto receiver : transceiver->internal()->receivers()) {
5393 if (receiver->id() == receiver_id) {
5394 return receiver;
5395 }
5396 }
5397 }
5398 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005399}
5400
Steve Anton4171afb2017-11-20 10:20:22 -08005401std::vector<PeerConnection::RtpSenderInfo>*
5402PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5403 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5404 media_type == cricket::MEDIA_TYPE_VIDEO);
5405 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5406 ? &remote_audio_sender_infos_
5407 : &remote_video_sender_infos_;
5408}
5409
5410std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005411 cricket::MediaType media_type) {
5412 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5413 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005414 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5415 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005416}
5417
Steve Anton4171afb2017-11-20 10:20:22 -08005418const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5419 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005420 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005421 const std::string sender_id) const {
5422 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005423 if (sender_info.stream_id == stream_id &&
5424 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005425 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005426 }
5427 }
5428 return nullptr;
5429}
5430
5431DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5432 for (const auto& channel : sctp_data_channels_) {
5433 if (channel->id() == sid) {
5434 return channel;
5435 }
5436 }
5437 return nullptr;
5438}
5439
Karl Wibergfb3be392019-03-22 14:13:22 +01005440PeerConnection::InitializePortAllocatorResult
5441PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005442 const cricket::ServerAddresses& stun_servers,
5443 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005444 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005445 RTC_DCHECK_RUN_ON(network_thread());
5446
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005447 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005448 // To handle both internal and externally created port allocator, we will
5449 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005450 int port_allocator_flags = port_allocator_->flags();
5451 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5452 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5453 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005454 // If the disable-IPv6 flag was specified, we'll not override it
5455 // by experiment.
5456 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005457 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005458 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5459 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005460 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005461 }
5462
zhihuangb09b3f92017-03-07 14:40:51 -08005463 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005464 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005465 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005466 }
5467
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005468 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005469 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005470 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005471 }
5472
honghaiz60347052016-05-31 18:29:12 -07005473 if (configuration.candidate_network_policy ==
5474 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005475 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005476 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005477 }
5478
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005479 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005480 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005481 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5482 }
5483
Karl Wibergfb3be392019-03-22 14:13:22 +01005484 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005485 // No step delay is used while allocating ports.
5486 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005487 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005488 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005489 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005490
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005491 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005492 for (auto& turn_server : turn_servers_copy) {
5493 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005494 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005495 // Call this last since it may create pooled allocator sessions using the
5496 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005497 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005498 stun_servers, std::move(turn_servers_copy),
5499 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5500 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005501 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005502
5503 InitializePortAllocatorResult res;
5504 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5505 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005506}
5507
deadbeef91dd5672016-05-18 16:55:30 -07005508bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005509 const cricket::ServerAddresses& stun_servers,
5510 const std::vector<cricket::RelayServerConfig>& turn_servers,
5511 IceTransportsType type,
5512 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005513 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005514 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005515 absl::optional<int> stun_candidate_keepalive_interval,
5516 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005517 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005518 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005519 // According to JSEP, after setLocalDescription, changing the candidate pool
5520 // size is not allowed, and changing the set of ICE servers will not result
5521 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005522 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005523 port_allocator_->FreezeCandidatePool();
5524 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005525 // Add the custom tls turn servers if they exist.
5526 auto turn_servers_copy = turn_servers;
5527 for (auto& turn_server : turn_servers_copy) {
5528 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5529 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005530 // Call this last since it may create pooled allocator sessions using the
5531 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005532 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005533 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5534 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005535}
5536
Steve Antonba818672017-11-06 10:21:57 -08005537cricket::ChannelManager* PeerConnection::channel_manager() const {
5538 return factory_->channel_manager();
5539}
5540
Elad Alon99c3fe52017-10-13 16:29:40 +02005541bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005542 std::unique_ptr<RtcEventLogOutput> output,
5543 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005544 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005545 if (!event_log_) {
5546 return false;
5547 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005548 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005549}
5550
5551void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005552 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005553 if (event_log_) {
5554 event_log_->StopLogging();
5555 }
ivoc14d5dbe2016-07-04 07:06:55 -07005556}
nisseeaabdf62017-05-05 02:23:02 -07005557
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005558cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005559 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005560 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005561 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005562 if (channel && channel->content_name() == content_name) {
5563 return channel;
5564 }
Steve Anton75737c02017-11-06 10:37:17 -08005565 }
5566 if (rtp_data_channel() &&
5567 rtp_data_channel()->content_name() == content_name) {
5568 return rtp_data_channel();
5569 }
5570 return nullptr;
5571}
5572
5573bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005574 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005575 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005576 RTC_LOG(LS_INFO)
5577 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005578 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005579 return false;
5580 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005581 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005582 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005583 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005584 return false;
5585 }
5586
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005587 absl::optional<rtc::SSLRole> dtls_role;
5588 if (sctp_mid_) {
5589 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5590 } else if (is_caller_) {
5591 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5592 }
Zhi Huange830e682018-03-30 10:48:35 -07005593 if (dtls_role) {
5594 *role = *dtls_role;
5595 return true;
5596 }
5597 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005598}
5599
5600bool PeerConnection::GetSslRole(const std::string& content_name,
5601 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005602 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005603 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005604 RTC_LOG(LS_INFO)
5605 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005606 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005607 return false;
5608 }
5609
Zhi Huange830e682018-03-30 10:48:35 -07005610 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5611 if (dtls_role) {
5612 *role = *dtls_role;
5613 return true;
5614 }
5615 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005616}
5617
Steve Antonf8470812017-12-04 10:46:21 -08005618void PeerConnection::SetSessionError(SessionError error,
5619 const std::string& error_desc) {
5620 RTC_DCHECK_RUN_ON(signaling_thread());
5621 if (error != session_error_) {
5622 session_error_ = error;
5623 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005624 }
5625}
5626
Zhi Huange830e682018-03-30 10:48:35 -07005627RTCError PeerConnection::UpdateSessionState(
5628 SdpType type,
5629 cricket::ContentSource source,
5630 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005631 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005632
5633 // If there's already a pending error then no state transition should happen.
5634 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005635 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005636
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005637 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005638 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005639 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005640 }
5641
5642 // Update the signaling state according to the specified state machine (see
5643 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005644 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005645 ChangeSignalingState(source == cricket::CS_LOCAL
5646 ? PeerConnectionInterface::kHaveLocalOffer
5647 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005648 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005649 ChangeSignalingState(source == cricket::CS_LOCAL
5650 ? PeerConnectionInterface::kHaveLocalPrAnswer
5651 : PeerConnectionInterface::kHaveRemotePrAnswer);
5652 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005653 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005654 ChangeSignalingState(PeerConnectionInterface::kStable);
5655 }
5656
5657 // Update internal objects according to the session description's media
5658 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005659 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005660 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005661 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005662 }
5663
Steve Anton8a006912017-12-04 15:25:56 -08005664 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005665}
5666
Steve Anton8a006912017-12-04 15:25:56 -08005667RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005668 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005669 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005670 const SessionDescriptionInterface* sdesc =
5671 (source == cricket::CS_LOCAL ? local_description()
5672 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005673 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005674
5675 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005676 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005677 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005678 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005679 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005680 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005681 continue;
5682 }
5683 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005684 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005685 if (!content_desc) {
5686 continue;
5687 }
5688 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005689 bool success = (source == cricket::CS_LOCAL)
5690 ? channel->SetLocalContent(content_desc, type, &error)
5691 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005692 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005693 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005694 }
5695 }
5696
5697 // If using the RtpDataChannel, push down the new SDP section for it too.
5698 if (rtp_data_channel_) {
5699 const ContentInfo* data_content =
5700 cricket::GetFirstDataContent(sdesc->description());
5701 if (data_content && !data_content->rejected) {
5702 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005703 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005704 if (data_desc) {
5705 std::string error;
5706 bool success =
5707 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005708 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005709 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005710 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005711 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005712 }
Steve Anton75737c02017-11-06 10:37:17 -08005713 }
5714 }
5715 }
Steve Antoned10bd92017-12-05 10:52:59 -08005716
Steve Anton75737c02017-11-06 10:37:17 -08005717 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5718 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005719 if (sctp_transport_ && local_description() && remote_description()) {
5720 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5721 local_description()->description());
5722 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5723 remote_description()->description());
5724 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005725 int max_message_size;
5726 // A remote max message size of zero means "any size supported".
5727 // We configure the connection with our own max message size.
5728 if (remote_sctp_description->max_message_size() == 0) {
5729 max_message_size = local_sctp_description->max_message_size();
5730 } else {
5731 max_message_size =
5732 std::min(local_sctp_description->max_message_size(),
5733 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005734 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005735 sctp_transport_->Start(local_sctp_description->port(),
5736 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005737 }
Steve Anton75737c02017-11-06 10:37:17 -08005738 }
Steve Antoned10bd92017-12-05 10:52:59 -08005739
Steve Anton8a006912017-12-04 15:25:56 -08005740 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005741}
5742
Steve Anton8a006912017-12-04 15:25:56 -08005743RTCError PeerConnection::PushdownTransportDescription(
5744 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005745 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005746 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005747
Zhi Huange830e682018-03-30 10:48:35 -07005748 if (source == cricket::CS_LOCAL) {
5749 const SessionDescriptionInterface* sdesc = local_description();
5750 RTC_DCHECK(sdesc);
5751 return transport_controller_->SetLocalDescription(type,
5752 sdesc->description());
5753 } else {
5754 const SessionDescriptionInterface* sdesc = remote_description();
5755 RTC_DCHECK(sdesc);
5756 return transport_controller_->SetRemoteDescription(type,
5757 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005758 }
Steve Anton75737c02017-11-06 10:37:17 -08005759}
5760
5761bool PeerConnection::GetTransportDescription(
5762 const SessionDescription* description,
5763 const std::string& content_name,
5764 cricket::TransportDescription* tdesc) {
5765 if (!description || !tdesc) {
5766 return false;
5767 }
5768 const TransportInfo* transport_info =
5769 description->GetTransportInfoByName(content_name);
5770 if (!transport_info) {
5771 return false;
5772 }
5773 *tdesc = transport_info->description;
5774 return true;
5775}
5776
Steve Anton75737c02017-11-06 10:37:17 -08005777cricket::IceConfig PeerConnection::ParseIceConfig(
5778 const PeerConnectionInterface::RTCConfiguration& config) const {
5779 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005780 switch (config.continual_gathering_policy) {
5781 case PeerConnectionInterface::GATHER_ONCE:
5782 gathering_policy = cricket::GATHER_ONCE;
5783 break;
5784 case PeerConnectionInterface::GATHER_CONTINUALLY:
5785 gathering_policy = cricket::GATHER_CONTINUALLY;
5786 break;
5787 default:
5788 RTC_NOTREACHED();
5789 gathering_policy = cricket::GATHER_ONCE;
5790 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005791
Steve Anton75737c02017-11-06 10:37:17 -08005792 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005793 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5794 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005795 ice_config.prioritize_most_likely_candidate_pairs =
5796 config.prioritize_most_likely_ice_candidate_pairs;
5797 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005798 RTCConfigurationToIceConfigOptionalInt(
5799 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005800 ice_config.continual_gathering_policy = gathering_policy;
5801 ice_config.presume_writable_when_fully_relayed =
5802 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005803 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5804 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005805 ice_config.ice_check_interval_strong_connectivity =
5806 config.ice_check_interval_strong_connectivity;
5807 ice_config.ice_check_interval_weak_connectivity =
5808 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005809 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005810 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5811 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005812 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005813 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005814 ice_config.regather_all_networks_interval_range =
5815 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005816 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005817 return ice_config;
5818}
5819
Steve Anton75737c02017-11-06 10:37:17 -08005820bool PeerConnection::SendData(const cricket::SendDataParams& params,
5821 const rtc::CopyOnWriteBuffer& payload,
5822 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005823 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005824 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5825 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5826 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005827 return false;
5828 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005829 if (media_transport_) {
5830 SendDataParams send_params;
5831 send_params.type = ToWebrtcDataMessageType(params.type);
5832 send_params.ordered = params.ordered;
5833 if (params.max_rtx_count >= 0) {
5834 send_params.max_rtx_count = params.max_rtx_count;
5835 } else if (params.max_rtx_ms >= 0) {
5836 send_params.max_rtx_ms = params.max_rtx_ms;
5837 }
5838 return media_transport_->SendData(params.sid, send_params, payload).ok();
5839 }
Steve Anton75737c02017-11-06 10:37:17 -08005840 return rtp_data_channel_
5841 ? rtp_data_channel_->SendData(params, payload, result)
5842 : network_thread()->Invoke<bool>(
5843 RTC_FROM_HERE,
5844 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005845 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005846}
5847
5848bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005849 RTC_DCHECK_RUN_ON(signaling_thread());
5850 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 // Don't log an error here, because DataChannels are expected to call
5852 // ConnectDataChannel in this state. It's the only way to initially tell
5853 // whether or not the underlying transport is ready.
5854 return false;
5855 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005856 if (media_transport_) {
5857 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5858 &DataChannel::OnChannelReady);
5859 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5860 &DataChannel::OnDataReceived);
5861 SignalMediaTransportChannelClosing_s.connect(
5862 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5863 SignalMediaTransportChannelClosed_s.connect(
5864 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5865 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005866 rtp_data_channel_->SignalReadyToSendData.connect(
5867 webrtc_data_channel, &DataChannel::OnChannelReady);
5868 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5869 &DataChannel::OnDataReceived);
5870 } else {
5871 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5872 &DataChannel::OnChannelReady);
5873 SignalSctpDataReceived.connect(webrtc_data_channel,
5874 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005875 SignalSctpClosingProcedureStartedRemotely.connect(
5876 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5877 SignalSctpClosingProcedureComplete.connect(
5878 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005879 }
5880 return true;
5881}
5882
5883void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005884 RTC_DCHECK_RUN_ON(signaling_thread());
5885 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005886 RTC_LOG(LS_ERROR)
5887 << "DisconnectDataChannel called when rtp_data_channel_ and "
5888 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005889 return;
5890 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005891 if (media_transport_) {
5892 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5893 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5894 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5895 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5896 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005897 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5898 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5899 } else {
5900 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5901 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005902 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5903 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005904 }
5905}
5906
5907void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005908 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005909 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005910 return;
5911 }
Steve Anton75737c02017-11-06 10:37:17 -08005912 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005913 RTC_LOG(LS_ERROR)
5914 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005915 return;
5916 }
5917 network_thread()->Invoke<void>(
5918 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005919 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005920}
5921
5922void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005923 if (media_transport_) {
5924 media_transport_->CloseChannel(sid);
5925 return;
5926 }
Steve Anton75737c02017-11-06 10:37:17 -08005927 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005928 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005929 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005930 return;
5931 }
5932 network_thread()->Invoke<void>(
5933 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005934 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005935}
5936
5937bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005938 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005939 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005940 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005941 sctp_ready_to_send_data_;
5942}
5943
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005944void PeerConnection::OnDataReceived(int channel_id,
5945 DataMessageType type,
5946 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005947 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005948 cricket::ReceiveDataParams params;
5949 params.sid = channel_id;
5950 params.type = ToCricketDataMessageType(type);
5951 media_transport_invoker_->AsyncInvoke<void>(
5952 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5953 RTC_DCHECK_RUN_ON(signaling_thread());
5954 if (!HandleOpenMessage_s(params, buffer)) {
5955 SignalMediaTransportReceivedData_s(params, buffer);
5956 }
5957 });
5958}
5959
5960void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005961 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005962 media_transport_invoker_->AsyncInvoke<void>(
5963 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5964 RTC_DCHECK_RUN_ON(signaling_thread());
5965 SignalMediaTransportChannelClosing_s(channel_id);
5966 });
5967}
5968
5969void PeerConnection::OnChannelClosed(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 SignalMediaTransportChannelClosed_s(channel_id);
5975 });
5976}
5977
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005978absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005979 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07005980 if (sctp_mid_ && transport_controller_) {
5981 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5982 if (dtls_transport) {
5983 return dtls_transport->transport_name();
5984 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005985 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005986 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005987 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005988}
5989
Qingsi Wang72a43a12018-02-20 16:03:18 -08005990cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5991 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005992 network_thread()->Invoke<void>(
5993 RTC_FROM_HERE,
5994 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5995 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005996 return candidate_states_list;
5997}
5998
Steve Anton5dfde182018-02-06 10:34:40 -08005999std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6000 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006001 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006002 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006003 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006004 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006005 if (channel) {
6006 transport_names_by_mid[channel->content_name()] =
6007 channel->transport_name();
6008 }
Steve Anton75737c02017-11-06 10:37:17 -08006009 }
Steve Anton5dfde182018-02-06 10:34:40 -08006010 if (rtp_data_channel_) {
6011 transport_names_by_mid[rtp_data_channel_->content_name()] =
6012 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006013 }
6014 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006015 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006016 RTC_DCHECK(transport_name);
6017 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006018 }
Steve Anton5dfde182018-02-06 10:34:40 -08006019 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006020}
6021
Steve Anton5dfde182018-02-06 10:34:40 -08006022std::map<std::string, cricket::TransportStats>
6023PeerConnection::GetTransportStatsByNames(
6024 const std::set<std::string>& transport_names) {
6025 if (!network_thread()->IsCurrent()) {
6026 return network_thread()
6027 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6028 RTC_FROM_HERE,
6029 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006030 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006031 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006032 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6033 for (const std::string& transport_name : transport_names) {
6034 cricket::TransportStats transport_stats;
6035 bool success =
6036 transport_controller_->GetStats(transport_name, &transport_stats);
6037 if (success) {
6038 transport_stats_by_name[transport_name] = std::move(transport_stats);
6039 } else {
6040 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6041 << transport_name;
6042 }
6043 }
6044 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006045}
6046
6047bool PeerConnection::GetLocalCertificate(
6048 const std::string& transport_name,
6049 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006050 if (!certificate) {
6051 return false;
6052 }
6053 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6054 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006055}
6056
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006057std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006058 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006059 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006060}
6061
6062cricket::DataChannelType PeerConnection::data_channel_type() const {
6063 return data_channel_type_;
6064}
6065
6066bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006067 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006068 return pending_ice_restarts_.find(content_name) !=
6069 pending_ice_restarts_.end();
6070}
6071
Steve Anton75737c02017-11-06 10:37:17 -08006072bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6073 return transport_controller_->NeedsIceRestart(content_name);
6074}
6075
6076void PeerConnection::OnCertificateReady(
6077 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6078 transport_controller_->SetLocalCertificate(certificate);
6079}
6080
6081void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006082 SetSessionError(SessionError::kTransport,
6083 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006084}
6085
Alex Loiko9289eda2018-11-23 16:18:59 +00006086void PeerConnection::OnTransportControllerConnectionState(
6087 cricket::IceConnectionState state) {
6088 switch (state) {
6089 case cricket::kIceConnectionConnecting:
6090 // If the current state is Connected or Completed, then there were
6091 // writable channels but now there are not, so the next state must
6092 // be Disconnected.
6093 // kIceConnectionConnecting is currently used as the default,
6094 // un-connected state by the TransportController, so its only use is
6095 // detecting disconnections.
6096 if (ice_connection_state_ ==
6097 PeerConnectionInterface::kIceConnectionConnected ||
6098 ice_connection_state_ ==
6099 PeerConnectionInterface::kIceConnectionCompleted) {
6100 SetIceConnectionState(
6101 PeerConnectionInterface::kIceConnectionDisconnected);
6102 }
6103 break;
6104 case cricket::kIceConnectionFailed:
6105 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6106 break;
6107 case cricket::kIceConnectionConnected:
6108 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6109 "all transports are writable.";
6110 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6111 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6112 break;
6113 case cricket::kIceConnectionCompleted:
6114 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6115 "all transports are complete.";
6116 if (ice_connection_state_ !=
6117 PeerConnectionInterface::kIceConnectionConnected) {
6118 // If jumping directly from "checking" to "connected",
6119 // signal "connected" first.
6120 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6121 }
6122 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6123 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6124 ReportTransportStats();
6125 break;
6126 default:
6127 RTC_NOTREACHED();
6128 }
6129}
6130
Steve Anton75737c02017-11-06 10:37:17 -08006131void PeerConnection::OnTransportControllerCandidatesGathered(
6132 const std::string& transport_name,
6133 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006134 int sdp_mline_index;
6135 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006136 RTC_LOG(LS_ERROR)
6137 << "OnTransportControllerCandidatesGathered: content name "
6138 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006139 return;
6140 }
6141
6142 for (cricket::Candidates::const_iterator citer = candidates.begin();
6143 citer != candidates.end(); ++citer) {
6144 // Use transport_name as the candidate media id.
6145 std::unique_ptr<JsepIceCandidate> candidate(
6146 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6147 if (local_description()) {
6148 mutable_local_description()->AddCandidate(candidate.get());
6149 }
6150 OnIceCandidate(std::move(candidate));
6151 }
6152}
6153
Eldar Relloda13ea22019-06-01 12:23:43 +03006154void PeerConnection::OnTransportControllerCandidateError(
6155 const cricket::IceCandidateErrorEvent& event) {
6156 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6157 event.error_text);
6158}
6159
Steve Anton75737c02017-11-06 10:37:17 -08006160void PeerConnection::OnTransportControllerCandidatesRemoved(
6161 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006162 // Sanity check.
6163 for (const cricket::Candidate& candidate : candidates) {
6164 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006165 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006166 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006167 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006168 return;
6169 }
6170 }
6171
6172 if (local_description()) {
6173 mutable_local_description()->RemoveCandidates(candidates);
6174 }
6175 OnIceCandidatesRemoved(candidates);
6176}
6177
6178void PeerConnection::OnTransportControllerDtlsHandshakeError(
6179 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006180 RTC_HISTOGRAM_ENUMERATION(
6181 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6182 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006183}
6184
Steve Antoned10bd92017-12-05 10:52:59 -08006185void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006186 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006187 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006188 if (channel && !channel->enabled()) {
6189 channel->Enable(true);
6190 }
Steve Anton75737c02017-11-06 10:37:17 -08006191 }
6192
Steve Anton4171afb2017-11-20 10:20:22 -08006193 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006194 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006195 }
Steve Anton75737c02017-11-06 10:37:17 -08006196}
6197
6198// Returns the media index for a local ice candidate given the content name.
6199bool PeerConnection::GetLocalCandidateMediaIndex(
6200 const std::string& content_name,
6201 int* sdp_mline_index) {
6202 if (!local_description() || !sdp_mline_index) {
6203 return false;
6204 }
6205
6206 bool content_found = false;
6207 const ContentInfos& contents = local_description()->description()->contents();
6208 for (size_t index = 0; index < contents.size(); ++index) {
6209 if (contents[index].name == content_name) {
6210 *sdp_mline_index = static_cast<int>(index);
6211 content_found = true;
6212 break;
6213 }
6214 }
6215 return content_found;
6216}
6217
6218bool PeerConnection::UseCandidatesInSessionDescription(
6219 const SessionDescriptionInterface* remote_desc) {
6220 if (!remote_desc) {
6221 return true;
6222 }
6223 bool ret = true;
6224
6225 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6226 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6227 for (size_t n = 0; n < candidates->count(); ++n) {
6228 const IceCandidateInterface* candidate = candidates->at(n);
6229 bool valid = false;
6230 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6231 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006232 RTC_LOG(LS_INFO)
6233 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006234 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006235 }
6236 continue;
6237 }
6238 ret = UseCandidate(candidate);
6239 if (!ret) {
6240 break;
6241 }
6242 }
6243 }
6244 return ret;
6245}
6246
6247bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006248 RTCErrorOr<const cricket::ContentInfo*> result =
6249 FindContentInfo(remote_description(), candidate);
6250 if (!result.ok()) {
6251 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6252 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006253 return false;
6254 }
Steve Anton75737c02017-11-06 10:37:17 -08006255 std::vector<cricket::Candidate> candidates;
6256 candidates.push_back(candidate->candidate());
6257 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006258 RTCError error = transport_controller_->AddRemoteCandidates(
6259 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006260 if (error.ok()) {
6261 // Candidates successfully submitted for checking.
6262 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6263 ice_connection_state_ ==
6264 PeerConnectionInterface::kIceConnectionDisconnected) {
6265 // If state is New, then the session has just gotten its first remote ICE
6266 // candidates, so go to Checking.
6267 // If state is Disconnected, the session is re-using old candidates or
6268 // receiving additional ones, so go to Checking.
6269 // If state is Connected, stay Connected.
6270 // TODO(bemasc): If state is Connected, and the new candidates are for a
6271 // newly added transport, then the state actually _should_ move to
6272 // checking. Add a way to distinguish that case.
6273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6274 }
6275 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006276 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006277 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006278 }
6279 return true;
6280}
6281
Guido Urdaneta41633172019-05-23 20:12:29 +02006282RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6283 const SessionDescriptionInterface* description,
6284 const IceCandidateInterface* candidate) {
6285 if (candidate->sdp_mline_index() >= 0) {
6286 size_t mediacontent_index =
6287 static_cast<size_t>(candidate->sdp_mline_index());
6288 size_t content_size = description->description()->contents().size();
6289 if (mediacontent_index < content_size) {
6290 return &description->description()->contents()[mediacontent_index];
6291 } else {
6292 return RTCError(RTCErrorType::INVALID_RANGE,
6293 "Media line index (" +
6294 rtc::ToString(candidate->sdp_mline_index()) +
6295 ") out of range (number of mlines: " +
6296 rtc::ToString(content_size) + ").");
6297 }
6298 } else if (!candidate->sdp_mid().empty()) {
6299 auto& contents = description->description()->contents();
6300 auto it = absl::c_find_if(
6301 contents, [candidate](const cricket::ContentInfo& content_info) {
6302 return content_info.mid() == candidate->sdp_mid();
6303 });
6304 if (it == contents.end()) {
6305 return RTCError(
6306 RTCErrorType::INVALID_PARAMETER,
6307 "Mid " + candidate->sdp_mid() +
6308 " specified but no media section with that mid found.");
6309 } else {
6310 return &*it;
6311 }
6312 }
6313
6314 return RTCError(RTCErrorType::INVALID_PARAMETER,
6315 "Neither sdp_mline_index nor sdp_mid specified.");
6316}
6317
Steve Anton75737c02017-11-06 10:37:17 -08006318void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006319 // Destroy video channel first since it may have a pointer to the
6320 // voice channel.
6321 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006322 if (!video_info || video_info->rejected) {
6323 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006324 }
6325
Steve Anton6fec8802017-12-04 10:37:29 -08006326 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6327 if (!audio_info || audio_info->rejected) {
6328 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006329 }
6330
6331 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6332 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006333 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006334 }
6335}
6336
Steve Antondcc3c022017-12-22 16:02:54 -08006337RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6338 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006339 const cricket::ContentGroup* bundle_group = nullptr;
6340 if (configuration_.bundle_policy ==
6341 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006342 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006343 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6345 "max-bundle configured but session description "
6346 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006347 }
6348 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006349 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006350}
6351
6352RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006353 // Creating the media channels. Transports should already have been created
6354 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006355 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006356 if (voice && !voice->rejected &&
6357 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006358 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006359 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006360 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6361 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006362 }
6363 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6364 }
6365
Steve Antondcc3c022017-12-22 16:02:54 -08006366 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006367 if (video && !video->rejected &&
6368 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006369 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006370 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006371 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6372 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006373 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006374 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006375 }
6376
Steve Antondcc3c022017-12-22 16:02:54 -08006377 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006378 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006379 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006380 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006381 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6382 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006383 }
6384 }
6385
Steve Anton8a006912017-12-04 15:25:56 -08006386 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006387}
6388
Steve Anton4171afb2017-11-20 10:20:22 -08006389// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006390cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006391 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006392 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006393 MediaTransportConfig media_transport_config =
6394 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006395
Steve Anton75737c02017-11-06 10:37:17 -08006396 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006397 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006398 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6399 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006400 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006401 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006402 }
Steve Anton75737c02017-11-06 10:37:17 -08006403 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6404 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006405 voice_channel->SignalSentPacket.connect(this,
6406 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006407 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006408
Steve Antoneda6ccd2017-12-04 10:21:55 -08006409 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006410}
6411
Steve Anton4171afb2017-11-20 10:20:22 -08006412// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006413cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006414 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006415 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006416 MediaTransportConfig media_transport_config =
6417 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006418
Steve Anton75737c02017-11-06 10:37:17 -08006419 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006420 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006421 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6422 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006423 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006424 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006425 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006426 }
Steve Anton75737c02017-11-06 10:37:17 -08006427 video_channel->SignalDtlsSrtpSetupFailure.connect(
6428 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006429 video_channel->SignalSentPacket.connect(this,
6430 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006431 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006432
Steve Antoneda6ccd2017-12-04 10:21:55 -08006433 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006434}
6435
Zhi Huange830e682018-03-30 10:48:35 -07006436bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006437 switch (data_channel_type_) {
6438 case cricket::DCT_MEDIA_TRANSPORT:
6439 if (network_thread()->Invoke<bool>(
6440 RTC_FROM_HERE,
6441 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6442 this, mid))) {
6443 for (const auto& channel : sctp_data_channels_) {
6444 channel->OnTransportChannelCreated();
6445 }
6446 return true;
6447 }
Steve Anton75737c02017-11-06 10:37:17 -08006448 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006449 case cricket::DCT_SCTP:
6450 if (!sctp_factory_) {
6451 RTC_LOG(LS_ERROR)
6452 << "Trying to create SCTP transport, but didn't compile with "
6453 "SCTP support (HAVE_SCTP)";
6454 return false;
6455 }
6456 if (!network_thread()->Invoke<bool>(
6457 RTC_FROM_HERE,
6458 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6459 return false;
6460 }
6461 for (const auto& channel : sctp_data_channels_) {
6462 channel->OnTransportChannelCreated();
6463 }
6464 return true;
6465 case cricket::DCT_RTP:
6466 default:
6467 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6468 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6469 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006470 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006471 if (!rtp_data_channel_) {
6472 return false;
6473 }
6474 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6475 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6476 rtp_data_channel_->SignalSentPacket.connect(
6477 this, &PeerConnection::OnSentPacket_w);
6478 rtp_data_channel_->SetRtpTransport(rtp_transport);
6479 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006480 }
6481
Steve Anton75737c02017-11-06 10:37:17 -08006482 return true;
6483}
6484
6485Call::Stats PeerConnection::GetCallStats() {
6486 if (!worker_thread()->IsCurrent()) {
6487 return worker_thread()->Invoke<Call::Stats>(
6488 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6489 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006490 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006491 if (call_) {
6492 return call_->GetStats();
6493 } else {
6494 return Call::Stats();
6495 }
6496}
6497
Zhi Huange830e682018-03-30 10:48:35 -07006498bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006499 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006500 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006501 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6502 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006503 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006504 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006505 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006506 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6507 sctp_factory_->CreateSctpTransport(dtls_transport);
6508 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006509 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006510 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006511 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006512 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006513 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006514 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6515 // another thread. Would be nice if there was a helper class similar to
6516 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6517 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006518 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006519 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006520 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006521 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006522 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006523 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6524 std::move(cricket_sctp_transport));
6525 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006526 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006527}
6528
6529void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006530 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006531 sctp_transport_->Clear();
6532 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006533 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006534 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006535}
6536
6537void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006538 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006539 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006540 // Note: Cannot use rtc::Bind here because it will grab a reference to
6541 // PeerConnection and potentially cause PeerConnection to live longer than
6542 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6543 // be destroyed before PeerConnection is destroyed, and at that point all
6544 // pending tasks will be cleared.
6545 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6546 OnSctpTransportReadyToSendData_s(true);
6547 });
6548}
6549
6550void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006551 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006552 sctp_ready_to_send_data_ = ready;
6553 SignalSctpReadyToSendData(ready);
6554}
6555
6556void PeerConnection::OnSctpTransportDataReceived_n(
6557 const cricket::ReceiveDataParams& params,
6558 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006559 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006560 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006561 // Note: Cannot use rtc::Bind here because it will grab a reference to
6562 // PeerConnection and potentially cause PeerConnection to live longer than
6563 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6564 // be destroyed before PeerConnection is destroyed, and at that point all
6565 // pending tasks will be cleared.
6566 sctp_invoker_->AsyncInvoke<void>(
6567 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6568 OnSctpTransportDataReceived_s(params, payload);
6569 });
6570}
6571
6572void PeerConnection::OnSctpTransportDataReceived_s(
6573 const cricket::ReceiveDataParams& params,
6574 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006575 RTC_DCHECK_RUN_ON(signaling_thread());
6576 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006577 SignalSctpDataReceived(params, payload);
6578 }
6579}
6580
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006581void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006582 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006583 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006584 sctp_invoker_->AsyncInvoke<void>(
6585 RTC_FROM_HERE, signaling_thread(),
6586 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006587 &SignalSctpClosingProcedureStartedRemotely, sid));
6588}
6589
6590void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006591 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006592 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006593 sctp_invoker_->AsyncInvoke<void>(
6594 RTC_FROM_HERE, signaling_thread(),
6595 rtc::Bind(&sigslot::signal1<int>::operator(),
6596 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006597}
6598
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006599bool PeerConnection::SetupMediaTransportForDataChannels_n(
6600 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006601 media_transport_ =
6602 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006603 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006604 RTC_LOG(LS_ERROR)
6605 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006606 return false;
6607 }
6608
6609 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6610 media_transport_->SetDataSink(this);
6611 media_transport_data_mid_ = mid;
6612 transport_controller_->SignalMediaTransportStateChanged.connect(
6613 this, &PeerConnection::OnMediaTransportStateChanged_n);
6614 // Check the initial state right away, in case transport is already writable.
6615 OnMediaTransportStateChanged_n();
6616 return true;
6617}
6618
6619void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6620 if (!media_transport_) {
6621 return;
6622 }
6623 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6624 media_transport_data_mid_.reset();
6625 media_transport_->SetDataSink(nullptr);
6626 media_transport_invoker_ = nullptr;
6627 media_transport_ = nullptr;
6628}
6629
6630void PeerConnection::OnMediaTransportStateChanged_n() {
6631 if (!media_transport_data_mid_ ||
6632 transport_controller_->GetMediaTransportState(
6633 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6634 return;
6635 }
6636 media_transport_invoker_->AsyncInvoke<void>(
6637 RTC_FROM_HERE, signaling_thread(), [this] {
6638 RTC_DCHECK_RUN_ON(signaling_thread());
6639 media_transport_ready_to_send_data_ = true;
6640 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6641 });
6642}
6643
Steve Anton75737c02017-11-06 10:37:17 -08006644// Returns false if bundle is enabled and rtcp_mux is disabled.
6645bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6646 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6647 if (!bundle_enabled)
6648 return true;
6649
6650 const cricket::ContentGroup* bundle_group =
6651 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6652 RTC_DCHECK(bundle_group != NULL);
6653
6654 const cricket::ContentInfos& contents = desc->contents();
6655 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6656 citer != contents.end(); ++citer) {
6657 const cricket::ContentInfo* content = (&*citer);
6658 RTC_DCHECK(content != NULL);
6659 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006660 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006661 if (!HasRtcpMuxEnabled(content))
6662 return false;
6663 }
6664 }
6665 // RTCP-MUX is enabled in all the contents.
6666 return true;
6667}
6668
6669bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006670 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006671}
6672
Steve Anton06817cd2018-12-18 15:55:30 -08006673static RTCError ValidateMids(const cricket::SessionDescription& description) {
6674 std::set<std::string> mids;
6675 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006676 if (content.name.empty()) {
6677 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6678 "A media section is missing a MID attribute.");
6679 }
Steve Anton06817cd2018-12-18 15:55:30 -08006680 if (!mids.insert(content.name).second) {
6681 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6682 "Duplicate a=mid value '" + content.name + "'.");
6683 }
6684 }
6685 return RTCError::OK();
6686}
6687
Steve Anton8a006912017-12-04 15:25:56 -08006688RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006689 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006690 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006691 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006692 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006693 }
6694
6695 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006697 }
6698
Steve Anton3828c062017-12-06 10:34:51 -08006699 SdpType type = sdesc->GetType();
6700 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6701 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006702 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006703 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006704 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006705 }
6706
Steve Anton06817cd2018-12-18 15:55:30 -08006707 RTCError error = ValidateMids(*sdesc->description());
6708 if (!error.ok()) {
6709 return error;
6710 }
6711
Steve Anton75737c02017-11-06 10:37:17 -08006712 // Verify crypto settings.
6713 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006714 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6715 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006716 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006717 if (!crypto_error.ok()) {
6718 return crypto_error;
6719 }
Steve Anton75737c02017-11-06 10:37:17 -08006720 }
6721
6722 // Verify ice-ufrag and ice-pwd.
6723 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006724 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6725 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006726 }
6727
6728 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006729 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6730 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006731 }
6732
6733 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6734 // m-lines that do not rtcp-mux enabled.
6735
6736 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006737 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006738 // With an answer we want to compare the new answer session description with
6739 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006740 const cricket::SessionDescription* offer_desc =
6741 (source == cricket::CS_LOCAL) ? remote_description()->description()
6742 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006743 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6744 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6745 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006746 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6747 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006748 }
6749 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006750 // The re-offers should respect the order of m= sections in current
6751 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006752 // With a re-offer, either the current local or current remote descriptions
6753 // could be the most up to date, so we would like to check against both of
6754 // them if they exist. It could be the case that one of them has a 0 port
6755 // for a media section, but the other does not. This is important to check
6756 // against in the case that we are recycling an m= section.
6757 const cricket::SessionDescription* current_desc = nullptr;
6758 const cricket::SessionDescription* secondary_current_desc = nullptr;
6759 if (local_description()) {
6760 current_desc = local_description()->description();
6761 if (remote_description()) {
6762 secondary_current_desc = remote_description()->description();
6763 }
6764 } else if (remote_description()) {
6765 current_desc = remote_description()->description();
6766 }
Steve Anton75737c02017-11-06 10:37:17 -08006767 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006768 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6769 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6771 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006772 }
6773 }
6774
Steve Antonba42e992018-04-09 14:10:01 -07006775 if (IsUnifiedPlan()) {
6776 // Ensure that each audio and video media section has at most one
6777 // "StreamParams". This will return an error if receiving a session
6778 // description from a "Plan B" endpoint which adds multiple tracks of the
6779 // same type. With Unified Plan, there can only be at most one track per
6780 // media section.
6781 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006782 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006783 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6784 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6785 desc.streams().size() > 1u) {
6786 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6787 "Media section has more than one track specified "
6788 "with a=ssrc lines which is not supported with "
6789 "Unified Plan.");
6790 }
6791 }
6792 }
6793
Steve Anton8a006912017-12-04 15:25:56 -08006794 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006795}
6796
Steve Anton3828c062017-12-06 10:34:51 -08006797bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006798 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006799 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006800 return (state == PeerConnectionInterface::kStable) ||
6801 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006802 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006803 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006804 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6805 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6806 }
6807}
6808
Steve Anton3828c062017-12-06 10:34:51 -08006809bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006810 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006811 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006812 return (state == PeerConnectionInterface::kStable) ||
6813 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006814 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006815 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006816 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6817 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6818 }
6819}
6820
Steve Antonf8470812017-12-04 10:46:21 -08006821const char* PeerConnection::SessionErrorToString(SessionError error) const {
6822 switch (error) {
6823 case SessionError::kNone:
6824 return "ERROR_NONE";
6825 case SessionError::kContent:
6826 return "ERROR_CONTENT";
6827 case SessionError::kTransport:
6828 return "ERROR_TRANSPORT";
6829 }
6830 RTC_NOTREACHED();
6831 return "";
6832}
6833
Steve Anton75737c02017-11-06 10:37:17 -08006834std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006835 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006836 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6837 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006838 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006839}
6840
Steve Anton8e20f172018-03-06 10:55:04 -08006841void PeerConnection::ReportSdpFormatReceived(
6842 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006843 int num_audio_mlines = 0;
6844 int num_video_mlines = 0;
6845 int num_audio_tracks = 0;
6846 int num_video_tracks = 0;
6847 for (const ContentInfo& content : remote_offer.description()->contents()) {
6848 cricket::MediaType media_type = content.media_description()->type();
6849 int num_tracks = std::max(
6850 1, static_cast<int>(content.media_description()->streams().size()));
6851 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6852 num_audio_mlines += 1;
6853 num_audio_tracks += num_tracks;
6854 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6855 num_video_mlines += 1;
6856 num_video_tracks += num_tracks;
6857 }
6858 }
6859 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6860 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6861 format = kSdpFormatReceivedComplexUnifiedPlan;
6862 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6863 format = kSdpFormatReceivedComplexPlanB;
6864 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6865 format = kSdpFormatReceivedSimple;
6866 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006867 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6868 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006869}
6870
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006871void PeerConnection::NoteUsageEvent(UsageEvent event) {
6872 RTC_DCHECK_RUN_ON(signaling_thread());
6873 usage_event_accumulator_ |= static_cast<int>(event);
6874}
6875
6876void PeerConnection::ReportUsagePattern() const {
6877 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006878 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6879 usage_event_accumulator_,
6880 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006881 const int bad_bits =
6882 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6883 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6884 const int good_bits =
6885 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6886 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6887 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6888 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6889 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006890 // If called after close(), we can't report, because observer may have
6891 // been deallocated, and therefore pointer is null. Write to log instead.
6892 if (observer_) {
6893 Observer()->OnInterestingUsage(usage_event_accumulator_);
6894 } else {
6895 RTC_LOG(LS_INFO) << "Interesting usage signature "
6896 << usage_event_accumulator_
6897 << " observed after observer shutdown";
6898 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006899 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006900}
6901
Steve Anton0ffaaa22018-02-23 10:31:30 -08006902void PeerConnection::ReportNegotiatedSdpSemantics(
6903 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006904 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006905 switch (answer.description()->msid_signaling()) {
6906 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006907 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006908 break;
6909 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006910 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006911 break;
6912 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006913 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006914 break;
6915 case cricket::kMsidSignalingMediaSection |
6916 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006917 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006918 break;
6919 default:
6920 RTC_NOTREACHED();
6921 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006922 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6923 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006924}
6925
Steve Anton75737c02017-11-06 10:37:17 -08006926// We need to check the local/remote description for the Transport instead of
6927// the session, because a new Transport added during renegotiation may have
6928// them unset while the session has them set from the previous negotiation.
6929// Not doing so may trigger the auto generation of transport description and
6930// mess up DTLS identity information, ICE credential, etc.
6931bool PeerConnection::ReadyToUseRemoteCandidate(
6932 const IceCandidateInterface* candidate,
6933 const SessionDescriptionInterface* remote_desc,
6934 bool* valid) {
6935 *valid = true;
6936
6937 const SessionDescriptionInterface* current_remote_desc =
6938 remote_desc ? remote_desc : remote_description();
6939
6940 if (!current_remote_desc) {
6941 return false;
6942 }
6943
Guido Urdaneta41633172019-05-23 20:12:29 +02006944 RTCErrorOr<const cricket::ContentInfo*> result =
6945 FindContentInfo(current_remote_desc, candidate);
6946 if (!result.ok()) {
6947 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6948 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006949
6950 *valid = false;
6951 return false;
6952 }
6953
Guido Urdaneta41633172019-05-23 20:12:29 +02006954 std::string transport_name = GetTransportName(result.value()->name);
6955 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006956}
6957
6958bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07006959 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006960 (dtls_enabled_ ||
6961 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006962}
6963
6964void PeerConnection::OnTransportControllerGatheringState(
6965 cricket::IceGatheringState state) {
6966 RTC_DCHECK(signaling_thread()->IsCurrent());
6967 if (state == cricket::kIceGatheringGathering) {
6968 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6969 } else if (state == cricket::kIceGatheringComplete) {
6970 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6971 }
6972}
6973
6974void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006975 std::map<std::string, std::set<cricket::MediaType>>
6976 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006977 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006978 if (transceiver->internal()->channel()) {
6979 const std::string& transport_name =
6980 transceiver->internal()->channel()->transport_name();
6981 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006982 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006983 }
Steve Anton75737c02017-11-06 10:37:17 -08006984 }
6985 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006986 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6987 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006988 }
Zhi Huange830e682018-03-30 10:48:35 -07006989
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006990 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006991 if (transport_name) {
6992 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006993 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006994 }
Zhi Huange830e682018-03-30 10:48:35 -07006995
Steve Antonc7b964c2018-02-01 14:39:45 -08006996 for (const auto& entry : media_types_by_transport_name) {
6997 const std::string& transport_name = entry.first;
6998 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006999 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007000 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007001 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007002 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007003 }
7004 }
7005}
7006// Walk through the ConnectionInfos to gather best connection usage
7007// for IPv4 and IPv6.
7008void PeerConnection::ReportBestConnectionState(
7009 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007010 for (const cricket::TransportChannelStats& channel_stats :
7011 stats.channel_stats) {
7012 for (const cricket::ConnectionInfo& connection_info :
7013 channel_stats.connection_infos) {
7014 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007015 continue;
7016 }
7017
Steve Antonc7b964c2018-02-01 14:39:45 -08007018 const cricket::Candidate& local = connection_info.local_candidate;
7019 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007020
7021 // Increment the counter for IceCandidatePairType.
7022 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7023 (local.type() == RELAY_PORT_TYPE &&
7024 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007025 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7026 GetIceCandidatePairCounter(local, remote),
7027 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007028 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007029 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7030 GetIceCandidatePairCounter(local, remote),
7031 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007032 } else {
7033 RTC_CHECK(0);
7034 }
Steve Anton75737c02017-11-06 10:37:17 -08007035
7036 // Increment the counter for IP type.
7037 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007038 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7039 kBestConnections_IPv4,
7040 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007041 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007042 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7043 kBestConnections_IPv6,
7044 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007045 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007046 RTC_CHECK(!local.address().hostname().empty() &&
7047 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007048 }
7049
7050 return;
7051 }
7052 }
7053}
7054
7055void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007056 const cricket::TransportStats& stats,
7057 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007058 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7059 return;
7060 }
7061
7062 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7063 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7064 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7065 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7066 return;
7067 }
7068
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007069 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7070 for (cricket::MediaType media_type : media_types) {
7071 switch (media_type) {
7072 case cricket::MEDIA_TYPE_AUDIO:
7073 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7074 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7075 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7076 break;
7077 case cricket::MEDIA_TYPE_VIDEO:
7078 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7079 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7080 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7081 break;
7082 case cricket::MEDIA_TYPE_DATA:
7083 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7084 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7085 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7086 break;
7087 default:
7088 RTC_NOTREACHED();
7089 continue;
7090 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007091 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007092 }
7093
7094 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7095 for (cricket::MediaType media_type : media_types) {
7096 switch (media_type) {
7097 case cricket::MEDIA_TYPE_AUDIO:
7098 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7099 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7100 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7101 break;
7102 case cricket::MEDIA_TYPE_VIDEO:
7103 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7104 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7105 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7106 break;
7107 case cricket::MEDIA_TYPE_DATA:
7108 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7109 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7110 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7111 break;
7112 default:
7113 RTC_NOTREACHED();
7114 continue;
7115 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007116 }
Steve Anton75737c02017-11-06 10:37:17 -08007117 }
7118}
7119
7120void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007121 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007122 RTC_DCHECK(call_);
7123 call_->OnSentPacket(sent_packet);
7124}
7125
7126const std::string PeerConnection::GetTransportName(
7127 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007128 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007129 if (channel) {
7130 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007131 }
Steve Anton6fec8802017-12-04 10:37:29 -08007132 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007133 RTC_DCHECK(sctp_mid_);
7134 if (content_name == *sctp_mid_) {
7135 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007136 }
7137 }
7138 // Return an empty string if failed to retrieve the transport name.
7139 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007140}
7141
Steve Anton6fec8802017-12-04 10:37:29 -08007142void PeerConnection::DestroyTransceiverChannel(
7143 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7144 transceiver) {
7145 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007146
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007147 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007148 if (channel) {
7149 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007150 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007151 }
7152}
7153
7154void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007155 if (rtp_data_channel_) {
7156 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007157 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007158 rtp_data_channel_ = nullptr;
7159 }
7160
7161 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7162 // grab a reference to this PeerConnection. If this is called from the
7163 // PeerConnection destructor, the RefCountedObject vtable will have already
7164 // been destroyed (since it is a subclass of PeerConnection) and using
7165 // rtc::Bind will cause "Pure virtual function called" error to appear.
7166
7167 if (sctp_transport_) {
7168 OnDataChannelDestroyed();
7169 network_thread()->Invoke<void>(RTC_FROM_HERE,
7170 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007171 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007172 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007173
7174 if (media_transport_) {
7175 OnDataChannelDestroyed();
7176 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7177 RTC_DCHECK_RUN_ON(network_thread());
7178 TeardownMediaTransportForDataChannels_n();
7179 });
7180 }
Steve Anton6fec8802017-12-04 10:37:29 -08007181}
7182
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007183void PeerConnection::DestroyChannelInterface(
7184 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007185 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007186 switch (channel->media_type()) {
7187 case cricket::MEDIA_TYPE_AUDIO:
7188 channel_manager()->DestroyVoiceChannel(
7189 static_cast<cricket::VoiceChannel*>(channel));
7190 break;
7191 case cricket::MEDIA_TYPE_VIDEO:
7192 channel_manager()->DestroyVideoChannel(
7193 static_cast<cricket::VideoChannel*>(channel));
7194 break;
7195 case cricket::MEDIA_TYPE_DATA:
7196 channel_manager()->DestroyRtpDataChannel(
7197 static_cast<cricket::RtpDataChannel*>(channel));
7198 break;
7199 default:
7200 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7201 break;
7202 }
Zhi Huange830e682018-03-30 10:48:35 -07007203}
Steve Anton6fec8802017-12-04 10:37:29 -08007204
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007205bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007206 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007207 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007208 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007209 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007210 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007211 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007212 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007213 auto base_channel = GetChannel(mid);
7214 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007215 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007216 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007217 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007218 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007219 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007220
Karl Wiberg5966c502019-02-21 23:55:09 +01007221 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007222 // Only pass media transport to call object if media transport is used
7223 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007224 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007225 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007226
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007227 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007228}
7229
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007230void PeerConnection::OnSetStreams() {
7231 RTC_DCHECK_RUN_ON(signaling_thread());
7232 if (IsUnifiedPlan())
7233 UpdateNegotiationNeeded();
7234}
7235
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007236PeerConnectionObserver* PeerConnection::Observer() const {
7237 // In earlier production code, the pointer was not cleared on close,
7238 // which might have led to undefined behavior if the observer was not
7239 // deallocated, or strange crashes if it was.
7240 // We use CHECK in order to catch such behavior if it exists.
7241 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7242 RTC_CHECK(observer_);
7243 return observer_;
7244}
7245
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007246CryptoOptions PeerConnection::GetCryptoOptions() {
7247 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7248 // after it has been removed.
7249 return configuration_.crypto_options.has_value()
7250 ? *configuration_.crypto_options
7251 : factory_->options().crypto_options;
7252}
7253
Harald Alvestrand89061872018-01-02 14:08:34 +01007254void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007255 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007256 if (stats_collector_) {
7257 stats_collector_->ClearCachedStatsReport();
7258 }
7259}
7260
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007261void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007262 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7263 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007264}
7265
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007266void PeerConnection::UpdateNegotiationNeeded() {
7267 RTC_DCHECK_RUN_ON(signaling_thread());
7268 if (!IsUnifiedPlan()) {
7269 Observer()->OnRenegotiationNeeded();
7270 return;
7271 }
7272
7273 // If connection's [[IsClosed]] slot is true, abort these steps.
7274 if (IsClosed())
7275 return;
7276
7277 // If connection's signaling state is not "stable", abort these steps.
7278 if (signaling_state() != kStable)
7279 return;
7280
7281 // NOTE
7282 // The negotiation-needed flag will be updated once the state transitions to
7283 // "stable", as part of the steps for setting an RTCSessionDescription.
7284
7285 // If the result of checking if negotiation is needed is false, clear the
7286 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7287 // to false, and abort these steps.
7288 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7289 if (!is_negotiation_needed) {
7290 is_negotiation_needed_ = false;
7291 return;
7292 }
7293
7294 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7295 // steps.
7296 if (is_negotiation_needed_)
7297 return;
7298
7299 // Set connection's [[NegotiationNeeded]] slot to true.
7300 is_negotiation_needed_ = true;
7301
7302 // Queue a task that runs the following steps:
7303 // If connection's [[IsClosed]] slot is true, abort these steps.
7304 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7305 // Fire an event named negotiationneeded at connection.
7306 Observer()->OnRenegotiationNeeded();
7307}
7308
7309bool PeerConnection::CheckIfNegotiationIsNeeded() {
7310 RTC_DCHECK_RUN_ON(signaling_thread());
7311 // 1. If any implementation-specific negotiation is required, as described at
7312 // the start of this section, return true.
7313
7314 // 2. Let description be connection.[[CurrentLocalDescription]].
7315 const SessionDescriptionInterface* description = current_local_description();
7316 if (!description)
7317 return true;
7318
7319 // 3. If connection has created any RTCDataChannels, and no m= section in
7320 // description has been negotiated yet for data, return true.
7321 if (!sctp_data_channels_.empty()) {
7322 if (!cricket::GetFirstDataContent(description->description()->contents()))
7323 return true;
7324 }
7325
7326 // 4. For each transceiver in connection's set of transceivers, perform the
7327 // following checks:
7328 for (const auto& transceiver : transceivers_) {
7329 const ContentInfo* current_local_msection =
7330 FindTransceiverMSection(transceiver.get(), description);
7331
7332 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7333 transceiver.get(), current_remote_description());
7334
7335 // 4.3 If transceiver is stopped and is associated with an m= section,
7336 // but the associated m= section is not yet rejected in
7337 // connection.[[CurrentLocalDescription]] or
7338 // connection.[[CurrentRemoteDescription]], return true.
7339 if (transceiver->stopped()) {
7340 if (current_local_msection && !current_local_msection->rejected &&
7341 ((current_remote_msection && !current_remote_msection->rejected) ||
7342 !current_remote_msection)) {
7343 return true;
7344 }
7345 continue;
7346 }
7347
7348 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7349 // section in description, return true.
7350 if (!current_local_msection)
7351 return true;
7352
7353 const MediaContentDescription* current_local_media_description =
7354 current_local_msection->media_description();
7355 // 4.2 If transceiver isn't stopped and is associated with an m= section
7356 // in description then perform the following checks:
7357
7358 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7359 // associated m= section in description either doesn't contain a single
7360 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7361 // m= section, or the MSID values themselves, differ from what is in
7362 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7363 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7364 if (current_local_media_description->streams().size() == 0)
7365 return true;
7366
7367 std::vector<std::string> msection_msids;
7368 for (const auto& stream : current_local_media_description->streams()) {
7369 for (const std::string& msid : stream.stream_ids())
7370 msection_msids.push_back(msid);
7371 }
7372
7373 std::vector<std::string> transceiver_msids =
7374 transceiver->sender()->stream_ids();
7375 if (msection_msids.size() != transceiver_msids.size())
7376 return true;
7377
7378 absl::c_sort(transceiver_msids);
7379 absl::c_sort(msection_msids);
7380 if (transceiver_msids != msection_msids)
7381 return true;
7382 }
7383
7384 // 4.2.2 If description is of type "offer", and the direction of the
7385 // associated m= section in neither connection.[[CurrentLocalDescription]]
7386 // nor connection.[[CurrentRemoteDescription]] matches
7387 // transceiver.[[Direction]], return true.
7388 if (description->GetType() == SdpType::kOffer) {
7389 if (!current_remote_description())
7390 return true;
7391
7392 if (!current_remote_msection)
7393 return true;
7394
7395 RtpTransceiverDirection current_local_direction =
7396 current_local_media_description->direction();
7397 RtpTransceiverDirection current_remote_direction =
7398 current_remote_msection->media_description()->direction();
7399 if (transceiver->direction() != current_local_direction &&
7400 transceiver->direction() !=
7401 RtpTransceiverDirectionReversed(current_remote_direction)) {
7402 return true;
7403 }
7404 }
7405
7406 // 4.2.3 If description is of type "answer", and the direction of the
7407 // associated m= section in the description does not match
7408 // transceiver.[[Direction]] intersected with the offered direction (as
7409 // described in [JSEP] (section 5.3.1.)), return true.
7410 if (description->GetType() == SdpType::kAnswer) {
7411 if (!remote_description())
7412 return true;
7413
7414 const ContentInfo* offered_remote_msection =
7415 FindTransceiverMSection(transceiver.get(), remote_description());
7416
7417 RtpTransceiverDirection offered_direction =
7418 offered_remote_msection
7419 ? offered_remote_msection->media_description()->direction()
7420 : RtpTransceiverDirection::kInactive;
7421
7422 if (current_local_media_description->direction() !=
7423 (RtpTransceiverDirectionIntersection(
7424 transceiver->direction(),
7425 RtpTransceiverDirectionReversed(offered_direction)))) {
7426 return true;
7427 }
7428 }
7429 }
7430
7431 // If all the preceding checks were performed and true was not returned,
7432 // nothing remains to be negotiated; return false.
7433 return false;
7434}
7435
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007436} // namespace webrtc