blob: b1ec403c0f05f1735752a29395a364aea4ac9633 [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öm79b69802019-07-18 11:16:56 +0200693class PeerConnection::LocalIceCredentialsToReplace {
694 public:
695 // Sets the ICE credentials that need restarting to the ICE credentials of
696 // the current and pending descriptions.
697 void SetIceCredentialsFromLocalDescriptions(
698 const SessionDescriptionInterface* current_local_description,
699 const SessionDescriptionInterface* pending_local_description) {
700 ice_credentials_.clear();
701 if (current_local_description) {
702 AppendIceCredentialsFromSessionDescription(*current_local_description);
703 }
704 if (pending_local_description) {
705 AppendIceCredentialsFromSessionDescription(*pending_local_description);
706 }
707 }
708
709 void ClearIceCredentials() { ice_credentials_.clear(); }
710
711 // Returns true if we have ICE credentials that need restarting.
712 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
713
714 // Returns true if |local_description| shares no ICE credentials with the
715 // ICE credentials that need restarting.
716 bool SatisfiesIceRestart(
717 const SessionDescriptionInterface& local_description) const {
718 for (const auto& transport_info :
719 local_description.description()->transport_infos()) {
720 if (ice_credentials_.find(std::make_pair(
721 transport_info.description.ice_ufrag,
722 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
723 return false;
724 }
725 }
726 return true;
727 }
728
729 private:
730 void AppendIceCredentialsFromSessionDescription(
731 const SessionDescriptionInterface& desc) {
732 for (const auto& transport_info : desc.description()->transport_infos()) {
733 ice_credentials_.insert(
734 std::make_pair(transport_info.description.ice_ufrag,
735 transport_info.description.ice_pwd));
736 }
737 }
738
739 std::set<std::pair<std::string, std::string>> ice_credentials_;
740};
741
Henrik Boström31638672017-11-23 17:48:32 +0100742// Upon completion, posts a task to execute the callback of the
743// SetSessionDescriptionObserver asynchronously on the same thread. At this
744// point, the state of the peer connection might no longer reflect the effects
745// of the SetRemoteDescription operation, as the peer connection could have been
746// modified during the post.
747// TODO(hbos): Remove this class once we remove the version of
748// PeerConnectionInterface::SetRemoteDescription() that takes a
749// SetSessionDescriptionObserver as an argument.
750class PeerConnection::SetRemoteDescriptionObserverAdapter
751 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
752 public:
753 SetRemoteDescriptionObserverAdapter(
754 rtc::scoped_refptr<PeerConnection> pc,
755 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
756 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
757
758 // SetRemoteDescriptionObserverInterface implementation.
759 void OnSetRemoteDescriptionComplete(RTCError error) override {
760 if (error.ok())
761 pc_->PostSetSessionDescriptionSuccess(wrapper_);
762 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100763 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100764 }
765
766 private:
767 rtc::scoped_refptr<PeerConnection> pc_;
768 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
769};
770
deadbeef293e9262017-01-11 12:28:30 -0800771bool PeerConnectionInterface::RTCConfiguration::operator==(
772 const PeerConnectionInterface::RTCConfiguration& o) const {
773 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700774 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800775 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000776 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700777 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800778 BundlePolicy bundle_policy;
779 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700780 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
781 int ice_candidate_pool_size;
782 bool disable_ipv6;
783 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700784 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100785 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700786 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200787 absl::optional<int> screencast_min_bitrate;
788 absl::optional<bool> combined_audio_video_bwe;
789 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800790 TcpCandidatePolicy tcp_candidate_policy;
791 CandidateNetworkPolicy candidate_network_policy;
792 int audio_jitter_buffer_max_packets;
793 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100794 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100795 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800796 int ice_connection_receiving_timeout;
797 int ice_backup_candidate_pair_ping_interval;
798 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800799 bool prioritize_most_likely_ice_candidate_pairs;
800 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800801 bool prune_turn_ports;
802 bool presume_writable_when_fully_relayed;
803 bool enable_ice_renomination;
804 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700805 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200806 absl::optional<int> ice_check_interval_strong_connectivity;
807 absl::optional<int> ice_check_interval_weak_connectivity;
808 absl::optional<int> ice_check_min_interval;
809 absl::optional<int> ice_unwritable_timeout;
810 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800811 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200812 absl::optional<int> stun_candidate_keepalive_interval;
813 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200814 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800815 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200816 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700817 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700818 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700819 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700820 absl::optional<bool> use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700821 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100822 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800823 };
824 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
825 "Did you add something to RTCConfiguration and forget to "
826 "update operator==?");
827 return type == o.type && servers == o.servers &&
828 bundle_policy == o.bundle_policy &&
829 rtcp_mux_policy == o.rtcp_mux_policy &&
830 tcp_candidate_policy == o.tcp_candidate_policy &&
831 candidate_network_policy == o.candidate_network_policy &&
832 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
833 audio_jitter_buffer_fast_accelerate ==
834 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100835 audio_jitter_buffer_min_delay_ms ==
836 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100837 audio_jitter_buffer_enable_rtx_handling ==
838 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800839 ice_connection_receiving_timeout ==
840 o.ice_connection_receiving_timeout &&
841 ice_backup_candidate_pair_ping_interval ==
842 o.ice_backup_candidate_pair_ping_interval &&
843 continual_gathering_policy == o.continual_gathering_policy &&
844 certificates == o.certificates &&
845 prioritize_most_likely_ice_candidate_pairs ==
846 o.prioritize_most_likely_ice_candidate_pairs &&
847 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800848 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700849 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100850 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800851 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800852 screencast_min_bitrate == o.screencast_min_bitrate &&
853 combined_audio_video_bwe == o.combined_audio_video_bwe &&
854 enable_dtls_srtp == o.enable_dtls_srtp &&
855 ice_candidate_pool_size == o.ice_candidate_pool_size &&
856 prune_turn_ports == o.prune_turn_ports &&
857 presume_writable_when_fully_relayed ==
858 o.presume_writable_when_fully_relayed &&
859 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800860 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700861 surface_ice_candidates_on_ice_transport_type_changed ==
862 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800863 ice_check_interval_strong_connectivity ==
864 o.ice_check_interval_strong_connectivity &&
865 ice_check_interval_weak_connectivity ==
866 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700867 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700868 ice_unwritable_timeout == o.ice_unwritable_timeout &&
869 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800870 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800871 stun_candidate_keepalive_interval ==
872 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200873 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800874 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800875 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700876 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700877 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700878 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700879 use_media_transport_for_data_channels ==
880 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700881 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100882 crypto_options == o.crypto_options &&
883 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800884}
885
886bool PeerConnectionInterface::RTCConfiguration::operator!=(
887 const PeerConnectionInterface::RTCConfiguration& o) const {
888 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800889}
890
zhihuang8f65cdf2016-05-06 18:40:30 -0700891// Generate a RTCP CNAME when a PeerConnection is created.
892std::string GenerateRtcpCname() {
893 std::string cname;
894 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800896 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700897 }
898 return cname;
899}
900
zhihuang1c378ed2017-08-17 14:10:50 -0700901bool ValidateOfferAnswerOptions(
902 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
903 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
904 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700905}
906
zhihuang1c378ed2017-08-17 14:10:50 -0700907// From |rtc_options|, fill parts of |session_options| shared by all generated
908// m= sections (in other words, nothing that involves a map/array).
909void ExtractSharedMediaSessionOptions(
910 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
911 cricket::MediaSessionOptions* session_options) {
912 session_options->vad_enabled = rtc_options.voice_activity_detection;
913 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200914 session_options->raw_packetization_for_video =
915 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700916}
zhihuanga77e6bb2017-08-14 18:17:48 -0700917
zhihuang38ede132017-06-15 12:52:32 -0700918PeerConnection::PeerConnection(PeerConnectionFactory* factory,
919 std::unique_ptr<RtcEventLog> event_log,
920 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700922 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100923 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700924 datagram_transport_config_(
925 field_trial::FindFullName(kDatagramTransportFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700926 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700927 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700928 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100929 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200930 call_ptr_(call_.get()),
931 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932
933PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100934 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800935 RTC_DCHECK_RUN_ON(signaling_thread());
936
Steve Anton8af21862017-12-15 11:20:13 -0800937 // Need to stop transceivers before destroying the stats collector because
938 // AudioRtpSender has a reference to the StatsCollector it will update when
939 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100940 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800941 transceiver->Stop();
942 }
Steve Anton4171afb2017-11-20 10:20:22 -0800943
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700944 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800945 if (stats_collector_) {
946 stats_collector_->WaitForPendingRequest();
947 stats_collector_ = nullptr;
948 }
Steve Anton75737c02017-11-06 10:37:17 -0800949
Steve Anton8af21862017-12-15 11:20:13 -0800950 // Don't destroy BaseChannels until after stats has been cleaned up so that
951 // the last stats request can still read from the channels.
952 DestroyAllChannels();
953
Mirko Bonadei675513b2017-11-09 11:09:25 +0100954 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800955
956 webrtc_session_desc_factory_.reset();
957 sctp_invoker_.reset();
958 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800959 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800960 transport_controller_.reset();
961
deadbeef91dd5672016-05-18 16:55:30 -0700962 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100963 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
964 RTC_DCHECK_RUN_ON(network_thread());
965 port_allocator_.reset();
966 });
eladalon248fd4f2017-09-06 05:18:15 -0700967 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700968 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100969 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700970 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800971 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700972 event_log_.reset();
973 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974}
975
Steve Anton8af21862017-12-15 11:20:13 -0800976void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800977 // Destroy video channels first since they may have a pointer to a voice
978 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100979 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800980 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800981 DestroyTransceiverChannel(transceiver);
982 }
983 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100984 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800985 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800986 DestroyTransceiverChannel(transceiver);
987 }
988 }
989 DestroyDataChannel();
990}
991
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000993 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700994 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100995 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100996 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100997 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700998
999 RTCError config_error = ValidateConfiguration(configuration);
1000 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001001 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -07001002 return false;
1003 }
1004
Benjamin Wrightcab58882018-05-02 15:12:47 -07001005 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001006 RTC_LOG(LS_ERROR)
1007 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001008 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001009 return false;
1010 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001011
Benjamin Wrightcab58882018-05-02 15:12:47 -07001012 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001013 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001014 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001015 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001016 return false;
1017 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001018
Benjamin Wrightcab58882018-05-02 15:12:47 -07001019 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001020 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001021 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001022 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001023
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001024 cricket::ServerAddresses stun_servers;
1025 std::vector<cricket::RelayServerConfig> turn_servers;
1026
1027 RTCErrorType parse_error =
1028 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1029 if (parse_error != RTCErrorType::NONE) {
1030 return false;
1031 }
1032
deadbeef91dd5672016-05-18 16:55:30 -07001033 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001034 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001035 const auto pa_result =
1036 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001037 RTC_FROM_HERE,
1038 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001039 stun_servers, turn_servers, configuration));
1040
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001041 // If initialization was successful, note if STUN or TURN servers
1042 // were supplied.
1043 if (!stun_servers.empty()) {
1044 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1045 }
1046 if (!turn_servers.empty()) {
1047 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1048 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001050 // Send information about IPv4/IPv6 status.
1051 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001052 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001053 address_family = kPeerConnection_IPv6;
1054 } else {
1055 address_family = kPeerConnection_IPv4;
1056 }
1057 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1058 kPeerConnectionAddressFamilyCounter_Max);
1059
Zhi Huange830e682018-03-30 10:48:35 -07001060 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1061
Steve Anton75737c02017-11-06 10:37:17 -08001062 // RFC 3264: The numeric value of the session id and version in the
1063 // o line MUST be representable with a "64 bit signed integer".
1064 // Due to this constraint session id |session_id_| is max limited to
1065 // LLONG_MAX.
1066 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001067 JsepTransportController::Config config;
1068 config.redetermine_role_on_ice_restart =
1069 configuration.redetermine_role_on_ice_restart;
1070 config.ssl_max_version = factory_->options().ssl_max_version;
1071 config.disable_encryption = options.disable_encryption;
1072 config.bundle_policy = configuration.bundle_policy;
1073 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001074 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1075 // stub.
1076 config.crypto_options = configuration.crypto_options.has_value()
1077 ? *configuration.crypto_options
1078 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001079 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001080 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001081#if defined(ENABLE_EXTERNAL_AUTH)
1082 config.enable_external_auth = true;
1083#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001084 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001085
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001086 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001087 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001088 datagram_transport_config_.default_value);
1089 if (use_datagram_transport_ || configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001090 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001091 if (!factory_->media_transport_factory()) {
1092 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001093 << "PeerConnecton is initialized with use_media_transport = true or "
1094 << "use_media_transport_for_data_channels = true "
1095 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001096 return false;
1097 }
1098
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001099 if (configuration.use_media_transport ||
1100 configuration.use_media_transport_for_data_channels) {
1101 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1102 // RTP media transport is introduced. But until then, we require SDES to
1103 // be enabled.
1104 if (configuration.enable_dtls_srtp.has_value() &&
1105 configuration.enable_dtls_srtp.value()) {
1106 RTC_LOG(LS_WARNING)
1107 << "When media transport is used, SDES must be enabled. Set "
1108 "configuration.enable_dtls_srtp to false. use_media_transport="
1109 << configuration.use_media_transport
1110 << ", use_media_transport_for_data_channels="
1111 << configuration.use_media_transport_for_data_channels;
1112 return false;
1113 }
1114 }
1115
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001116 config.use_media_transport_for_media = configuration.use_media_transport;
1117 config.use_media_transport_for_data_channels =
1118 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001119 config.use_datagram_transport = use_datagram_transport_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001120 config.media_transport_factory = factory_->media_transport_factory();
1121 }
1122
Zhi Huange830e682018-03-30 10:48:35 -07001123 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001124 signaling_thread(), network_thread(), port_allocator_.get(),
1125 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001126 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001127 this, &PeerConnection::OnTransportControllerConnectionState);
1128 transport_controller_->SignalStandardizedIceConnectionState.connect(
1129 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001130 transport_controller_->SignalConnectionState.connect(
1131 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001132 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001133 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001134 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001135 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001136 transport_controller_->SignalIceCandidateError.connect(
1137 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001138 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001139 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1140 transport_controller_->SignalDtlsHandshakeError.connect(
1141 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001142 transport_controller_->SignalIceCandidatePairChanged.connect(
1143 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001144
1145 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001146
deadbeefab9b2d12015-10-14 11:33:11 -07001147 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001148 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001149
Steve Antonba818672017-11-06 10:21:57 -08001150 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001151 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001152
Steve Anton75737c02017-11-06 10:37:17 -08001153 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1154 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1155 if (!configuration.certificates.empty()) {
1156 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1157 // just picking the first one. The decision should be made based on the DTLS
1158 // handshake. The DTLS negotiations need to know about all certificates.
1159 certificate = configuration.certificates[0];
1160 }
1161
Steve Antond25da372017-11-06 14:50:29 -08001162 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001163
1164 if (options.disable_encryption) {
1165 dtls_enabled_ = false;
1166 } else {
1167 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001168 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001169 // |configuration| can override the default |dtls_enabled_| value.
1170 if (configuration.enable_dtls_srtp) {
1171 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1172 }
1173 }
1174
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001175 if (configuration.use_media_transport_for_data_channels) {
1176 if (configuration.enable_rtp_data_channel) {
1177 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1178 "use_media_transport_for_data_channels are "
1179 "incompatible and cannot both be set to true";
1180 return false;
1181 }
1182 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1183 } else if (configuration.enable_rtp_data_channel) {
1184 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1185 // set. It takes precendence over the disable_sctp_data_channels
1186 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001187 data_channel_type_ = cricket::DCT_RTP;
1188 } else {
1189 // DTLS has to be enabled to use SCTP.
1190 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1191 data_channel_type_ = cricket::DCT_SCTP;
1192 }
1193 }
1194
1195 video_options_.screencast_min_bitrate_kbps =
1196 configuration.screencast_min_bitrate;
1197 audio_options_.combined_audio_video_bwe =
1198 configuration.combined_audio_video_bwe;
1199
1200 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001201 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001202
1203 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001204 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001205
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001206 audio_options_.audio_jitter_buffer_min_delay_ms =
1207 configuration.audio_jitter_buffer_min_delay_ms;
1208
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001209 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1210 configuration.audio_jitter_buffer_enable_rtx_handling;
1211
Steve Anton75737c02017-11-06 10:37:17 -08001212 // Whether the certificate generator/certificate is null or not determines
1213 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1214 // the right instructions by clearing the variables if needed.
1215 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001216 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001217 certificate = nullptr;
1218 } else if (certificate) {
1219 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001220 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001221 }
1222
1223 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1224 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001225 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001226 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1227 this, &PeerConnection::OnCertificateReady);
1228
1229 if (options.disable_encryption) {
1230 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1231 }
1232
1233 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001234 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001235 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236
Steve Anton4171afb2017-11-20 10:20:22 -08001237 // Add default audio/video transceivers for Plan B SDP.
1238 if (!IsUnifiedPlan()) {
1239 transceivers_.push_back(
1240 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1241 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1242 transceivers_.push_back(
1243 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1244 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1245 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001246 int delay_ms =
1247 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001248 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1249 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001250
1251 if (dependencies.video_bitrate_allocator_factory) {
1252 video_bitrate_allocator_factory_ =
1253 std::move(dependencies.video_bitrate_allocator_factory);
1254 } else {
1255 video_bitrate_allocator_factory_ =
1256 CreateBuiltinVideoBitrateAllocatorFactory();
1257 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 return true;
1259}
1260
Steve Anton038834f2017-07-14 15:59:59 -07001261RTCError PeerConnection::ValidateConfiguration(
1262 const RTCConfiguration& config) const {
1263 if (config.ice_regather_interval_range &&
1264 config.continual_gathering_policy == GATHER_ONCE) {
1265 return RTCError(RTCErrorType::INVALID_PARAMETER,
1266 "ice_regather_interval_range specified but continual "
1267 "gathering policy is GATHER_ONCE");
1268 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001269 auto result =
1270 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1271 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001272}
1273
Yves Gerey665174f2018-06-19 15:03:05 +02001274rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001275 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001276 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1277 "Plan SdpSemantics. Please use GetSenders "
1278 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001279 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280}
1281
Yves Gerey665174f2018-06-19 15:03:05 +02001282rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001283 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001284 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1285 "Plan SdpSemantics. Please use GetReceivers "
1286 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001287 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288}
1289
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001290bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001291 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001292 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1293 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001294 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 if (IsClosed()) {
1296 return false;
1297 }
deadbeefab9b2d12015-10-14 11:33:11 -07001298 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 return false;
1300 }
deadbeefab9b2d12015-10-14 11:33:11 -07001301
1302 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001303 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1304 observer->SignalAudioTrackAdded.connect(this,
1305 &PeerConnection::OnAudioTrackAdded);
1306 observer->SignalAudioTrackRemoved.connect(
1307 this, &PeerConnection::OnAudioTrackRemoved);
1308 observer->SignalVideoTrackAdded.connect(this,
1309 &PeerConnection::OnVideoTrackAdded);
1310 observer->SignalVideoTrackRemoved.connect(
1311 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001312 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001313
deadbeefab9b2d12015-10-14 11:33:11 -07001314 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001315 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001316 }
1317 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001318 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001319 }
1320
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001321 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001322 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 return true;
1324}
1325
1326void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001327 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001328 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1329 "Plan SdpSemantics. Please use RemoveTrack "
1330 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001331 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001332 if (!IsClosed()) {
1333 for (const auto& track : local_stream->GetAudioTracks()) {
1334 RemoveAudioTrack(track.get(), local_stream);
1335 }
1336 for (const auto& track : local_stream->GetVideoTracks()) {
1337 RemoveVideoTrack(track.get(), local_stream);
1338 }
deadbeefab9b2d12015-10-14 11:33:11 -07001339 }
deadbeefab9b2d12015-10-14 11:33:11 -07001340 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001341 stream_observers_.erase(
1342 std::remove_if(
1343 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001344 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001345 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001346 }),
1347 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001348
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 if (IsClosed()) {
1350 return;
1351 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001352 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353}
1354
Steve Anton2d6c76a2018-01-05 17:10:52 -08001355RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001356 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001357 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001358 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001359 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001360 if (!track) {
1361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1362 }
1363 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1364 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1365 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1366 "Track has invalid kind: " + track->kind());
1367 }
Steve Antonf9381f02017-12-14 10:23:57 -08001368 if (IsClosed()) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1370 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001371 }
Steve Anton4171afb2017-11-20 10:20:22 -08001372 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001373 LOG_AND_RETURN_ERROR(
1374 RTCErrorType::INVALID_PARAMETER,
1375 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001376 }
Steve Antonf9381f02017-12-14 10:23:57 -08001377 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001378 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1379 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001380 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001381 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001382 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001383 }
1384 return sender_or_error;
1385}
deadbeefe1f9d832016-01-14 15:35:42 -08001386
Steve Antonf9381f02017-12-14 10:23:57 -08001387RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1388PeerConnection::AddTrackPlanB(
1389 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001390 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001391 if (stream_ids.size() > 1u) {
1392 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1393 "AddTrack with more than one stream is not "
1394 "supported with Plan B semantics.");
1395 }
1396 std::vector<std::string> adjusted_stream_ids = stream_ids;
1397 if (adjusted_stream_ids.empty()) {
1398 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1399 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001400 cricket::MediaType media_type =
1401 (track->kind() == MediaStreamTrackInterface::kAudioKind
1402 ? cricket::MEDIA_TYPE_AUDIO
1403 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001404 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001405 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001406 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001407 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001408 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001409 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001410 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001411 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001412 if (sender_info) {
1413 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001414 }
Steve Antonf9381f02017-12-14 10:23:57 -08001415 } else {
1416 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001417 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001418 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001419 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001420 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001421 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001422 if (sender_info) {
1423 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001424 }
deadbeefe1f9d832016-01-14 15:35:42 -08001425 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001426 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001427}
deadbeefe1f9d832016-01-14 15:35:42 -08001428
Steve Antonf9381f02017-12-14 10:23:57 -08001429RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1430PeerConnection::AddTrackUnifiedPlan(
1431 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001432 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001433 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1434 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001435 RTC_LOG(LS_INFO) << "Reusing an existing "
1436 << cricket::MediaTypeToString(transceiver->media_type())
1437 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001438 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001439 transceiver->internal()->set_direction(
1440 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001441 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001442 transceiver->internal()->set_direction(
1443 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001444 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001445 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001446 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001447 } else {
1448 cricket::MediaType media_type =
1449 (track->kind() == MediaStreamTrackInterface::kAudioKind
1450 ? cricket::MEDIA_TYPE_AUDIO
1451 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001452 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1453 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001454 std::string sender_id = track->id();
1455 // Avoid creating a sender with an existing ID by generating a random ID.
1456 // This can happen if this is the second time AddTrack has created a sender
1457 // for this track.
1458 if (FindSenderById(sender_id)) {
1459 sender_id = rtc::CreateRandomUuid();
1460 }
Florent Castelli892acf02018-10-01 22:47:20 +02001461 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001462 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1463 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001464 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001465 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001466 }
Steve Antonf9381f02017-12-14 10:23:57 -08001467 return transceiver->sender();
1468}
1469
1470rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1471PeerConnection::FindFirstTransceiverForAddedTrack(
1472 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1473 RTC_DCHECK(track);
1474 for (auto transceiver : transceivers_) {
1475 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001476 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001477 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001478 !transceiver->internal()->has_ever_been_used_to_send() &&
1479 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001480 return transceiver;
1481 }
1482 }
1483 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001484}
1485
1486bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1487 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001488 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001489}
1490
Steve Anton24db5732018-07-23 10:27:33 -07001491RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001492 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001493 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001494 if (!sender) {
1495 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1496 }
deadbeefe1f9d832016-01-14 15:35:42 -08001497 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1499 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001500 }
Steve Antonf9381f02017-12-14 10:23:57 -08001501 if (IsUnifiedPlan()) {
1502 auto transceiver = FindTransceiverBySender(sender);
1503 if (!transceiver || !sender->track()) {
1504 return RTCError::OK();
1505 }
1506 sender->SetTrack(nullptr);
1507 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001508 transceiver->internal()->set_direction(
1509 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001510 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001511 transceiver->internal()->set_direction(
1512 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001513 }
Steve Anton4171afb2017-11-20 10:20:22 -08001514 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001515 bool removed;
1516 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1517 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1518 } else {
1519 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1520 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1521 }
1522 if (!removed) {
1523 LOG_AND_RETURN_ERROR(
1524 RTCErrorType::INVALID_PARAMETER,
1525 "Couldn't find sender " + sender->id() + " to remove.");
1526 }
Steve Anton4171afb2017-11-20 10:20:22 -08001527 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001528 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001529 return RTCError::OK();
1530}
1531
1532rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1533PeerConnection::FindTransceiverBySender(
1534 rtc::scoped_refptr<RtpSenderInterface> sender) {
1535 for (auto transceiver : transceivers_) {
1536 if (transceiver->sender() == sender) {
1537 return transceiver;
1538 }
1539 }
1540 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001541}
1542
Steve Anton9158ef62017-11-27 13:01:52 -08001543RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1544PeerConnection::AddTransceiver(
1545 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1546 return AddTransceiver(track, RtpTransceiverInit());
1547}
1548
1549RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1550PeerConnection::AddTransceiver(
1551 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1552 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001553 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001554 RTC_CHECK(IsUnifiedPlan())
1555 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001556 if (!track) {
1557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1558 }
1559 cricket::MediaType media_type;
1560 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1561 media_type = cricket::MEDIA_TYPE_AUDIO;
1562 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1563 media_type = cricket::MEDIA_TYPE_VIDEO;
1564 } else {
1565 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1566 "Track kind is not audio or video");
1567 }
1568 return AddTransceiver(media_type, track, init);
1569}
1570
1571RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1572PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1573 return AddTransceiver(media_type, RtpTransceiverInit());
1574}
1575
1576RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1577PeerConnection::AddTransceiver(cricket::MediaType media_type,
1578 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001579 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001580 RTC_CHECK(IsUnifiedPlan())
1581 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001582 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1583 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1584 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1585 "media type is not audio or video");
1586 }
1587 return AddTransceiver(media_type, nullptr, init);
1588}
1589
1590RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1591PeerConnection::AddTransceiver(
1592 cricket::MediaType media_type,
1593 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001594 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001595 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001596 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1597 media_type == cricket::MEDIA_TYPE_VIDEO));
1598 if (track) {
1599 RTC_DCHECK_EQ(media_type,
1600 (track->kind() == MediaStreamTrackInterface::kAudioKind
1601 ? cricket::MEDIA_TYPE_AUDIO
1602 : cricket::MEDIA_TYPE_VIDEO));
1603 }
1604
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001605 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1606 init.send_encodings.size(), 0, 7, 8);
1607
Amit Hilbuchaa584152019-02-06 17:09:52 -08001608 size_t num_rids = absl::c_count_if(init.send_encodings,
1609 [](const RtpEncodingParameters& encoding) {
1610 return !encoding.rid.empty();
1611 });
1612 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001613 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001614 RTCErrorType::INVALID_PARAMETER,
1615 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001616 }
1617
Amit Hilbuchf4770402019-04-08 14:11:57 -07001618 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1619 [](const RtpEncodingParameters& encoding) {
1620 return !IsLegalRsidName(encoding.rid);
1621 })) {
1622 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1623 "Invalid RID value provided.");
1624 }
1625
Amit Hilbuchaa584152019-02-06 17:09:52 -08001626 if (absl::c_any_of(init.send_encodings,
1627 [](const RtpEncodingParameters& encoding) {
1628 return encoding.ssrc.has_value();
1629 })) {
1630 LOG_AND_RETURN_ERROR(
1631 RTCErrorType::UNSUPPORTED_PARAMETER,
1632 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001633 }
1634
1635 RtpParameters parameters;
1636 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001637
1638 // Encodings are dropped from the tail if too many are provided.
1639 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1640 parameters.encodings.erase(
1641 parameters.encodings.begin() + kMaxSimulcastStreams,
1642 parameters.encodings.end());
1643 }
1644
1645 // Single RID should be removed.
1646 if (parameters.encodings.size() == 1 &&
1647 !parameters.encodings[0].rid.empty()) {
1648 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1649 parameters.encodings[0].rid.clear();
1650 }
1651
1652 // If RIDs were not provided, they are generated for simulcast scenario.
1653 if (parameters.encodings.size() > 1 && num_rids == 0) {
1654 rtc::UniqueStringGenerator rid_generator;
1655 for (RtpEncodingParameters& encoding : parameters.encodings) {
1656 encoding.rid = rid_generator();
1657 }
1658 }
1659
Florent Castelli892acf02018-10-01 22:47:20 +02001660 if (UnimplementedRtpParameterHasValue(parameters)) {
1661 LOG_AND_RETURN_ERROR(
1662 RTCErrorType::UNSUPPORTED_PARAMETER,
1663 "Attempted to set an unimplemented parameter of RtpParameters.");
1664 }
Steve Anton9158ef62017-11-27 13:01:52 -08001665
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001666 auto result = cricket::CheckRtpParametersValues(parameters);
1667 if (!result.ok()) {
1668 LOG_AND_RETURN_ERROR(result.type(), result.message());
1669 }
1670
Steve Anton3d954a62018-04-02 11:27:23 -07001671 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1672 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001673 // Set the sender ID equal to the track ID if the track is specified unless
1674 // that sender ID is already in use.
1675 std::string sender_id =
1676 (track && !FindSenderById(track->id()) ? track->id()
1677 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001678 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001679 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001680 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1681 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1682 transceiver->internal()->set_direction(init.direction);
1683
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001684 if (update_negotiation_needed) {
1685 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001686 }
Steve Antonf9381f02017-12-14 10:23:57 -08001687
1688 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1689}
1690
Steve Anton02ee47c2018-01-10 16:26:06 -08001691rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1692PeerConnection::CreateSender(
1693 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001694 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001695 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001696 const std::vector<std::string>& stream_ids,
1697 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001698 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001699 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001700 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1701 RTC_DCHECK(!track ||
1702 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1703 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1704 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001705 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001706 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001707 } else {
1708 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1709 RTC_DCHECK(!track ||
1710 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1711 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001712 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001713 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001714 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001715 bool set_track_succeeded = sender->SetTrack(track);
1716 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001717 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001718 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001719 return sender;
1720}
1721
1722rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1723PeerConnection::CreateReceiver(cricket::MediaType media_type,
1724 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001725 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1726 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001727 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001728 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001729 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1730 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001731 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001732 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001733 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001734 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001735 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1736 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001737 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001738 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001739 return receiver;
1740}
1741
1742rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1743PeerConnection::CreateAndAddTransceiver(
1744 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1745 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1746 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001747 // Ensure that the new sender does not have an ID that is already in use by
1748 // another sender.
1749 // Allow receiver IDs to conflict since those come from remote SDP (which
1750 // could be invalid, but should not cause a crash).
1751 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001752 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001753 signaling_thread(),
1754 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001755 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001756 transceiver->internal()->SignalNegotiationNeeded.connect(
1757 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001758 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001759}
1760
Steve Anton52d86772018-02-20 15:48:12 -08001761void PeerConnection::OnNegotiationNeeded() {
1762 RTC_DCHECK_RUN_ON(signaling_thread());
1763 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001764 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001765}
1766
deadbeeffac06552015-11-25 11:26:01 -08001767rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001768 const std::string& kind,
1769 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001770 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001771 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1772 "Plan SdpSemantics. Please use AddTransceiver "
1773 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001774 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001775 if (IsClosed()) {
1776 return nullptr;
1777 }
Steve Anton4171afb2017-11-20 10:20:22 -08001778
Seth Hampson5b4f0752018-04-02 16:31:36 -07001779 // Internally we need to have one stream with Plan B semantics, so we
1780 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001781 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001782 if (stream_id.empty()) {
1783 stream_ids.push_back(rtc::CreateRandomUuid());
1784 RTC_LOG(LS_INFO)
1785 << "No stream_id specified for sender. Generated stream ID: "
1786 << stream_ids[0];
1787 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001788 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001789 }
1790
Steve Anton4171afb2017-11-20 10:20:22 -08001791 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001792 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001793 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001794 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001795 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001796 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001797 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001798 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001799 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001800 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001801 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001802 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001803 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001804 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001805 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001806 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001807 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001808 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001809 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001810 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001811 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001812
deadbeefe1f9d832016-01-14 15:35:42 -08001813 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001814}
1815
deadbeef70ab1a12015-09-28 16:53:55 -07001816std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1817 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001818 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001819 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001820 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001821 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001822 }
1823 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001824}
1825
Steve Anton4171afb2017-11-20 10:20:22 -08001826std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1827PeerConnection::GetSendersInternal() const {
1828 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1829 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001830 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001831 auto senders = transceiver->internal()->senders();
1832 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1833 }
1834 return all_senders;
1835}
1836
deadbeef70ab1a12015-09-28 16:53:55 -07001837std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1838PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001839 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001840 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001841 for (const auto& receiver : GetReceiversInternal()) {
1842 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001843 }
1844 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001845}
1846
Steve Anton4171afb2017-11-20 10:20:22 -08001847std::vector<
1848 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1849PeerConnection::GetReceiversInternal() const {
1850 std::vector<
1851 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1852 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001853 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001854 auto receivers = transceiver->internal()->receivers();
1855 all_receivers.insert(all_receivers.end(), receivers.begin(),
1856 receivers.end());
1857 }
1858 return all_receivers;
1859}
1860
Steve Anton9158ef62017-11-27 13:01:52 -08001861std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1862PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001863 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001864 RTC_CHECK(IsUnifiedPlan())
1865 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001866 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001867 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001868 all_transceivers.push_back(transceiver);
1869 }
1870 return all_transceivers;
1871}
1872
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001873bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001874 MediaStreamTrackInterface* track,
1875 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001876 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001877 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001878 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001879 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001880 return false;
1881 }
1882
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001883 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001884 // The StatsCollector is used to tell if a track is valid because it may
1885 // remember tracks that the PeerConnection previously removed.
1886 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001887 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1888 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001889 return false;
1890 }
Steve Antonad182762018-09-05 20:22:40 +00001891 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1892 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 return true;
1894}
1895
hbos74e1a4f2016-09-15 23:33:01 -07001896void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001897 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001898 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001899 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001900 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001901 stats_collector_->GetStatsReport(callback);
1902}
1903
Henrik Boström1df1bf82018-03-20 13:24:20 +01001904void PeerConnection::GetStats(
1905 rtc::scoped_refptr<RtpSenderInterface> selector,
1906 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1907 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001908 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001909 RTC_DCHECK(callback);
1910 RTC_DCHECK(stats_collector_);
1911 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1912 if (selector) {
1913 for (const auto& proxy_transceiver : transceivers_) {
1914 for (const auto& proxy_sender :
1915 proxy_transceiver->internal()->senders()) {
1916 if (proxy_sender == selector) {
1917 internal_sender = proxy_sender->internal();
1918 break;
1919 }
1920 }
1921 if (internal_sender)
1922 break;
1923 }
1924 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001925 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001926 // belong to the PeerConnection (in Plan B, senders can be removed from the
1927 // PeerConnection). This means that "all the stats objects representing the
1928 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1929 // produces an empty stats report.
1930 stats_collector_->GetStatsReport(internal_sender, callback);
1931}
1932
1933void PeerConnection::GetStats(
1934 rtc::scoped_refptr<RtpReceiverInterface> selector,
1935 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1936 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001937 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001938 RTC_DCHECK(callback);
1939 RTC_DCHECK(stats_collector_);
1940 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1941 if (selector) {
1942 for (const auto& proxy_transceiver : transceivers_) {
1943 for (const auto& proxy_receiver :
1944 proxy_transceiver->internal()->receivers()) {
1945 if (proxy_receiver == selector) {
1946 internal_receiver = proxy_receiver->internal();
1947 break;
1948 }
1949 }
1950 if (internal_receiver)
1951 break;
1952 }
1953 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001954 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001955 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1956 // the PeerConnection). This means that "all the stats objects representing
1957 // the selector" is an empty set. Invoking GetStatsReport() with a null
1958 // selector produces an empty stats report.
1959 stats_collector_->GetStatsReport(internal_receiver, callback);
1960}
1961
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001962PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001963 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 return signaling_state_;
1965}
1966
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967PeerConnectionInterface::IceConnectionState
1968PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001969 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 return ice_connection_state_;
1971}
1972
Alex Loiko9289eda2018-11-23 16:18:59 +00001973PeerConnectionInterface::IceConnectionState
1974PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001975 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001976 return standardized_ice_connection_state_;
1977}
1978
Jonas Olsson635474e2018-10-18 15:58:17 +02001979PeerConnectionInterface::PeerConnectionState
1980PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001981 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001982 return connection_state_;
1983}
1984
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985PeerConnectionInterface::IceGatheringState
1986PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001987 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001988 return ice_gathering_state_;
1989}
1990
Yves Gerey665174f2018-06-19 15:03:05 +02001991rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 const std::string& label,
1993 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001994 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001995 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001996
deadbeefab9b2d12015-10-14 11:33:11 -07001997 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001998
kwibergd1fe2812016-04-27 06:47:29 -07001999 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002000 if (config) {
2001 internal_config.reset(new InternalDataChannelInit(*config));
2002 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002003 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002004 InternalCreateDataChannel(label, internal_config.get()));
2005 if (!channel.get()) {
2006 return nullptr;
2007 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002009 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2010 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002011 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002012 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002013 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002014 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 return DataChannelProxy::Create(signaling_thread(), channel.get());
2016}
2017
Henrik Boström79b69802019-07-18 11:16:56 +02002018void PeerConnection::RestartIce() {
2019 RTC_DCHECK_RUN_ON(signaling_thread());
2020 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2021 current_local_description_.get(), pending_local_description_.get());
2022 UpdateNegotiationNeeded();
2023}
2024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002026 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002027 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002028 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002029
nisse7ce109a2017-01-31 00:57:56 -08002030 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002031 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002032 return;
2033 }
deadbeefab9b2d12015-10-14 11:33:11 -07002034
Steve Anton8d3444d2017-10-20 15:30:51 -07002035 if (IsClosed()) {
2036 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002037 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002038 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002039 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002040 return;
2041 }
2042
Steve Anton25ca0ac2019-06-25 10:40:48 -07002043 // If a session error has occurred the PeerConnection is in a possibly
2044 // inconsistent state so fail right away.
2045 if (session_error() != SessionError::kNone) {
2046 std::string error_message = GetSessionErrorMsg();
2047 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2048 PostCreateSessionDescriptionFailure(
2049 observer,
2050 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2051 return;
2052 }
2053
zhihuang1c378ed2017-08-17 14:10:50 -07002054 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002055 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002056 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002057 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002058 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002059 return;
2060 }
2061
Steve Anton22da89f2018-01-25 13:58:07 -08002062 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2063 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2064 if (IsUnifiedPlan()) {
2065 RTCError error = HandleLegacyOfferOptions(options);
2066 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002067 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002068 return;
2069 }
2070 }
2071
zhihuang1c378ed2017-08-17 14:10:50 -07002072 cricket::MediaSessionOptions session_options;
2073 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002074 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002075}
2076
Steve Anton22da89f2018-01-25 13:58:07 -08002077RTCError PeerConnection::HandleLegacyOfferOptions(
2078 const RTCOfferAnswerOptions& options) {
2079 RTC_DCHECK(IsUnifiedPlan());
2080
2081 if (options.offer_to_receive_audio == 0) {
2082 RemoveRecvDirectionFromReceivingTransceiversOfType(
2083 cricket::MEDIA_TYPE_AUDIO);
2084 } else if (options.offer_to_receive_audio == 1) {
2085 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2086 } else if (options.offer_to_receive_audio > 1) {
2087 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2088 "offer_to_receive_audio > 1 is not supported.");
2089 }
2090
2091 if (options.offer_to_receive_video == 0) {
2092 RemoveRecvDirectionFromReceivingTransceiversOfType(
2093 cricket::MEDIA_TYPE_VIDEO);
2094 } else if (options.offer_to_receive_video == 1) {
2095 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2096 } else if (options.offer_to_receive_video > 1) {
2097 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2098 "offer_to_receive_video > 1 is not supported.");
2099 }
2100
2101 return RTCError::OK();
2102}
2103
2104void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2105 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002106 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002107 RtpTransceiverDirection new_direction =
2108 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2109 if (new_direction != transceiver->direction()) {
2110 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2111 << " transceiver (MID="
2112 << transceiver->mid().value_or("<not set>") << ") from "
2113 << RtpTransceiverDirectionToString(
2114 transceiver->direction())
2115 << " to "
2116 << RtpTransceiverDirectionToString(new_direction)
2117 << " since CreateOffer specified offer_to_receive=0";
2118 transceiver->internal()->set_direction(new_direction);
2119 }
Steve Anton22da89f2018-01-25 13:58:07 -08002120 }
2121}
2122
2123void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2124 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002125 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002126 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002127 RTC_LOG(LS_INFO)
2128 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2129 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002130 RtpTransceiverInit init;
2131 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002132 AddTransceiver(media_type, nullptr, init,
2133 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002134 }
2135}
2136
2137std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2138PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2139 std::vector<
2140 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2141 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002142 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002143 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002144 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2145 receiving_transceivers.push_back(transceiver);
2146 }
2147 }
2148 return receiving_transceivers;
2149}
2150
htaa2a49d92016-03-04 02:51:39 -08002151void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2152 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002153 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002154 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002155 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002156 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002157 return;
2158 }
2159
Steve Anton25ca0ac2019-06-25 10:40:48 -07002160 // If a session error has occurred the PeerConnection is in a possibly
2161 // inconsistent state so fail right away.
2162 if (session_error() != SessionError::kNone) {
2163 std::string error_message = GetSessionErrorMsg();
2164 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2165 PostCreateSessionDescriptionFailure(
2166 observer,
2167 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2168 return;
2169 }
2170
Steve Antondffead82018-02-06 10:31:29 -08002171 if (!(signaling_state_ == kHaveRemoteOffer ||
2172 signaling_state_ == kHaveLocalPrAnswer)) {
2173 std::string error =
2174 "PeerConnection cannot create an answer in a state other than "
2175 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002176 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002177 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002178 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002179 return;
2180 }
2181
Steve Antondffead82018-02-06 10:31:29 -08002182 // The remote description should be set if we're in the right state.
2183 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002184
Steve Anton22da89f2018-01-25 13:58:07 -08002185 if (IsUnifiedPlan()) {
2186 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2187 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2188 "supported with Unified Plan semantics. Use the "
2189 "RtpTransceiver API instead.";
2190 }
2191 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2192 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2193 "supported with Unified Plan semantics. Use the "
2194 "RtpTransceiver API instead.";
2195 }
2196 }
2197
htaa2a49d92016-03-04 02:51:39 -08002198 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002199 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002200
Steve Antond25da372017-11-06 14:50:29 -08002201 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202}
2203
2204void PeerConnection::SetLocalDescription(
2205 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002206 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002207 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002208 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002209
Steve Anton80dd7b52018-02-16 17:08:42 -08002210 // The SetLocalDescription contract is that we take ownership of the session
2211 // description regardless of the outcome, so wrap it in a unique_ptr right
2212 // away. Ideally, SetLocalDescription's signature will be changed to take the
2213 // description as a unique_ptr argument to formalize this agreement.
2214 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2215
nisse7ce109a2017-01-31 00:57:56 -08002216 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002217 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002218 return;
2219 }
Steve Anton8a006912017-12-04 15:25:56 -08002220
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002222 PostSetSessionDescriptionFailure(
2223 observer,
2224 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 return;
2226 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002227
Steve Anton80dd7b52018-02-16 17:08:42 -08002228 // If a session error has occurred the PeerConnection is in a possibly
2229 // inconsistent state so fail right away.
2230 if (session_error() != SessionError::kNone) {
2231 std::string error_message = GetSessionErrorMsg();
2232 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002233 PostSetSessionDescriptionFailure(
2234 observer,
2235 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002236 return;
2237 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002238
Steve Anton80dd7b52018-02-16 17:08:42 -08002239 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2240 if (!error.ok()) {
2241 std::string error_message = GetSetDescriptionErrorMessage(
2242 cricket::CS_LOCAL, desc->GetType(), error);
2243 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002244 PostSetSessionDescriptionFailure(
2245 observer,
2246 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002247 return;
2248 }
2249
2250 // Grab the description type before moving ownership to ApplyLocalDescription,
2251 // which may destroy it before returning.
2252 const SdpType type = desc->GetType();
2253
2254 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002255 // |desc| may be destroyed at this point.
2256
2257 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002258 // If ApplyLocalDescription fails, the PeerConnection could be in an
2259 // inconsistent state, so act conservatively here and set the session error
2260 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2261 SetSessionError(SessionError::kContent, error.message());
2262 std::string error_message =
2263 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2264 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002265 PostSetSessionDescriptionFailure(
2266 observer,
2267 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002268 return;
2269 }
Steve Anton8a006912017-12-04 15:25:56 -08002270 RTC_DCHECK(local_description());
2271
2272 PostSetSessionDescriptionSuccess(observer);
2273
Steve Antonad182762018-09-05 20:22:40 +00002274 // MaybeStartGathering needs to be called after posting
2275 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2276 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002277 transport_controller_->MaybeStartGathering();
2278
Steve Antona3a92c22017-12-07 10:27:41 -08002279 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002280 // TODO(deadbeef): We already had to hop to the network thread for
2281 // MaybeStartGathering...
2282 network_thread()->Invoke<void>(
2283 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2284 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002285 // Make UMA notes about what was agreed to.
2286 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002287 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002288
2289 if (IsUnifiedPlan()) {
2290 bool was_negotiation_needed = is_negotiation_needed_;
2291 UpdateNegotiationNeeded();
2292 if (signaling_state() == kStable && was_negotiation_needed &&
2293 is_negotiation_needed_) {
2294 Observer()->OnRenegotiationNeeded();
2295 }
2296 }
2297
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002298 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002299}
2300
2301RTCError PeerConnection::ApplyLocalDescription(
2302 std::unique_ptr<SessionDescriptionInterface> desc) {
2303 RTC_DCHECK_RUN_ON(signaling_thread());
2304 RTC_DCHECK(desc);
2305
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306 // Update stats here so that we have the most recent stats for tracks and
2307 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002308 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002309
Steve Antondcc3c022017-12-22 16:02:54 -08002310 // Take a reference to the old local description since it's used below to
2311 // compare against the new local description. When setting the new local
2312 // description, grab ownership of the replaced session description in case it
2313 // is the same as |old_local_description|, to keep it alive for the duration
2314 // of the method.
2315 const SessionDescriptionInterface* old_local_description =
2316 local_description();
2317 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002318 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002319 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002320 replaced_local_description = pending_local_description_
2321 ? std::move(pending_local_description_)
2322 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002323 current_local_description_ = std::move(desc);
2324 pending_local_description_ = nullptr;
2325 current_remote_description_ = std::move(pending_remote_description_);
2326 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002327 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002328 pending_local_description_ = std::move(desc);
2329 }
2330 // The session description to apply now must be accessed by
2331 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002332 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002333
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002334 // Report statistics about any use of simulcast.
2335 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2336 *local_description()->description());
2337
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002338 if (!is_caller_) {
2339 if (remote_description()) {
2340 // Remote description was applied first, so this PC is the callee.
2341 is_caller_ = false;
2342 } else {
2343 // Local description is applied first, so this PC is the caller.
2344 is_caller_ = true;
2345 }
2346 }
2347
Zhi Huange830e682018-03-30 10:48:35 -07002348 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2349 if (!error.ok()) {
2350 return error;
2351 }
2352
Steve Antondcc3c022017-12-22 16:02:54 -08002353 if (IsUnifiedPlan()) {
2354 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002355 cricket::CS_LOCAL, *local_description(), old_local_description,
2356 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002357 if (!error.ok()) {
2358 return error;
2359 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002360 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2361 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002362 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002363 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2364 // Note that code paths that don't set MID won't be able to use
2365 // information about DTLS transports.
2366 if (transceiver->mid()) {
2367 auto dtls_transport =
2368 LookupDtlsTransportByMidInternal(*transceiver->mid());
2369 transceiver->internal()->sender_internal()->set_transport(
2370 dtls_transport);
2371 transceiver->internal()->receiver_internal()->set_transport(
2372 dtls_transport);
2373 }
2374
Steve Antondcc3c022017-12-22 16:02:54 -08002375 const ContentInfo* content =
2376 FindMediaSectionForTransceiver(transceiver, local_description());
2377 if (!content) {
2378 continue;
2379 }
2380 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002381 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2382 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002383 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002384 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2385 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2386 // "recvonly", process the removal of a remote track for the media
2387 // description, given transceiver, removeList, and muteTracks.
2388 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2389 (transceiver->internal()->fired_direction() &&
2390 RtpTransceiverDirectionHasRecv(
2391 *transceiver->internal()->fired_direction()))) {
2392 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2393 &removed_streams);
2394 }
2395 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2396 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002397 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002398 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002399 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002400 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002401 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002402 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002403 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002404 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002405 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002406 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002407 }
2408 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002409 // Media channels will be created only when offer is set. These may use new
2410 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002411 if (type == SdpType::kOffer) {
2412 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2413 // description is applied. Restore back to old description.
2414 RTCError error = CreateChannels(*local_description()->description());
2415 if (!error.ok()) {
2416 return error;
2417 }
2418 }
Steve Antondcc3c022017-12-22 16:02:54 -08002419 // Remove unused channels if MediaContentDescription is rejected.
2420 RemoveUnusedChannels(local_description()->description());
2421 }
Steve Anton8a006912017-12-04 15:25:56 -08002422
Zhi Huange830e682018-03-30 10:48:35 -07002423 error = UpdateSessionState(type, cricket::CS_LOCAL,
2424 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002425 if (!error.ok()) {
2426 return error;
2427 }
Steve Antondcc3c022017-12-22 16:02:54 -08002428
Steve Anton8a006912017-12-04 15:25:56 -08002429 if (remote_description()) {
2430 // Now that we have a local description, we can push down remote candidates.
2431 UseCandidatesInSessionDescription(remote_description());
2432 }
2433
2434 pending_ice_restarts_.clear();
2435 if (session_error() != SessionError::kNone) {
2436 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2437 }
2438
deadbeefab9b2d12015-10-14 11:33:11 -07002439 // If setting the description decided our SSL role, allocate any necessary
2440 // SCTP sids.
2441 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002442 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002443 AllocateSctpSids(role);
2444 }
2445
Steve Antond3679212018-01-17 17:41:02 -08002446 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002447 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002448 const ContentInfo* content =
2449 FindMediaSectionForTransceiver(transceiver, local_description());
2450 if (!content) {
2451 continue;
2452 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002453 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2454 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002455 // 0 is a special value meaning "this sender has no associated send
2456 // stream". Need to call this so the sender won't attempt to configure
2457 // a no longer existing stream and run into DCHECKs in the lower
2458 // layers.
2459 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002460 } else {
2461 // Get the StreamParams from the channel which could generate SSRCs.
2462 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002463 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002464 streams[0].stream_ids());
2465 transceiver->internal()->sender_internal()->SetSsrc(
2466 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002467 }
2468 }
2469 } else {
2470 // Plan B semantics.
2471
Steve Antondcc3c022017-12-22 16:02:54 -08002472 // Update state and SSRC of local MediaStreams and DataChannels based on the
2473 // local session description.
2474 const cricket::ContentInfo* audio_content =
2475 GetFirstAudioContent(local_description()->description());
2476 if (audio_content) {
2477 if (audio_content->rejected) {
2478 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2479 } else {
2480 const cricket::AudioContentDescription* audio_desc =
2481 audio_content->media_description()->as_audio();
2482 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2483 }
deadbeeffaac4972015-11-12 15:33:07 -08002484 }
deadbeefab9b2d12015-10-14 11:33:11 -07002485
Steve Antondcc3c022017-12-22 16:02:54 -08002486 const cricket::ContentInfo* video_content =
2487 GetFirstVideoContent(local_description()->description());
2488 if (video_content) {
2489 if (video_content->rejected) {
2490 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2491 } else {
2492 const cricket::VideoContentDescription* video_desc =
2493 video_content->media_description()->as_video();
2494 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2495 }
deadbeeffaac4972015-11-12 15:33:07 -08002496 }
deadbeefab9b2d12015-10-14 11:33:11 -07002497 }
2498
2499 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002500 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002501 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002502 const cricket::RtpDataContentDescription* rtp_data_desc =
2503 data_content->media_description()->as_rtp_data();
2504 // rtp_data_desc will be null if this is an SCTP description.
2505 if (rtp_data_desc) {
2506 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002507 }
2508 }
2509
Henrik Boström79b69802019-07-18 11:16:56 +02002510 if (type == SdpType::kAnswer &&
2511 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2512 *current_local_description_)) {
2513 local_ice_credentials_to_replace_->ClearIceCredentials();
2514 }
2515
Steve Anton8a006912017-12-04 15:25:56 -08002516 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002517}
2518
Steve Anton06817cd2018-12-18 15:55:30 -08002519// The SDP parser used to populate these values by default for the 'content
2520// name' if an a=mid line was absent.
2521static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2522 switch (media_type) {
2523 case cricket::MEDIA_TYPE_AUDIO:
2524 return cricket::CN_AUDIO;
2525 case cricket::MEDIA_TYPE_VIDEO:
2526 return cricket::CN_VIDEO;
2527 case cricket::MEDIA_TYPE_DATA:
2528 return cricket::CN_DATA;
2529 }
2530 RTC_NOTREACHED();
2531 return "";
2532}
2533
2534void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002535 cricket::SessionDescription* new_remote_description) {
2536 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002537 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002538 const cricket::ContentInfos& local_contents =
2539 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002540 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002541 const cricket::ContentInfos& remote_contents =
2542 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002543 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002544 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2545 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002546 if (!content.name.empty()) {
2547 continue;
2548 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002549 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002550 absl::string_view source_explanation;
2551 if (IsUnifiedPlan()) {
2552 if (i < local_contents.size()) {
2553 new_mid = local_contents[i].name;
2554 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002555 } else if (i < remote_contents.size()) {
2556 new_mid = remote_contents[i].name;
2557 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002558 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002559 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002560 source_explanation = "generated just now";
2561 }
2562 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002563 new_mid = std::string(
2564 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002565 source_explanation = "to match pre-existing behavior";
2566 }
Steve Antond7180cc2019-02-07 10:44:53 -08002567 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002568 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002569 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002570 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2571 << " is missing an a=mid line. Filling in the value '"
2572 << new_mid << "' " << source_explanation << ".";
2573 }
2574}
2575
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002577 SetSessionDescriptionObserver* observer,
2578 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002579 SetRemoteDescription(
2580 std::unique_ptr<SessionDescriptionInterface>(desc),
2581 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2582 new SetRemoteDescriptionObserverAdapter(this, observer)));
2583}
2584
2585void PeerConnection::SetRemoteDescription(
2586 std::unique_ptr<SessionDescriptionInterface> desc,
2587 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002588 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002589 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002590
nisse7ce109a2017-01-31 00:57:56 -08002591 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002592 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 return;
2594 }
Steve Anton8a006912017-12-04 15:25:56 -08002595
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002596 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002597 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002598 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002599 return;
2600 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002601
Steve Anton80dd7b52018-02-16 17:08:42 -08002602 // If a session error has occurred the PeerConnection is in a possibly
2603 // inconsistent state so fail right away.
2604 if (session_error() != SessionError::kNone) {
2605 std::string error_message = GetSessionErrorMsg();
2606 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2607 observer->OnSetRemoteDescriptionComplete(
2608 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2609 return;
2610 }
Steve Anton71439a62018-02-15 11:53:06 -08002611
Steve Antonba42e992018-04-09 14:10:01 -07002612 if (desc->GetType() == SdpType::kOffer) {
2613 // Report to UMA the format of the received offer.
2614 ReportSdpFormatReceived(*desc);
2615 }
2616
Steve Anton06817cd2018-12-18 15:55:30 -08002617 // Handle remote descriptions missing a=mid lines for interop with legacy end
2618 // points.
2619 FillInMissingRemoteMids(desc->description());
2620
Steve Anton80dd7b52018-02-16 17:08:42 -08002621 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002622 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002623 std::string error_message = GetSetDescriptionErrorMessage(
2624 cricket::CS_REMOTE, desc->GetType(), error);
2625 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002626 observer->OnSetRemoteDescriptionComplete(
2627 RTCError(error.type(), std::move(error_message)));
2628 return;
2629 }
Steve Anton71439a62018-02-15 11:53:06 -08002630
Steve Anton80dd7b52018-02-16 17:08:42 -08002631 // Grab the description type before moving ownership to
2632 // ApplyRemoteDescription, which may destroy it before returning.
2633 const SdpType type = desc->GetType();
2634
2635 error = ApplyRemoteDescription(std::move(desc));
2636 // |desc| may be destroyed at this point.
2637
2638 if (!error.ok()) {
2639 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2640 // inconsistent state, so act conservatively here and set the session error
2641 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2642 SetSessionError(SessionError::kContent, error.message());
2643 std::string error_message =
2644 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2645 RTC_LOG(LS_ERROR) << error_message;
2646 observer->OnSetRemoteDescriptionComplete(
2647 RTCError(error.type(), std::move(error_message)));
2648 return;
2649 }
2650 RTC_DCHECK(remote_description());
2651
2652 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002653 // TODO(deadbeef): We already had to hop to the network thread for
2654 // MaybeStartGathering...
2655 network_thread()->Invoke<void>(
2656 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2657 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002658 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002659 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002660 }
2661
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002662 if (IsUnifiedPlan()) {
2663 bool was_negotiation_needed = is_negotiation_needed_;
2664 UpdateNegotiationNeeded();
2665 if (signaling_state() == kStable && was_negotiation_needed &&
2666 is_negotiation_needed_) {
2667 Observer()->OnRenegotiationNeeded();
2668 }
2669 }
2670
Steve Anton8a006912017-12-04 15:25:56 -08002671 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002672 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002673}
2674
2675RTCError PeerConnection::ApplyRemoteDescription(
2676 std::unique_ptr<SessionDescriptionInterface> desc) {
2677 RTC_DCHECK_RUN_ON(signaling_thread());
2678 RTC_DCHECK(desc);
2679
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002680 // Update stats here so that we have the most recent stats for tracks and
2681 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002682 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002683
Steve Antondcc3c022017-12-22 16:02:54 -08002684 // Take a reference to the old remote description since it's used below to
2685 // compare against the new remote description. When setting the new remote
2686 // description, grab ownership of the replaced session description in case it
2687 // is the same as |old_remote_description|, to keep it alive for the duration
2688 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002689 const SessionDescriptionInterface* old_remote_description =
2690 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002691 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002692 SdpType type = desc->GetType();
2693 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002694 replaced_remote_description = pending_remote_description_
2695 ? std::move(pending_remote_description_)
2696 : std::move(current_remote_description_);
2697 current_remote_description_ = std::move(desc);
2698 pending_remote_description_ = nullptr;
2699 current_local_description_ = std::move(pending_local_description_);
2700 } else {
2701 replaced_remote_description = std::move(pending_remote_description_);
2702 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002703 }
Steve Anton8a006912017-12-04 15:25:56 -08002704 // The session description to apply now must be accessed by
2705 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002706 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002707
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002708 // Report statistics about any use of simulcast.
2709 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2710 *remote_description()->description());
2711
Zhi Huange830e682018-03-30 10:48:35 -07002712 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2713 if (!error.ok()) {
2714 return error;
2715 }
Steve Anton8a006912017-12-04 15:25:56 -08002716 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002717 if (IsUnifiedPlan()) {
2718 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002719 cricket::CS_REMOTE, *remote_description(), local_description(),
2720 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002721 if (!error.ok()) {
2722 return error;
2723 }
Steve Antondcc3c022017-12-22 16:02:54 -08002724 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002725 // Media channels will be created only when offer is set. These may use new
2726 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002727 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002728 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002729 // description is applied. Restore back to old description.
2730 RTCError error = CreateChannels(*remote_description()->description());
2731 if (!error.ok()) {
2732 return error;
2733 }
2734 }
Steve Antondcc3c022017-12-22 16:02:54 -08002735 // Remove unused channels if MediaContentDescription is rejected.
2736 RemoveUnusedChannels(remote_description()->description());
2737 }
Steve Anton8a006912017-12-04 15:25:56 -08002738
Zhi Huange830e682018-03-30 10:48:35 -07002739 // NOTE: Candidates allocation will be initiated only when
2740 // SetLocalDescription is called.
2741 error = UpdateSessionState(type, cricket::CS_REMOTE,
2742 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002743 if (!error.ok()) {
2744 return error;
2745 }
2746
2747 if (local_description() &&
2748 !UseCandidatesInSessionDescription(remote_description())) {
2749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2750 }
2751
2752 if (old_remote_description) {
2753 for (const cricket::ContentInfo& content :
2754 old_remote_description->description()->contents()) {
2755 // Check if this new SessionDescription contains new ICE ufrag and
2756 // password that indicates the remote peer requests an ICE restart.
2757 // TODO(deadbeef): When we start storing both the current and pending
2758 // remote description, this should reset pending_ice_restarts and compare
2759 // against the current description.
2760 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2761 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002762 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002763 pending_ice_restarts_.insert(content.name);
2764 }
2765 } else {
2766 // We retain all received candidates only if ICE is not restarted.
2767 // When ICE is restarted, all previous candidates belong to an old
2768 // generation and should not be kept.
2769 // TODO(deadbeef): This goes against the W3C spec which says the remote
2770 // description should only contain candidates from the last set remote
2771 // description plus any candidates added since then. We should remove
2772 // this once we're sure it won't break anything.
2773 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2774 old_remote_description, content.name, mutable_remote_description());
2775 }
2776 }
2777 }
2778
2779 if (session_error() != SessionError::kNone) {
2780 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2781 }
2782
2783 // Set the the ICE connection state to connecting since the connection may
2784 // become writable with peer reflexive candidates before any remote candidate
2785 // is signaled.
2786 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2787 // is to have a new signal the indicates a change in checking state from the
2788 // transport and expose a new checking() member from transport that can be
2789 // read to determine the current checking state. The existing SignalConnecting
2790 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002791 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002792 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002793 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2794 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2795 }
2796
deadbeefab9b2d12015-10-14 11:33:11 -07002797 // If setting the description decided our SSL role, allocate any necessary
2798 // SCTP sids.
2799 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002800 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002801 AllocateSctpSids(role);
2802 }
2803
Steve Antondcc3c022017-12-22 16:02:54 -08002804 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002805 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002806 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002807 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002808 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002809 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002810 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002811 const ContentInfo* content =
2812 FindMediaSectionForTransceiver(transceiver, remote_description());
2813 if (!content) {
2814 continue;
2815 }
2816 const MediaContentDescription* media_desc = content->media_description();
2817 RtpTransceiverDirection local_direction =
2818 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002819 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2820 // RTCSessionDescription: Set the associated remote streams given
2821 // transceiver.[[Receiver]], msids, addList, and removeList".
2822 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2823 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2824 std::vector<std::string> stream_ids;
2825 if (!media_desc->streams().empty()) {
2826 // The remote description has signaled the stream IDs.
2827 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002828 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002829 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2830 << " (" << GetStreamIdsString(stream_ids) << ").";
2831 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2832 stream_ids, &added_streams,
2833 &removed_streams);
2834 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2835 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2836 // and transceiver's current direction is neither sendrecv nor recvonly,
2837 // process the addition of a remote track for the media description.
2838 if (!transceiver->fired_direction() ||
2839 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2840 RTC_LOG(LS_INFO)
2841 << "Processing the addition of a remote track for MID="
2842 << content->name << ".";
2843 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002844 }
Steve Antondcc3c022017-12-22 16:02:54 -08002845 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002846 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002847 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2848 // removal of a remote track for the media description, given transceiver,
2849 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002850 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002851 (transceiver->fired_direction() &&
2852 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2853 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2854 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002855 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002856 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002857 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002858 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002859 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002860 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002861 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002862 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002863 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002864 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2865 if (transceiver->mid()) {
2866 auto dtls_transport =
2867 LookupDtlsTransportByMidInternal(*transceiver->mid());
2868 transceiver->internal()->sender_internal()->set_transport(
2869 dtls_transport);
2870 transceiver->internal()->receiver_internal()->set_transport(
2871 dtls_transport);
2872 }
Steve Antondcc3c022017-12-22 16:02:54 -08002873 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002874 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002875 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002876 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002877 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2878 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002879 transceiver->Stop();
2880 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002881 if (!content->rejected &&
2882 RtpTransceiverDirectionHasRecv(local_direction)) {
2883 // Set ssrc to 0 in the case of an unsignalled ssrc.
2884 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002885 if (!media_desc->streams().empty() &&
2886 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002887 ssrc = media_desc->streams()[0].first_ssrc();
2888 }
2889 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002890 }
Steve Antondcc3c022017-12-22 16:02:54 -08002891 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002892 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002893 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002894 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002895 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002896 observer->OnTrack(transceiver);
2897 observer->OnAddTrack(transceiver->receiver(),
2898 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002899 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002900 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002901 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002902 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002903 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002904 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002905 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002906 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002907 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002908 }
Steve Antondcc3c022017-12-22 16:02:54 -08002909 }
2910
Henrik Boströmfdb92012017-11-09 19:55:44 +01002911 const cricket::ContentInfo* audio_content =
2912 GetFirstAudioContent(remote_description()->description());
2913 const cricket::ContentInfo* video_content =
2914 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002915 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002916 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002917 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002918 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002919 const cricket::RtpDataContentDescription* rtp_data_desc =
2920 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002921
2922 // Check if the descriptions include streams, just in case the peer supports
2923 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002924 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002925 (audio_desc && !audio_desc->streams().empty()) ||
2926 (video_desc && !video_desc->streams().empty())) {
2927 remote_peer_supports_msid_ = true;
2928 }
deadbeefab9b2d12015-10-14 11:33:11 -07002929
2930 // We wait to signal new streams until we finish processing the description,
2931 // since only at that point will new streams have all their tracks.
2932 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2933
Steve Antondcc3c022017-12-22 16:02:54 -08002934 if (!IsUnifiedPlan()) {
2935 // TODO(steveanton): When removing RTP senders/receivers in response to a
2936 // rejected media section, there is some cleanup logic that expects the
2937 // voice/ video channel to still be set. But in this method the voice/video
2938 // channel would have been destroyed by the SetRemoteDescription caller
2939 // above so the cleanup that relies on them fails to run. The RemoveSenders
2940 // calls should be moved to right before the DestroyChannel calls to fix
2941 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002942
Steve Antondcc3c022017-12-22 16:02:54 -08002943 // Find all audio rtp streams and create corresponding remote AudioTracks
2944 // and MediaStreams.
2945 if (audio_content) {
2946 if (audio_content->rejected) {
2947 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2948 } else {
2949 bool default_audio_track_needed =
2950 !remote_peer_supports_msid_ &&
2951 RtpTransceiverDirectionHasSend(audio_desc->direction());
2952 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2953 default_audio_track_needed, audio_desc->type(),
2954 new_streams);
2955 }
deadbeeffaac4972015-11-12 15:33:07 -08002956 }
deadbeefab9b2d12015-10-14 11:33:11 -07002957
Steve Antondcc3c022017-12-22 16:02:54 -08002958 // Find all video rtp streams and create corresponding remote VideoTracks
2959 // and MediaStreams.
2960 if (video_content) {
2961 if (video_content->rejected) {
2962 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2963 } else {
2964 bool default_video_track_needed =
2965 !remote_peer_supports_msid_ &&
2966 RtpTransceiverDirectionHasSend(video_desc->direction());
2967 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2968 default_video_track_needed, video_desc->type(),
2969 new_streams);
2970 }
deadbeeffaac4972015-11-12 15:33:07 -08002971 }
deadbeefab9b2d12015-10-14 11:33:11 -07002972
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002973 // If this is an RTP data transport, update the DataChannels with the
2974 // information from the remote peer.
2975 if (rtp_data_desc) {
2976 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002977 }
deadbeefab9b2d12015-10-14 11:33:11 -07002978
Steve Antondcc3c022017-12-22 16:02:54 -08002979 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002980 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002981 for (size_t i = 0; i < new_streams->count(); ++i) {
2982 MediaStreamInterface* new_stream = new_streams->at(i);
2983 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002984 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002985 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2986 }
deadbeefab9b2d12015-10-14 11:33:11 -07002987
Steve Antondcc3c022017-12-22 16:02:54 -08002988 UpdateEndedRemoteMediaStreams();
2989 }
deadbeefab9b2d12015-10-14 11:33:11 -07002990
Henrik Boström79b69802019-07-18 11:16:56 +02002991 if (type == SdpType::kAnswer &&
2992 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2993 *current_local_description_)) {
2994 local_ice_credentials_to_replace_->ClearIceCredentials();
2995 }
2996
Steve Anton8a006912017-12-04 15:25:56 -08002997 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002998}
2999
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003000void PeerConnection::SetAssociatedRemoteStreams(
3001 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3002 const std::vector<std::string>& stream_ids,
3003 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3004 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3005 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3006 for (const std::string& stream_id : stream_ids) {
3007 rtc::scoped_refptr<MediaStreamInterface> stream =
3008 remote_streams_->find(stream_id);
3009 if (!stream) {
3010 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3011 MediaStream::Create(stream_id));
3012 remote_streams_->AddStream(stream);
3013 added_streams->push_back(stream);
3014 }
3015 media_streams.push_back(stream);
3016 }
3017 // Special case: "a=msid" missing, use random stream ID.
3018 if (media_streams.empty() &&
3019 !(remote_description()->description()->msid_signaling() &
3020 cricket::kMsidSignalingMediaSection)) {
3021 if (!missing_msid_default_stream_) {
3022 missing_msid_default_stream_ = MediaStreamProxy::Create(
3023 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3024 added_streams->push_back(missing_msid_default_stream_);
3025 }
3026 media_streams.push_back(missing_msid_default_stream_);
3027 }
3028 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3029 receiver->streams();
3030 // SetStreams() will add/remove the receiver's track to/from the streams. This
3031 // differs from the spec - the spec uses an "addList" and "removeList" to
3032 // update the stream-track relationships in a later step. We do this earlier,
3033 // changing the order of things, but the end-result is the same.
3034 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3035 // instead. https://crbug.com/webrtc/9480
3036 receiver->SetStreams(media_streams);
3037 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3038}
3039
Steve Anton0f5400a2018-07-17 14:25:36 -07003040void PeerConnection::ProcessRemovalOfRemoteTrack(
3041 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3042 transceiver,
3043 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3044 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3045 RTC_DCHECK(transceiver->mid());
3046 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3047 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003048 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003049 transceiver->internal()->receiver_internal()->streams();
3050 // This will remove the remote track from the streams.
3051 transceiver->internal()->receiver_internal()->set_stream_ids({});
3052 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003053 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3054}
3055
3056void PeerConnection::RemoveRemoteStreamsIfEmpty(
3057 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3058 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3059 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3060 // streams, see if the stream was removed by checking if this was the last
3061 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003062 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003063 if (remote_stream->GetAudioTracks().empty() &&
3064 remote_stream->GetVideoTracks().empty()) {
3065 remote_streams_->RemoveStream(remote_stream);
3066 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003067 }
3068 }
3069}
3070
Steve Antondcc3c022017-12-22 16:02:54 -08003071RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3072 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003073 const SessionDescriptionInterface& new_session,
3074 const SessionDescriptionInterface* old_local_description,
3075 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003076 RTC_DCHECK(IsUnifiedPlan());
3077
Steve Anton7464fca2018-01-19 11:10:37 -08003078 const cricket::ContentGroup* bundle_group = nullptr;
3079 if (new_session.GetType() == SdpType::kOffer) {
3080 auto bundle_group_or_error =
3081 GetEarlyBundleGroup(*new_session.description());
3082 if (!bundle_group_or_error.ok()) {
3083 return bundle_group_or_error.MoveError();
3084 }
3085 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003086 }
Steve Antondcc3c022017-12-22 16:02:54 -08003087
Steve Antondcc3c022017-12-22 16:02:54 -08003088 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003089 for (size_t i = 0; i < new_contents.size(); ++i) {
3090 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003091 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003092 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003093 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3094 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003095 const cricket::ContentInfo* old_local_content = nullptr;
3096 if (old_local_description &&
3097 i < old_local_description->description()->contents().size()) {
3098 old_local_content =
3099 &old_local_description->description()->contents()[i];
3100 }
3101 const cricket::ContentInfo* old_remote_content = nullptr;
3102 if (old_remote_description &&
3103 i < old_remote_description->description()->contents().size()) {
3104 old_remote_content =
3105 &old_remote_description->description()->contents()[i];
3106 }
Steve Antondcc3c022017-12-22 16:02:54 -08003107 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003108 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3109 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003110 if (!transceiver_or_error.ok()) {
3111 return transceiver_or_error.MoveError();
3112 }
3113 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003114 RTCError error =
3115 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3116 if (!error.ok()) {
3117 return error;
3118 }
3119 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003120 if (GetDataMid() && new_content.name != *GetDataMid()) {
3121 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003122 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3123 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003124 continue;
3125 }
3126 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3127 if (!error.ok()) {
3128 return error;
3129 }
Steve Antondcc3c022017-12-22 16:02:54 -08003130 } else {
3131 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3132 "Unknown section type.");
3133 }
3134 }
3135
3136 return RTCError::OK();
3137}
3138
3139RTCError PeerConnection::UpdateTransceiverChannel(
3140 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3141 transceiver,
3142 const cricket::ContentInfo& content,
3143 const cricket::ContentGroup* bundle_group) {
3144 RTC_DCHECK(IsUnifiedPlan());
3145 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003146 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003147 if (content.rejected) {
3148 if (channel) {
3149 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003150 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003151 }
3152 } else {
3153 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003154 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003155 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003156 } else {
Steve Anton69470252018-02-09 11:43:08 -08003157 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003158 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003159 }
3160 if (!channel) {
3161 LOG_AND_RETURN_ERROR(
3162 RTCErrorType::INTERNAL_ERROR,
3163 "Failed to create channel for mid=" + content.name);
3164 }
3165 transceiver->internal()->SetChannel(channel);
3166 }
3167 }
3168 return RTCError::OK();
3169}
3170
Steve Antonfa2260d2017-12-28 16:38:23 -08003171RTCError PeerConnection::UpdateDataChannel(
3172 cricket::ContentSource source,
3173 const cricket::ContentInfo& content,
3174 const cricket::ContentGroup* bundle_group) {
3175 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003176 // If data channels are disabled, ignore this media section. CreateAnswer
3177 // will take care of rejecting it.
3178 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003179 }
3180 if (content.rejected) {
3181 DestroyDataChannel();
3182 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003183 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003184 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003185 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3186 "Failed to create data channel.");
3187 }
3188 }
3189 if (source == cricket::CS_REMOTE) {
3190 const MediaContentDescription* data_desc = content.media_description();
3191 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3192 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3193 }
3194 }
3195 }
3196 return RTCError::OK();
3197}
3198
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003199// This method will extract any send encodings that were sent by the remote
3200// connection. This is currently only relevant for Simulcast scenario (where
3201// the number of layers may be communicated by the server).
3202static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3203 const MediaContentDescription& desc) {
3204 if (!desc.HasSimulcast()) {
3205 return {};
3206 }
3207 std::vector<RtpEncodingParameters> result;
3208 const SimulcastDescription& simulcast = desc.simulcast_description();
3209
3210 // This is a remote description, the parameters we are after should appear
3211 // as receive streams.
3212 for (const auto& alternatives : simulcast.receive_layers()) {
3213 RTC_DCHECK(!alternatives.empty());
3214 // There is currently no way to specify or choose from alternatives.
3215 // We will always use the first alternative, which is the most preferred.
3216 const SimulcastLayer& layer = alternatives[0];
3217 RtpEncodingParameters parameters;
3218 parameters.rid = layer.rid;
3219 parameters.active = !layer.is_paused;
3220 result.push_back(parameters);
3221 }
3222
3223 return result;
3224}
3225
3226static RTCError UpdateSimulcastLayerStatusInSender(
3227 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003228 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003229 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003230 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003231 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003232
3233 // The simulcast envelope cannot be changed, only the status of the streams.
3234 // So we will iterate over the send encodings rather than the layers.
3235 for (RtpEncodingParameters& encoding : parameters.encodings) {
3236 auto iter = std::find_if(layers.begin(), layers.end(),
3237 [&encoding](const SimulcastLayer& layer) {
3238 return layer.rid == encoding.rid;
3239 });
3240 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003241 if (iter == layers.end()) {
3242 disabled_layers.push_back(encoding.rid);
3243 continue;
3244 }
3245
3246 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003247 }
3248
Amit Hilbuch619b2942019-02-26 15:55:19 -08003249 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003250 if (result.ok()) {
3251 result = sender->DisableEncodingLayers(disabled_layers);
3252 }
3253
3254 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003255}
3256
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003257static bool SimulcastIsRejected(
3258 const ContentInfo* local_content,
3259 const MediaContentDescription& answer_media_desc) {
3260 bool simulcast_offered = local_content &&
3261 local_content->media_description() &&
3262 local_content->media_description()->HasSimulcast();
3263 bool simulcast_answered = answer_media_desc.HasSimulcast();
3264 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3265 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3266 return simulcast_offered && (!simulcast_answered || !rids_supported);
3267}
3268
Amit Hilbuch2297d332019-02-19 12:49:22 -08003269static RTCError DisableSimulcastInSender(
3270 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003271 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003272 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003273 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003274 return RTCError::OK();
3275 }
3276
Amit Hilbuch2297d332019-02-19 12:49:22 -08003277 std::vector<std::string> disabled_layers;
3278 std::transform(
3279 parameters.encodings.begin() + 1, parameters.encodings.end(),
3280 std::back_inserter(disabled_layers),
3281 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3282 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003283}
3284
Steve Antondcc3c022017-12-22 16:02:54 -08003285RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3286PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003287 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003288 size_t mline_index,
3289 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003290 const ContentInfo* old_local_content,
3291 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003292 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003293 // If this is an offer then the m= section might be recycled. If the m=
3294 // section is being recycled (defined as: rejected in the current local or
3295 // remote description and not rejected in new description), dissociate the
3296 // currently associated RtpTransceiver by setting its mid property to null,
3297 // and discard the mapping between the transceiver and its m= section index.
3298 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3299 old_remote_content)) {
3300 // We want to dissociate the transceiver that has the rejected mid.
3301 const std::string& old_mid =
3302 (old_local_content && old_local_content->rejected)
3303 ? old_local_content->name
3304 : old_remote_content->name;
3305 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003306 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003307 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3308 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003309 old_transceiver->internal()->set_mid(absl::nullopt);
3310 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003311 }
3312 }
3313 const MediaContentDescription* media_desc = content.media_description();
3314 auto transceiver = GetAssociatedTransceiver(content.name);
3315 if (source == cricket::CS_LOCAL) {
3316 // Find the RtpTransceiver that corresponds to this m= section, using the
3317 // mapping between transceivers and m= section indices established when
3318 // creating the offer.
3319 if (!transceiver) {
3320 transceiver = GetTransceiverByMLineIndex(mline_index);
3321 }
3322 if (!transceiver) {
3323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3324 "Unknown transceiver");
3325 }
3326 } else {
3327 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3328 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3329 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003330 // When simulcast is requested, a transceiver cannot be associated because
3331 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003332 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003333 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3334 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003335 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3336 }
3337 // If no RtpTransceiver was found in the previous step, create one with a
3338 // recvonly direction.
3339 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003340 RTC_LOG(LS_INFO) << "Adding "
3341 << cricket::MediaTypeToString(media_desc->type())
3342 << " transceiver for MID=" << content.name
3343 << " at i=" << mline_index
3344 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003345 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003346 std::vector<RtpEncodingParameters> send_encodings =
3347 GetSendEncodingsFromRemoteDescription(*media_desc);
3348 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3349 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003350 std::string receiver_id;
3351 if (!media_desc->streams().empty()) {
3352 receiver_id = media_desc->streams()[0].id;
3353 } else {
3354 receiver_id = rtc::CreateRandomUuid();
3355 }
3356 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003357 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003358 transceiver->internal()->set_direction(
3359 RtpTransceiverDirection::kRecvOnly);
3360 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003361
3362 // Check if the offer indicated simulcast but the answer rejected it.
3363 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003364 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003365 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003366 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003367 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003368 if (!error.ok()) {
3369 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3370 return std::move(error);
3371 }
3372 }
Steve Antondcc3c022017-12-22 16:02:54 -08003373 }
3374 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003375 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003376 LOG_AND_RETURN_ERROR(
3377 RTCErrorType::INVALID_PARAMETER,
3378 "Transceiver type does not match media description type.");
3379 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003380 if (media_desc->HasSimulcast()) {
3381 std::vector<SimulcastLayer> layers =
3382 source == cricket::CS_LOCAL
3383 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3384 : media_desc->simulcast_description()
3385 .receive_layers()
3386 .GetAllLayers();
3387 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003388 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003389 if (!error.ok()) {
3390 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3391 return std::move(error);
3392 }
3393 }
Steve Antondcc3c022017-12-22 16:02:54 -08003394 // Associate the found or created RtpTransceiver with the m= section by
3395 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3396 // section, and establish a mapping between the transceiver and the index of
3397 // the m= section.
3398 transceiver->internal()->set_mid(content.name);
3399 transceiver->internal()->set_mline_index(mline_index);
3400 return std::move(transceiver);
3401}
3402
3403rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3404PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3405 RTC_DCHECK(IsUnifiedPlan());
3406 for (auto transceiver : transceivers_) {
3407 if (transceiver->mid() == mid) {
3408 return transceiver;
3409 }
3410 }
3411 return nullptr;
3412}
3413
3414rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3415PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3416 RTC_DCHECK(IsUnifiedPlan());
3417 for (auto transceiver : transceivers_) {
3418 if (transceiver->internal()->mline_index() == mline_index) {
3419 return transceiver;
3420 }
3421 }
3422 return nullptr;
3423}
3424
3425rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3426PeerConnection::FindAvailableTransceiverToReceive(
3427 cricket::MediaType media_type) const {
3428 RTC_DCHECK(IsUnifiedPlan());
3429 // From JSEP section 5.10 (Applying a Remote Description):
3430 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3431 // the same type that were added to the PeerConnection by addTrack and are not
3432 // associated with any m= section and are not stopped, find the first such
3433 // RtpTransceiver.
3434 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003435 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003436 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3437 !transceiver->stopped()) {
3438 return transceiver;
3439 }
3440 }
3441 return nullptr;
3442}
3443
Steve Antoned10bd92017-12-05 10:52:59 -08003444const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3445 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3446 transceiver,
3447 const SessionDescriptionInterface* sdesc) const {
3448 RTC_DCHECK(transceiver);
3449 RTC_DCHECK(sdesc);
3450 if (IsUnifiedPlan()) {
3451 if (!transceiver->internal()->mid()) {
3452 // This transceiver is not associated with a media section yet.
3453 return nullptr;
3454 }
3455 return sdesc->description()->GetContentByName(
3456 *transceiver->internal()->mid());
3457 } else {
3458 // Plan B only allows at most one audio and one video section, so use the
3459 // first media section of that type.
3460 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003461 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003462 }
3463}
3464
deadbeef46c73892016-11-16 19:42:04 -08003465PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003466 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003467 return configuration_;
3468}
3469
deadbeef293e9262017-01-11 12:28:30 -08003470bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3471 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003472 RTC_DCHECK_RUN_ON(signaling_thread());
3473 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003474 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003475 if (IsClosed()) {
3476 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3477 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3478 }
3479
Qingsi Wanga2d60672018-04-11 16:57:45 -07003480 // According to JSEP, after setLocalDescription, changing the candidate pool
3481 // size is not allowed, and changing the set of ICE servers will not result
3482 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003483 if (local_description() && configuration.ice_candidate_pool_size !=
3484 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003485 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3486 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003487 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003488 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003489
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003490 if (local_description() &&
3491 configuration.use_media_transport != configuration_.use_media_transport) {
3492 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3493 "SetLocalDescription.";
3494 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3495 }
3496
3497 if (remote_description() &&
3498 configuration.use_media_transport != configuration_.use_media_transport) {
3499 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3500 "SetRemoteDescription.";
3501 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3502 }
3503
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003504 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003505 configuration.use_media_transport_for_data_channels !=
3506 configuration_.use_media_transport_for_data_channels) {
3507 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3508 "after calling SetLocalDescription.";
3509 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3510 }
3511
3512 if (remote_description() &&
3513 configuration.use_media_transport_for_data_channels !=
3514 configuration_.use_media_transport_for_data_channels) {
3515 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3516 "after calling SetRemoteDescription.";
3517 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3518 }
3519
3520 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003521 configuration.crypto_options != configuration_.crypto_options) {
3522 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3523 "SetLocalDescription.";
3524 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3525 }
3526
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003527 if (local_description() && configuration.use_datagram_transport !=
3528 configuration_.use_datagram_transport) {
3529 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3530 "after calling SetLocalDescription.";
3531 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3532 }
3533
3534 if (remote_description() && configuration.use_datagram_transport !=
3535 configuration_.use_datagram_transport) {
3536 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3537 "after calling SetRemoteDescription.";
3538 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3539 }
3540
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003541 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003542 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003543 (configuration.use_datagram_transport &&
3544 *configuration.use_datagram_transport)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003545 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3546 << "Media transport requires MaxBundle policy.";
3547 }
3548
deadbeef293e9262017-01-11 12:28:30 -08003549 // The simplest (and most future-compatible) way to tell if the config was
3550 // modified in an invalid way is to copy each property we do support
3551 // modifying, then use operator==. There are far more properties we don't
3552 // support modifying than those we do, and more could be added.
3553 RTCConfiguration modified_config = configuration_;
3554 modified_config.servers = configuration.servers;
3555 modified_config.type = configuration.type;
3556 modified_config.ice_candidate_pool_size =
3557 configuration.ice_candidate_pool_size;
3558 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003559 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3560 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003561 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003562 modified_config.ice_check_interval_strong_connectivity =
3563 configuration.ice_check_interval_strong_connectivity;
3564 modified_config.ice_check_interval_weak_connectivity =
3565 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003566 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3567 modified_config.ice_unwritable_min_checks =
3568 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003569 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003570 modified_config.stun_candidate_keepalive_interval =
3571 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003572 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003573 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003574 modified_config.active_reset_srtp_params =
3575 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003576 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003577 modified_config.use_media_transport_for_data_channels =
3578 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003579 modified_config.use_datagram_transport = configuration.use_datagram_transport;
deadbeef293e9262017-01-11 12:28:30 -08003580 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003581 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003582 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3583 }
3584
Steve Anton038834f2017-07-14 15:59:59 -07003585 // Validate the modified configuration.
3586 RTCError validate_error = ValidateConfiguration(modified_config);
3587 if (!validate_error.ok()) {
3588 return SafeSetError(std::move(validate_error), error);
3589 }
3590
deadbeef293e9262017-01-11 12:28:30 -08003591 // Note that this isn't possible through chromium, since it's an unsigned
3592 // short in WebIDL.
3593 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003594 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003595 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3596 }
3597
3598 // Parse ICE servers before hopping to network thread.
3599 cricket::ServerAddresses stun_servers;
3600 std::vector<cricket::RelayServerConfig> turn_servers;
3601 RTCErrorType parse_error =
3602 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3603 if (parse_error != RTCErrorType::NONE) {
3604 return SafeSetError(parse_error, error);
3605 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003606 // Note if STUN or TURN servers were supplied.
3607 if (!stun_servers.empty()) {
3608 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3609 }
3610 if (!turn_servers.empty()) {
3611 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3612 }
deadbeef293e9262017-01-11 12:28:30 -08003613
3614 // In theory this shouldn't fail.
3615 if (!network_thread()->Invoke<bool>(
3616 RTC_FROM_HERE,
3617 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3618 stun_servers, turn_servers, modified_config.type,
3619 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003620 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003621 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003622 modified_config.stun_candidate_keepalive_interval,
3623 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003624 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003625 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3626 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003627
deadbeefd1a38b52016-12-10 13:15:33 -08003628 // As described in JSEP, calling setConfiguration with new ICE servers or
3629 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3630 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003631 if (modified_config.servers != configuration_.servers ||
3632 modified_config.type != configuration_.type ||
3633 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003634 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003635 }
skvladd1f5fda2017-02-03 16:54:05 -08003636
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003637 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003638
3639 use_datagram_transport_ = datagram_transport_config_.enabled &&
3640 modified_config.use_datagram_transport.value_or(
3641 datagram_transport_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003642 transport_controller_->SetMediaTransportSettings(
3643 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003644 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003645 use_datagram_transport_);
skvladd1f5fda2017-02-03 16:54:05 -08003646
Zhi Huangb57e1692018-06-12 11:41:11 -07003647 if (configuration_.active_reset_srtp_params !=
3648 modified_config.active_reset_srtp_params) {
3649 transport_controller_->SetActiveResetSrtpParams(
3650 modified_config.active_reset_srtp_params);
3651 }
3652
deadbeef293e9262017-01-11 12:28:30 -08003653 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003654 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003655 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003656}
3657
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003658bool PeerConnection::AddIceCandidate(
3659 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003660 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003661 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003662 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003663 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003664 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003665 return false;
3666 }
Steve Antond25da372017-11-06 14:50:29 -08003667
3668 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003669 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003670 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003671 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003672 return false;
3673 }
3674
3675 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003676 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003677 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003678 return false;
3679 }
3680
3681 bool valid = false;
3682 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3683 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003684 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003685 return false;
3686 }
3687
3688 // Add this candidate to the remote session description.
3689 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003690 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003691 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003692 return false;
3693 }
3694
3695 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003696 bool result = UseCandidate(ice_candidate);
3697 if (result) {
3698 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003699 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3700 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3701 }
3702 if (ice_candidate->candidate().address().IsPrivateIP()) {
3703 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3704 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003705 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3706 } else {
3707 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3708 }
3709 return result;
Steve Antond25da372017-11-06 14:50:29 -08003710 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003711 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003712 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003713 return true;
3714 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003715}
3716
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003717bool PeerConnection::RemoveIceCandidates(
3718 const std::vector<cricket::Candidate>& candidates) {
3719 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003720 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003721 if (IsClosed()) {
3722 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3723 return false;
3724 }
3725
Steve Antond25da372017-11-06 14:50:29 -08003726 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003727 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3728 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003729 return false;
3730 }
3731
3732 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003733 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003734 return false;
3735 }
3736
3737 size_t number_removed =
3738 mutable_remote_description()->RemoveCandidates(candidates);
3739 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003740 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003741 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003742 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003743 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003744 }
3745
3746 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003747 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3748 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003749 RTC_LOG(LS_ERROR)
3750 << "RemoveIceCandidates: Error when removing remote candidates: "
3751 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003752 }
3753 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003754}
3755
Niels Möller0c4f7be2018-05-07 14:01:37 +02003756RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003757 if (!worker_thread()->IsCurrent()) {
3758 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003759 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003760 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003761 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003762
Niels Möller0c4f7be2018-05-07 14:01:37 +02003763 const bool has_min = bitrate.min_bitrate_bps.has_value();
3764 const bool has_start = bitrate.start_bitrate_bps.has_value();
3765 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003766 if (has_min && *bitrate.min_bitrate_bps < 0) {
3767 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3768 "min_bitrate_bps <= 0");
3769 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003770 if (has_start) {
3771 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003772 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003773 "start_bitrate_bps < min_bitrate_bps");
3774 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003775 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3776 "curent_bitrate_bps < 0");
3777 }
3778 }
3779 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003780 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003781 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003782 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003783 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3784 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3785 "max_bitrate_bps < min_bitrate_bps");
3786 } else if (*bitrate.max_bitrate_bps < 0) {
3787 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3788 "max_bitrate_bps < 0");
3789 }
3790 }
3791
zstein4b979802017-06-02 14:37:37 -07003792 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003793 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003794
3795 return RTCError::OK();
3796}
3797
henrika5f6bf242017-11-01 11:06:56 +01003798void PeerConnection::SetAudioPlayout(bool playout) {
3799 if (!worker_thread()->IsCurrent()) {
3800 worker_thread()->Invoke<void>(
3801 RTC_FROM_HERE,
3802 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3803 return;
3804 }
3805 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003806 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003807 audio_state->SetPlayout(playout);
3808}
3809
3810void PeerConnection::SetAudioRecording(bool recording) {
3811 if (!worker_thread()->IsCurrent()) {
3812 worker_thread()->Invoke<void>(
3813 RTC_FROM_HERE,
3814 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3815 return;
3816 }
3817 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003818 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003819 audio_state->SetRecording(recording);
3820}
3821
Steve Anton8c0f7a72017-10-03 10:03:10 -07003822std::unique_ptr<rtc::SSLCertificate>
3823PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003824 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3825 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003826 return nullptr;
3827 }
Steve Antonf25303e2018-10-16 15:23:31 -07003828 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003829}
3830
Zhi Huang70b820f2018-01-27 14:16:15 -08003831std::unique_ptr<rtc::SSLCertChain>
3832PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003833 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003834 auto audio_transceiver = GetFirstAudioTransceiver();
3835 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003836 return nullptr;
3837 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003838 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003839 audio_transceiver->internal()->channel()->transport_name());
3840}
3841
3842rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3843PeerConnection::GetFirstAudioTransceiver() const {
3844 for (auto transceiver : transceivers_) {
3845 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3846 return transceiver;
3847 }
3848 }
3849 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003850}
3851
Bjorn Tereliusde939432017-11-20 17:38:14 +01003852bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3853 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003854 // TODO(eladalon): In C++14, this can be done with a lambda.
3855 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003856 bool operator()() {
3857 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3858 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003859 PeerConnection* const pc;
3860 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003861 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003862 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003863 return worker_thread()->Invoke<bool>(
3864 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003865}
3866
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003867bool PeerConnection::StartRtcEventLog(
3868 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003869 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3870 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3871 output_period_ms = 5000;
3872 }
3873 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003874}
3875
ivoc14d5dbe2016-07-04 07:06:55 -07003876void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003877 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003878 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3879}
3880
Harald Alvestrandad88c882018-11-28 16:47:46 +01003881rtc::scoped_refptr<DtlsTransportInterface>
3882PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003883 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003884 return transport_controller_->LookupDtlsTransportByMid(mid);
3885}
3886
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003887rtc::scoped_refptr<DtlsTransport>
3888PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003889 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003890 return transport_controller_->LookupDtlsTransportByMid(mid);
3891}
3892
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003893rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3894 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003895 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003896 return sctp_transport_;
3897}
3898
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003899const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003900 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003901 return pending_local_description_ ? pending_local_description_.get()
3902 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003903}
3904
3905const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003906 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003907 return pending_remote_description_ ? pending_remote_description_.get()
3908 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003909}
3910
deadbeeffe4a8a42016-12-20 17:56:17 -08003911const SessionDescriptionInterface* PeerConnection::current_local_description()
3912 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003913 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003914 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003915}
3916
3917const SessionDescriptionInterface* PeerConnection::current_remote_description()
3918 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003919 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003920 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003921}
3922
3923const SessionDescriptionInterface* PeerConnection::pending_local_description()
3924 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003925 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003926 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003927}
3928
3929const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3930 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003931 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003932 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003933}
3934
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003935void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003936 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003937 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003938 // Update stats here so that we have the most recent stats for tracks and
3939 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003940 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003941
Steve Anton75737c02017-11-06 10:37:17 -08003942 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003943 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003944
Mirko Bonadei739baf02019-01-27 17:29:42 +01003945 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003946 transceiver->Stop();
3947 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003948
3949 // Ensure that all asynchronous stats requests are completed before destroying
3950 // the transport controller below.
3951 if (stats_collector_) {
3952 stats_collector_->WaitForPendingRequest();
3953 }
3954
3955 // Don't destroy BaseChannels until after stats has been cleaned up so that
3956 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003957 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003958
Qingsi Wang93a84392018-01-30 17:13:09 -08003959 // The event log is used in the transport controller, which must be outlived
3960 // by the former. CreateOffer by the peer connection is implemented
3961 // asynchronously and if the peer connection is closed without resetting the
3962 // WebRTC session description factory, the session description factory would
3963 // call the transport controller.
3964 webrtc_session_desc_factory_.reset();
3965 transport_controller_.reset();
3966
deadbeef42a42632017-03-10 15:18:00 -08003967 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003968 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3969 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003970
Steve Anton978b8762017-09-29 12:15:02 -07003971 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003972 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003973 call_.reset();
3974 // The event log must outlive call (and any other object that uses it).
3975 event_log_.reset();
3976 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003977 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003978 // The .h file says that observer can be discarded after close() returns.
3979 // Make sure this is true.
3980 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003981}
3982
Steve Antonad182762018-09-05 20:22:40 +00003983void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003984 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003985 switch (msg->message_id) {
3986 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3987 SetSessionDescriptionMsg* param =
3988 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3989 param->observer->OnSuccess();
3990 delete param;
3991 break;
3992 }
3993 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3994 SetSessionDescriptionMsg* param =
3995 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3996 param->observer->OnFailure(std::move(param->error));
3997 delete param;
3998 break;
3999 }
4000 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4001 CreateSessionDescriptionMsg* param =
4002 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4003 param->observer->OnFailure(std::move(param->error));
4004 delete param;
4005 break;
4006 }
4007 case MSG_GETSTATS: {
4008 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4009 StatsReports reports;
4010 stats_->GetStats(param->track, &reports);
4011 param->observer->OnComplete(reports);
4012 delete param;
4013 break;
4014 }
4015 case MSG_FREE_DATACHANNELS: {
4016 sctp_data_channels_to_free_.clear();
4017 break;
4018 }
4019 case MSG_REPORT_USAGE_PATTERN: {
4020 ReportUsagePattern();
4021 break;
4022 }
4023 default:
4024 RTC_NOTREACHED() << "Not implemented";
4025 break;
4026 }
4027}
4028
Steve Antonafb0bb72018-02-20 11:35:37 -08004029cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4030 RTC_DCHECK(!IsUnifiedPlan());
4031 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4032 GetAudioTransceiver()->internal()->channel());
4033 if (voice_channel) {
4034 return voice_channel->media_channel();
4035 } else {
4036 return nullptr;
4037 }
4038}
4039
4040cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4041 RTC_DCHECK(!IsUnifiedPlan());
4042 auto* video_channel = static_cast<cricket::VideoChannel*>(
4043 GetVideoTransceiver()->internal()->channel());
4044 if (video_channel) {
4045 return video_channel->media_channel();
4046 } else {
4047 return nullptr;
4048 }
4049}
4050
Steve Anton4171afb2017-11-20 10:20:22 -08004051void PeerConnection::CreateAudioReceiver(
4052 MediaStreamInterface* stream,
4053 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004054 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4055 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004056 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4057 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004058 auto* audio_receiver = new AudioRtpReceiver(
4059 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004060 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004061 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4062 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4063 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004064 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004065 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004066 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004067}
4068
Steve Anton4171afb2017-11-20 10:20:22 -08004069void PeerConnection::CreateVideoReceiver(
4070 MediaStreamInterface* stream,
4071 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004072 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4073 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004074 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4075 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004076 auto* video_receiver = new VideoRtpReceiver(
4077 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004078 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004079 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4080 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4081 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004082 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004083 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004084 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004085}
4086
deadbeef70ab1a12015-09-28 16:53:55 -07004087// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4088// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004089rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004090 const RtpSenderInfo& remote_sender_info) {
4091 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4092 if (!receiver) {
4093 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4094 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004095 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004096 }
Steve Anton4171afb2017-11-20 10:20:22 -08004097 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4098 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4099 } else {
4100 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4101 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004102 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004103}
4104
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004105void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4106 MediaStreamInterface* stream) {
4107 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004108 RTC_DCHECK(track);
4109 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004110 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004111 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004112 // We already have a sender for this track, so just change the stream_id
4113 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004114 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004115 return;
4116 }
4117
4118 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004119 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004120 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004121 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004122 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004123 // If the sender has already been configured in SDP, we call SetSsrc,
4124 // which will connect the sender to the underlying transport. This can
4125 // occur if a local session description that contains the ID of the sender
4126 // is set before AddStream is called. It can also occur if the local
4127 // session description is not changed and RemoveStream is called, and
4128 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004129 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004130 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004131 if (sender_info) {
4132 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004133 }
4134}
4135
4136// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4137// indefinitely, when we have unified plan SDP.
4138void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4139 MediaStreamInterface* stream) {
4140 RTC_DCHECK(!IsClosed());
4141 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004142 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004143 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4144 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004145 return;
4146 }
Steve Anton4171afb2017-11-20 10:20:22 -08004147 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004148}
4149
4150void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4151 MediaStreamInterface* stream) {
4152 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004153 RTC_DCHECK(track);
4154 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004155 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004156 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004157 // We already have a sender for this track, so just change the stream_id
4158 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004159 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004160 return;
4161 }
4162
4163 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004164 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004165 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004166 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004167 GetVideoTransceiver()->internal()->AddSender(new_sender);
4168 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004169 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004170 if (sender_info) {
4171 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004172 }
4173}
4174
4175void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4176 MediaStreamInterface* stream) {
4177 RTC_DCHECK(!IsClosed());
4178 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004179 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004180 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4181 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004182 return;
4183 }
Steve Anton4171afb2017-11-20 10:20:22 -08004184 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004185}
4186
Steve Antonba818672017-11-06 10:21:57 -08004187void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004188 if (ice_connection_state_ == new_state) {
4189 return;
4190 }
4191
deadbeefcbecd352015-09-23 11:50:27 -07004192 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004193 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004194 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004195 return;
4196 }
Steve Antonba818672017-11-06 10:21:57 -08004197
Mirko Bonadei675513b2017-11-09 11:09:25 +01004198 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4199 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004200 RTC_DCHECK(ice_connection_state_ !=
4201 PeerConnectionInterface::kIceConnectionClosed);
4202
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004203 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004204 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004205}
4206
Alex Loiko9289eda2018-11-23 16:18:59 +00004207void PeerConnection::SetStandardizedIceConnectionState(
4208 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004209 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004210 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004211 }
4212
4213 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004214 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004215 }
4216
4217 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4218 << standardized_ice_connection_state_ << " => " << new_state;
4219
Alex Loiko9289eda2018-11-23 16:18:59 +00004220 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004221 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004222}
4223
Jonas Olsson635474e2018-10-18 15:58:17 +02004224void PeerConnection::SetConnectionState(
4225 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004226 if (connection_state_ == new_state)
4227 return;
4228 if (IsClosed())
4229 return;
4230 connection_state_ = new_state;
4231 Observer()->OnConnectionChange(new_state);
4232}
4233
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004234void PeerConnection::OnIceGatheringChange(
4235 PeerConnectionInterface::IceGatheringState new_state) {
4236 if (IsClosed()) {
4237 return;
4238 }
4239 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004240 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004241}
4242
jbauch81bf7b02017-03-25 08:31:12 -07004243void PeerConnection::OnIceCandidate(
4244 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004245 if (IsClosed()) {
4246 return;
4247 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004248 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004249 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4250 candidate->candidate().address().IsPrivateIP()) {
4251 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4252 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004253 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4254 candidate->candidate().address().IsUnresolvedIP()) {
4255 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4256 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004257 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004258}
4259
Eldar Relloda13ea22019-06-01 12:23:43 +03004260void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4261 const std::string& url,
4262 int error_code,
4263 const std::string& error_text) {
4264 if (IsClosed()) {
4265 return;
4266 }
4267 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4268}
4269
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004270void PeerConnection::OnIceCandidatesRemoved(
4271 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004272 if (IsClosed()) {
4273 return;
4274 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004275 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004276}
4277
Alex Drake00c7ecf2019-08-06 10:54:47 -07004278void PeerConnection::OnSelectedCandidatePairChanged(
4279 const cricket::CandidatePairChangeEvent& event) {
4280 if (IsClosed()) {
4281 return;
4282 }
4283 Observer()->OnIceSelectedCandidatePairChanged(event);
4284}
4285
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004286void PeerConnection::ChangeSignalingState(
4287 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004288 if (signaling_state_ == signaling_state) {
4289 return;
4290 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004291 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4292 << GetSignalingStateString(signaling_state_)
4293 << " New state: "
4294 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004295 signaling_state_ = signaling_state;
4296 if (signaling_state == kClosed) {
4297 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004298 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004299 standardized_ice_connection_state_ =
4300 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004301 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4302 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004303 if (ice_gathering_state_ != kIceGatheringComplete) {
4304 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004305 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004306 }
4307 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004308 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004309}
4310
deadbeefeb459812015-12-15 19:24:43 -08004311void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4312 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004313 if (IsClosed()) {
4314 return;
4315 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004316 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004317 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004318}
4319
deadbeefeb459812015-12-15 19:24:43 -08004320void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4321 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004322 if (IsClosed()) {
4323 return;
4324 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004325 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004326 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004327}
4328
4329void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4330 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004331 if (IsClosed()) {
4332 return;
4333 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004334 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004335 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004336}
4337
4338void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4339 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004340 if (IsClosed()) {
4341 return;
4342 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004343 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004344 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004345}
4346
Henrik Boström31638672017-11-23 17:48:32 +01004347void PeerConnection::PostSetSessionDescriptionSuccess(
4348 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004349 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4350 signaling_thread()->Post(RTC_FROM_HERE, this,
4351 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004352}
4353
deadbeefab9b2d12015-10-14 11:33:11 -07004354void PeerConnection::PostSetSessionDescriptionFailure(
4355 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004356 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004357 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004358 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4359 msg->error = std::move(error);
4360 signaling_thread()->Post(RTC_FROM_HERE, this,
4361 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004362}
4363
4364void PeerConnection::PostCreateSessionDescriptionFailure(
4365 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004366 RTCError error) {
4367 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004368 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4369 msg->error = std::move(error);
4370 signaling_thread()->Post(RTC_FROM_HERE, this,
4371 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004372}
4373
zhihuang1c378ed2017-08-17 14:10:50 -07004374void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004375 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004376 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004377 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004378
Steve Antondcc3c022017-12-22 16:02:54 -08004379 if (IsUnifiedPlan()) {
4380 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4381 } else {
4382 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4383 }
4384
Steve Antonfa2260d2017-12-28 16:38:23 -08004385 // Intentionally unset the data channel type for RTP data channel with the
4386 // second condition. Otherwise the RTP data channels would be successfully
4387 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4388 // when building with chromium. We want to leave RTP data channels broken, so
4389 // people won't try to use them.
4390 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4391 session_options->data_channel_type = data_channel_type();
4392 }
4393
Steve Antondcc3c022017-12-22 16:02:54 -08004394 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004395 bool ice_restart = offer_answer_options.ice_restart ||
4396 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004397 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004398 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004399 options.transport_options.enable_ice_renomination =
4400 configuration_.enable_ice_renomination;
4401 }
4402
4403 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004404 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004405 session_options->pooled_ice_credentials =
4406 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4407 RTC_FROM_HERE,
4408 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4409 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004410 session_options->offer_extmap_allow_mixed =
4411 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004412
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004413 if (configuration_.use_media_transport ||
4414 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004415 session_options->media_transport_settings =
4416 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4417 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004418
4419 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004420 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004421 for (auto& options : session_options->media_description_options) {
4422 options.transport_options.opaque_parameters =
4423 transport_controller_->GetTransportParameters(options.mid);
4424 }
4425 }
4426
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004427 // Allow fallback for using obsolete SCTP syntax.
4428 // Note that the default in |session_options| is true, while
4429 // the default in |options| is false.
4430 session_options->use_obsolete_sctp_sdp =
4431 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004432}
4433
4434void PeerConnection::GetOptionsForPlanBOffer(
4435 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4436 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004437 // Figure out transceiver directional preferences.
4438 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4439 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4440
4441 // By default, generate sendrecv/recvonly m= sections.
4442 bool recv_audio = true;
4443 bool recv_video = true;
4444
4445 // By default, only offer a new m= section if we have media to send with it.
4446 bool offer_new_audio_description = send_audio;
4447 bool offer_new_video_description = send_video;
4448 bool offer_new_data_description = HasDataChannels();
4449
4450 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004451 if (offer_answer_options.offer_to_receive_audio !=
4452 RTCOfferAnswerOptions::kUndefined) {
4453 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004454 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004455 offer_new_audio_description ||
4456 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004457 }
Steve Antondcc3c022017-12-22 16:02:54 -08004458 if (offer_answer_options.offer_to_receive_video !=
4459 RTCOfferAnswerOptions::kUndefined) {
4460 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004461 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004462 offer_new_video_description ||
4463 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004464 }
4465
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004466 absl::optional<size_t> audio_index;
4467 absl::optional<size_t> video_index;
4468 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004469 // If a current description exists, generate m= sections in the same order,
4470 // using the first audio/video/data section that appears and rejecting
4471 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004472 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004473 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004474 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004475 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4476 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4477 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004478 }
4479
zhihuang1c378ed2017-08-17 14:10:50 -07004480 // Add audio/video/data m= sections to the end if needed.
4481 if (!audio_index && offer_new_audio_description) {
4482 session_options->media_description_options.push_back(
4483 cricket::MediaDescriptionOptions(
4484 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004485 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4486 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004487 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004488 }
zhihuang1c378ed2017-08-17 14:10:50 -07004489 if (!video_index && offer_new_video_description) {
4490 session_options->media_description_options.push_back(
4491 cricket::MediaDescriptionOptions(
4492 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004493 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4494 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004495 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004496 }
zhihuang1c378ed2017-08-17 14:10:50 -07004497 if (!data_index && offer_new_data_description) {
4498 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004499 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004500 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004501 }
4502
4503 cricket::MediaDescriptionOptions* audio_media_description_options =
4504 !audio_index ? nullptr
4505 : &session_options->media_description_options[*audio_index];
4506 cricket::MediaDescriptionOptions* video_media_description_options =
4507 !video_index ? nullptr
4508 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004509
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004510 AddPlanBRtpSenderOptions(GetSendersInternal(),
4511 audio_media_description_options,
4512 video_media_description_options,
4513 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004514}
4515
Steve Antondcc3c022017-12-22 16:02:54 -08004516static cricket::MediaDescriptionOptions
4517GetMediaDescriptionOptionsForTransceiver(
4518 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4519 transceiver,
4520 const std::string& mid) {
4521 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004522 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004523 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004524 media_description_options.codec_preferences =
4525 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004526 // This behavior is specified in JSEP. The gist is that:
4527 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4528 // sendrecv.
4529 // 2. If the MSID is included, then it must be included in any subsequent
4530 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004531 if (transceiver->stopped() ||
4532 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4533 !transceiver->internal()->has_ever_been_used_to_send())) {
4534 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004535 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004536
4537 cricket::SenderOptions sender_options;
4538 sender_options.track_id = transceiver->sender()->id();
4539 sender_options.stream_ids = transceiver->sender()->stream_ids();
4540
4541 // The following sets up RIDs and Simulcast.
4542 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004543 RtpParameters send_parameters =
4544 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004545 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4546 send_parameters.encodings.end(),
4547 [](const RtpEncodingParameters& encoding) {
4548 return !encoding.rid.empty();
4549 });
4550
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004551 std::vector<RidDescription> send_rids;
4552 SimulcastLayerList send_layers;
4553 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4554 if (encoding.rid.empty()) {
4555 continue;
4556 }
4557 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4558 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4559 }
4560
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004561 if (has_rids) {
4562 sender_options.rids = send_rids;
4563 }
4564
4565 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004566 // When RIDs are configured, we must set num_sim_layers to 0 to.
4567 // Otherwise, num_sim_layers must be 1 because either there is no
4568 // simulcast, or simulcast is acheived by munging the SDP.
4569 sender_options.num_sim_layers = has_rids ? 0 : 1;
4570 media_description_options.sender_options.push_back(sender_options);
4571
Steve Antondcc3c022017-12-22 16:02:54 -08004572 return media_description_options;
4573}
4574
Steve Anton5c72e712018-12-10 14:25:30 -08004575// Returns the ContentInfo at mline index |i|, or null if none exists.
4576static const ContentInfo* GetContentByIndex(
4577 const SessionDescriptionInterface* sdesc,
4578 size_t i) {
4579 if (!sdesc) {
4580 return nullptr;
4581 }
4582 const ContentInfos& contents = sdesc->description()->contents();
4583 return (i < contents.size() ? &contents[i] : nullptr);
4584}
4585
Steve Antondcc3c022017-12-22 16:02:54 -08004586void PeerConnection::GetOptionsForUnifiedPlanOffer(
4587 const RTCOfferAnswerOptions& offer_answer_options,
4588 cricket::MediaSessionOptions* session_options) {
4589 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4590 // Offers) and 5.2.2 (Subsequent Offers).
4591 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004592 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004593 const ContentInfos& local_contents =
4594 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004595 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004596 const ContentInfos& remote_contents =
4597 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004598 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004599 // The mline indices that can be recycled. New transceivers should reuse these
4600 // slots first.
4601 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004602 // First, go through each media section that exists in either the local or
4603 // remote description and generate a media section in this offer for the
4604 // associated transceiver. If a media section can be recycled, generate a
4605 // default, rejected media section here that can be later overwritten.
4606 for (size_t i = 0;
4607 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4608 // Either |local_content| or |remote_content| is non-null.
4609 const ContentInfo* local_content =
4610 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004611 const ContentInfo* current_local_content =
4612 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004613 const ContentInfo* remote_content =
4614 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004615 const ContentInfo* current_remote_content =
4616 GetContentByIndex(current_remote_description(), i);
4617 bool had_been_rejected =
4618 (current_local_content && current_local_content->rejected) ||
4619 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004620 const std::string& mid =
4621 (local_content ? local_content->name : remote_content->name);
4622 cricket::MediaType media_type =
4623 (local_content ? local_content->media_description()->type()
4624 : remote_content->media_description()->type());
4625 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4626 media_type == cricket::MEDIA_TYPE_VIDEO) {
4627 auto transceiver = GetAssociatedTransceiver(mid);
4628 RTC_CHECK(transceiver);
4629 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004630 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004631 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004632 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004633 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4634 RtpTransceiverDirection::kInactive,
4635 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004636 recycleable_mline_indices.push(i);
4637 } else {
4638 session_options->media_description_options.push_back(
4639 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4640 // CreateOffer shouldn't really cause any state changes in
4641 // PeerConnection, but we need a way to match new transceivers to new
4642 // media sections in SetLocalDescription and JSEP specifies this is done
4643 // by recording the index of the media section generated for the
4644 // transceiver in the offer.
4645 transceiver->internal()->set_mline_index(i);
4646 }
4647 } else {
4648 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004649 RTC_CHECK(GetDataMid());
4650 if (had_been_rejected || mid != *GetDataMid()) {
4651 session_options->media_description_options.push_back(
4652 GetMediaDescriptionOptionsForRejectedData(mid));
4653 } else {
4654 session_options->media_description_options.push_back(
4655 GetMediaDescriptionOptionsForActiveData(mid));
4656 }
Steve Antondcc3c022017-12-22 16:02:54 -08004657 }
4658 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004659
Steve Antondcc3c022017-12-22 16:02:54 -08004660 // Next, look for transceivers that are newly added (that is, are not stopped
4661 // and not associated). Reuse media sections marked as recyclable first,
4662 // otherwise append to the end of the offer. New media sections should be
4663 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004664 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004665 if (transceiver->mid() || transceiver->stopped()) {
4666 continue;
4667 }
4668 size_t mline_index;
4669 if (!recycleable_mline_indices.empty()) {
4670 mline_index = recycleable_mline_indices.front();
4671 recycleable_mline_indices.pop();
4672 session_options->media_description_options[mline_index] =
4673 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004674 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004675 } else {
4676 mline_index = session_options->media_description_options.size();
4677 session_options->media_description_options.push_back(
4678 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004679 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004680 }
4681 // See comment above for why CreateOffer changes the transceiver's state.
4682 transceiver->internal()->set_mline_index(mline_index);
4683 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004684 // Lastly, add a m-section if we have local data channels and an m section
4685 // does not already exist.
4686 if (!GetDataMid() && HasDataChannels()) {
4687 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004688 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004689 }
Steve Antondcc3c022017-12-22 16:02:54 -08004690}
4691
4692void PeerConnection::GetOptionsForAnswer(
4693 const RTCOfferAnswerOptions& offer_answer_options,
4694 cricket::MediaSessionOptions* session_options) {
4695 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4696
4697 if (IsUnifiedPlan()) {
4698 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4699 } else {
4700 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4701 }
4702
Steve Antonfa2260d2017-12-28 16:38:23 -08004703 // Intentionally unset the data channel type for RTP data channel. Otherwise
4704 // the RTP data channels would be successfully negotiated by default and the
4705 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4706 // We want to leave RTP data channels broken, so people won't try to use them.
4707 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4708 session_options->data_channel_type = data_channel_type();
4709 }
4710
Steve Antondcc3c022017-12-22 16:02:54 -08004711 // Apply ICE renomination flag.
4712 for (auto& options : session_options->media_description_options) {
4713 options.transport_options.enable_ice_renomination =
4714 configuration_.enable_ice_renomination;
4715 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004716
4717 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004718 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004719 session_options->pooled_ice_credentials =
4720 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4721 RTC_FROM_HERE,
4722 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4723 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004724
4725 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004726 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004727 for (auto& options : session_options->media_description_options) {
4728 options.transport_options.opaque_parameters =
4729 transport_controller_->GetTransportParameters(options.mid);
4730 }
4731 }
deadbeefab9b2d12015-10-14 11:33:11 -07004732}
4733
Steve Antondcc3c022017-12-22 16:02:54 -08004734void PeerConnection::GetOptionsForPlanBAnswer(
4735 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004736 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004737 // Figure out transceiver directional preferences.
4738 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4739 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4740
4741 // By default, generate sendrecv/recvonly m= sections. The direction is also
4742 // restricted by the direction in the offer.
4743 bool recv_audio = true;
4744 bool recv_video = true;
4745
4746 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004747 if (offer_answer_options.offer_to_receive_audio !=
4748 RTCOfferAnswerOptions::kUndefined) {
4749 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004750 }
Steve Antondcc3c022017-12-22 16:02:54 -08004751 if (offer_answer_options.offer_to_receive_video !=
4752 RTCOfferAnswerOptions::kUndefined) {
4753 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004754 }
4755
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004756 absl::optional<size_t> audio_index;
4757 absl::optional<size_t> video_index;
4758 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004759
4760 // Generate m= sections that match those in the offer.
4761 // Note that mediasession.cc will handle intersection our preferred
4762 // direction with the offered direction.
4763 GenerateMediaDescriptionOptions(
4764 remote_description(),
4765 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4766 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4767 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004768
4769 cricket::MediaDescriptionOptions* audio_media_description_options =
4770 !audio_index ? nullptr
4771 : &session_options->media_description_options[*audio_index];
4772 cricket::MediaDescriptionOptions* video_media_description_options =
4773 !video_index ? nullptr
4774 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004775
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004776 AddPlanBRtpSenderOptions(GetSendersInternal(),
4777 audio_media_description_options,
4778 video_media_description_options,
4779 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004780}
zhihuangaf388472016-11-02 16:49:48 -07004781
Steve Antondcc3c022017-12-22 16:02:54 -08004782void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4783 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4784 cricket::MediaSessionOptions* session_options) {
4785 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4786 // Answers) and 5.3.2 (Subsequent Answers).
4787 RTC_DCHECK(remote_description());
4788 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4789 for (const ContentInfo& content :
4790 remote_description()->description()->contents()) {
4791 cricket::MediaType media_type = content.media_description()->type();
4792 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4793 media_type == cricket::MEDIA_TYPE_VIDEO) {
4794 auto transceiver = GetAssociatedTransceiver(content.name);
4795 RTC_CHECK(transceiver);
4796 session_options->media_description_options.push_back(
4797 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4798 } else {
4799 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004800 // Reject all data sections if data channels are disabled.
4801 // Reject a data section if it has already been rejected.
4802 // Reject all data sections except for the first one.
4803 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4804 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004805 session_options->media_description_options.push_back(
4806 GetMediaDescriptionOptionsForRejectedData(content.name));
4807 } else {
4808 session_options->media_description_options.push_back(
4809 GetMediaDescriptionOptionsForActiveData(content.name));
4810 }
Steve Antondcc3c022017-12-22 16:02:54 -08004811 }
4812 }
htaa2a49d92016-03-04 02:51:39 -08004813}
4814
zhihuang1c378ed2017-08-17 14:10:50 -07004815void PeerConnection::GenerateMediaDescriptionOptions(
4816 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004817 RtpTransceiverDirection audio_direction,
4818 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004819 absl::optional<size_t>* audio_index,
4820 absl::optional<size_t>* video_index,
4821 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004822 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004823 for (const cricket::ContentInfo& content :
4824 session_desc->description()->contents()) {
4825 if (IsAudioContent(&content)) {
4826 // If we already have an audio m= section, reject this extra one.
4827 if (*audio_index) {
4828 session_options->media_description_options.push_back(
4829 cricket::MediaDescriptionOptions(
4830 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004831 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004832 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004833 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004834 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004835 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4836 content.name, audio_direction,
4837 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004838 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004839 }
4840 } else if (IsVideoContent(&content)) {
4841 // If we already have an video m= section, reject this extra one.
4842 if (*video_index) {
4843 session_options->media_description_options.push_back(
4844 cricket::MediaDescriptionOptions(
4845 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004846 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004847 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004848 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004849 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004850 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4851 content.name, video_direction,
4852 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004853 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004854 }
4855 } else {
4856 RTC_DCHECK(IsDataContent(&content));
4857 // If we already have an data m= section, reject this extra one.
4858 if (*data_index) {
4859 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004860 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004861 } else {
4862 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004863 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004864 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004865 }
4866 }
htaa2a49d92016-03-04 02:51:39 -08004867 }
deadbeefab9b2d12015-10-14 11:33:11 -07004868}
4869
Steve Antonfa2260d2017-12-28 16:38:23 -08004870cricket::MediaDescriptionOptions
4871PeerConnection::GetMediaDescriptionOptionsForActiveData(
4872 const std::string& mid) const {
4873 // Direction for data sections is meaningless, but legacy endpoints might
4874 // expect sendrecv.
4875 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4876 RtpTransceiverDirection::kSendRecv,
4877 /*stopped=*/false);
4878 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4879 return options;
4880}
4881
4882cricket::MediaDescriptionOptions
4883PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4884 const std::string& mid) const {
4885 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4886 RtpTransceiverDirection::kInactive,
4887 /*stopped=*/true);
4888 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4889 return options;
4890}
4891
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004892absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004893 switch (data_channel_type_) {
4894 case cricket::DCT_RTP:
4895 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004896 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004897 }
4898 return rtp_data_channel_->content_name();
4899 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004900 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004901 case cricket::DCT_MEDIA_TRANSPORT:
4902 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004903 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004904 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004905 }
4906}
4907
Steve Anton4171afb2017-11-20 10:20:22 -08004908void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4909 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4910 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004911 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004912}
4913
Steve Anton4171afb2017-11-20 10:20:22 -08004914void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004915 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004916 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004917 cricket::MediaType media_type,
4918 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004919 RTC_DCHECK(!IsUnifiedPlan());
4920
Steve Anton4171afb2017-11-20 10:20:22 -08004921 std::vector<RtpSenderInfo>* current_senders =
4922 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004923
Steve Anton4171afb2017-11-20 10:20:22 -08004924 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004925 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004926 for (auto sender_it = current_senders->begin();
4927 sender_it != current_senders->end();
4928 /* incremented manually */) {
4929 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004930 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004931 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004932 std::string params_stream_id;
4933 if (params) {
4934 params_stream_id =
4935 (!params->first_stream_id().empty() ? params->first_stream_id()
4936 : kDefaultStreamId);
4937 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004938 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004939 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004940 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004941 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004942 sender_exists) {
4943 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004944 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004945 OnRemoteSenderRemoved(info, media_type);
4946 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004947 }
4948 }
4949
Steve Anton4171afb2017-11-20 10:20:22 -08004950 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004951 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004952 if (!params.has_ssrcs()) {
4953 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4954 // sender, this means it is coming from a Unified Plan endpoint,so we just
4955 // create a default.
4956 default_sender_needed = true;
4957 break;
4958 }
4959
Seth Hampson845e8782018-03-02 11:34:10 -08004960 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004961 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004962 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4963 // not supported in Plan B, we just take the first here and create the
4964 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004965 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004966 (!params.first_stream_id().empty() ? params.first_stream_id()
4967 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004968 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004969 uint32_t ssrc = params.first_ssrc();
4970
4971 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004972 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004973 if (!stream) {
4974 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004975 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004976 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004977 remote_streams_->AddStream(stream);
4978 new_streams->AddStream(stream);
4979 }
4980
Steve Anton4171afb2017-11-20 10:20:22 -08004981 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004982 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004983 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004984 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004985 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004986 }
4987 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004988
Steve Anton4171afb2017-11-20 10:20:22 -08004989 // Add default sender if necessary.
4990 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004991 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004992 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004993 if (!default_stream) {
4994 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004995 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004996 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004997 remote_streams_->AddStream(default_stream);
4998 new_streams->AddStream(default_stream);
4999 }
Steve Anton4171afb2017-11-20 10:20:22 -08005000 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5001 ? kDefaultAudioSenderId
5002 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005003 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005004 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005005 if (!default_sender_info) {
5006 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005007 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005008 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005009 }
5010 }
deadbeefab9b2d12015-10-14 11:33:11 -07005011}
5012
Steve Anton4171afb2017-11-20 10:20:22 -08005013void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5014 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005015 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5016 << " receiver for track_id=" << sender_info.sender_id
5017 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005018
Steve Anton3d954a62018-04-02 11:27:23 -07005019 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005020 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005021 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005022 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005023 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005024 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005025 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005026 }
5027}
5028
Steve Anton4171afb2017-11-20 10:20:22 -08005029void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5030 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005031 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5032 << " receiver for track_id=" << sender_info.sender_id
5033 << " and stream_id=" << sender_info.stream_id;
5034
Seth Hampson845e8782018-03-02 11:34:10 -08005035 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005036
Henrik Boström933d8b02017-10-10 10:05:16 -07005037 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005038 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005039 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5040 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005041 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005042 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005043 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005044 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005045 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005046 }
5047 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005048 // Stopping or destroying a VideoRtpReceiver will end the
5049 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005050 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005051 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005052 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005053 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005054 // There's no guarantee the track is still available, e.g. the track may
5055 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005056 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005057 }
5058 } else {
nisseede5da42017-01-12 05:15:36 -08005059 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005060 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005061 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005062 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005063 }
deadbeefab9b2d12015-10-14 11:33:11 -07005064}
5065
5066void PeerConnection::UpdateEndedRemoteMediaStreams() {
5067 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5068 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5069 MediaStreamInterface* stream = remote_streams_->at(i);
5070 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5071 streams_to_remove.push_back(stream);
5072 }
5073 }
5074
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005075 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005076 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005077 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005078 }
5079}
5080
Steve Anton4171afb2017-11-20 10:20:22 -08005081void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005082 const std::vector<cricket::StreamParams>& streams,
5083 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005084 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005085
Seth Hampson845e8782018-03-02 11:34:10 -08005086 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005087 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005088 for (auto sender_it = current_senders->begin();
5089 sender_it != current_senders->end();
5090 /* incremented manually */) {
5091 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005092 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005093 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5094 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005095 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005096 OnLocalSenderRemoved(info, media_type);
5097 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005098 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005099 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005100 }
5101 }
5102
Steve Anton4171afb2017-11-20 10:20:22 -08005103 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005104 for (const cricket::StreamParams& params : streams) {
5105 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005106 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005107 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005108 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005109 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005110 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005111 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005112 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005113 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005114 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005115 }
5116 }
5117}
5118
Steve Anton4171afb2017-11-20 10:20:22 -08005119void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5120 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005121 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005122 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005123 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005124 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5125 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005126 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005127 return;
5128 }
5129
deadbeeffac06552015-11-25 11:26:01 -08005130 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005132 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005133 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005134 }
deadbeeffac06552015-11-25 11:26:01 -08005135
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005136 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005137 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005138}
5139
Steve Anton4171afb2017-11-20 10:20:22 -08005140void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5141 cricket::MediaType media_type) {
5142 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005143 if (!sender) {
5144 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005145 // SessionDescriptions has been renegotiated.
5146 return;
5147 }
deadbeeffac06552015-11-25 11:26:01 -08005148
5149 // A sender has been removed from the SessionDescription but it's still
5150 // associated with the PeerConnection. This only occurs if the SDP doesn't
5151 // match with the calls to CreateSender, AddStream and RemoveStream.
5152 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005153 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005154 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005155 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005156 }
deadbeeffac06552015-11-25 11:26:01 -08005157
Steve Anton4171afb2017-11-20 10:20:22 -08005158 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005159}
5160
5161void PeerConnection::UpdateLocalRtpDataChannels(
5162 const cricket::StreamParamsVec& streams) {
5163 std::vector<std::string> existing_channels;
5164
5165 // Find new and active data channels.
5166 for (const cricket::StreamParams& params : streams) {
5167 // |it->sync_label| is actually the data channel label. The reason is that
5168 // we use the same naming of data channels as we do for
5169 // MediaStreams and Tracks.
5170 // For MediaStreams, the sync_label is the MediaStream label and the
5171 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005172 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005173 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005174 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005175 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005176 continue;
5177 }
5178 // Set the SSRC the data channel should use for sending.
5179 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5180 existing_channels.push_back(data_channel_it->first);
5181 }
5182
5183 UpdateClosingRtpDataChannels(existing_channels, true);
5184}
5185
5186void PeerConnection::UpdateRemoteRtpDataChannels(
5187 const cricket::StreamParamsVec& streams) {
5188 std::vector<std::string> existing_channels;
5189
5190 // Find new and active data channels.
5191 for (const cricket::StreamParams& params : streams) {
5192 // The data channel label is either the mslabel or the SSRC if the mslabel
5193 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005194 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005195 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005196 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005197 auto data_channel_it = rtp_data_channels_.find(label);
5198 if (data_channel_it == rtp_data_channels_.end()) {
5199 // This is a new data channel.
5200 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5201 } else {
5202 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5203 }
5204 existing_channels.push_back(label);
5205 }
5206
5207 UpdateClosingRtpDataChannels(existing_channels, false);
5208}
5209
5210void PeerConnection::UpdateClosingRtpDataChannels(
5211 const std::vector<std::string>& active_channels,
5212 bool is_local_update) {
5213 auto it = rtp_data_channels_.begin();
5214 while (it != rtp_data_channels_.end()) {
5215 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005216 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005217 ++it;
5218 continue;
5219 }
5220
5221 if (is_local_update) {
5222 data_channel->SetSendSsrc(0);
5223 } else {
5224 data_channel->RemotePeerRequestClose();
5225 }
5226
5227 if (data_channel->state() == DataChannel::kClosed) {
5228 rtp_data_channels_.erase(it);
5229 it = rtp_data_channels_.begin();
5230 } else {
5231 ++it;
5232 }
5233 }
5234}
5235
5236void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5237 uint32_t remote_ssrc) {
5238 rtc::scoped_refptr<DataChannel> channel(
5239 InternalCreateDataChannel(label, nullptr));
5240 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005241 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005242 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005243 return;
5244 }
5245 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005246 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5247 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005248 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005249}
5250
5251rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5252 const std::string& label,
5253 const InternalDataChannelInit* config) {
5254 if (IsClosed()) {
5255 return nullptr;
5256 }
Steve Anton75737c02017-11-06 10:37:17 -08005257 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005258 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005259 << "InternalCreateDataChannel: Data is not supported in this call.";
5260 return nullptr;
5261 }
5262 InternalDataChannelInit new_config =
5263 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005264 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005265 if (new_config.id < 0) {
5266 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005267 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005268 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005269 RTC_LOG(LS_ERROR)
5270 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005271 return nullptr;
5272 }
5273 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005274 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005275 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005276 return nullptr;
5277 }
5278 }
5279
Steve Anton75737c02017-11-06 10:37:17 -08005280 rtc::scoped_refptr<DataChannel> channel(
5281 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005282 if (!channel) {
5283 sid_allocator_.ReleaseSid(new_config.id);
5284 return nullptr;
5285 }
5286
5287 if (channel->data_channel_type() == cricket::DCT_RTP) {
5288 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005289 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5290 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005291 return nullptr;
5292 }
5293 rtp_data_channels_[channel->label()] = channel;
5294 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005295 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005296 sctp_data_channels_.push_back(channel);
5297 channel->SignalClosed.connect(this,
5298 &PeerConnection::OnSctpDataChannelClosed);
5299 }
5300
Steve Anton2d8609c2018-01-23 16:38:46 -08005301 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005302 return channel;
5303}
5304
5305bool PeerConnection::HasDataChannels() const {
5306 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5307}
5308
5309void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005310 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005311 for (const auto& channel : sctp_data_channels_) {
5312 if (channel->id() < 0) {
5313 int sid;
5314 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005315 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5316 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005317 continue;
5318 }
5319 channel->SetSctpSid(sid);
5320 }
5321 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005322 // Since closing modifies the list of channels, we have to do the actual
5323 // closing outside the loop.
5324 for (const auto& channel : channels_to_close) {
5325 channel->CloseAbruptly();
5326 }
deadbeefab9b2d12015-10-14 11:33:11 -07005327}
5328
5329void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005330 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005331 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5332 ++it) {
5333 if (it->get() == channel) {
5334 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005335 // After the closing procedure is done, it's safe to use this ID for
5336 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005337 sid_allocator_.ReleaseSid(channel->id());
5338 }
deadbeefbd292462015-12-14 18:15:29 -08005339 // Since this method is triggered by a signal from the DataChannel,
5340 // we can't free it directly here; we need to free it asynchronously.
5341 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005342 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005343 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5344 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005345 return;
5346 }
5347 }
5348}
5349
deadbeefab9b2d12015-10-14 11:33:11 -07005350void PeerConnection::OnDataChannelDestroyed() {
5351 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5352 // DataChannel may callback to us and try to modify the list.
5353 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5354 temp_rtp_dcs.swap(rtp_data_channels_);
5355 for (const auto& kv : temp_rtp_dcs) {
5356 kv.second->OnTransportChannelDestroyed();
5357 }
5358
5359 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5360 temp_sctp_dcs.swap(sctp_data_channels_);
5361 for (const auto& channel : temp_sctp_dcs) {
5362 channel->OnTransportChannelDestroyed();
5363 }
5364}
5365
5366void PeerConnection::OnDataChannelOpenMessage(
5367 const std::string& label,
5368 const InternalDataChannelInit& config) {
5369 rtc::scoped_refptr<DataChannel> channel(
5370 InternalCreateDataChannel(label, &config));
5371 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005372 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005373 return;
5374 }
5375
deadbeefa601f5c2016-06-06 14:27:39 -07005376 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5377 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005378 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005379 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005380}
5381
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005382bool PeerConnection::HandleOpenMessage_s(
5383 const cricket::ReceiveDataParams& params,
5384 const rtc::CopyOnWriteBuffer& buffer) {
5385 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5386 // Received OPEN message; parse and signal that a new data channel should
5387 // be created.
5388 std::string label;
5389 InternalDataChannelInit config;
5390 config.id = params.ssrc;
5391 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5392 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5393 << params.ssrc;
5394 return true;
5395 }
5396 config.open_handshake_role = InternalDataChannelInit::kAcker;
5397 OnDataChannelOpenMessage(label, config);
5398 return true;
5399 }
5400 return false;
5401}
5402
Steve Anton4171afb2017-11-20 10:20:22 -08005403rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5404PeerConnection::GetAudioTransceiver() const {
5405 // This method only works with Plan B SDP, where there is a single
5406 // audio/video transceiver.
5407 RTC_DCHECK(!IsUnifiedPlan());
5408 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005409 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005410 return transceiver;
5411 }
5412 }
5413 RTC_NOTREACHED();
5414 return nullptr;
5415}
5416
5417rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5418PeerConnection::GetVideoTransceiver() const {
5419 // This method only works with Plan B SDP, where there is a single
5420 // audio/video transceiver.
5421 RTC_DCHECK(!IsUnifiedPlan());
5422 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005423 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005424 return transceiver;
5425 }
5426 }
5427 RTC_NOTREACHED();
5428 return nullptr;
5429}
5430
5431// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5432// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005433bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005434 switch (type) {
5435 case cricket::MEDIA_TYPE_AUDIO:
5436 return !GetAudioTransceiver()->internal()->senders().empty();
5437 case cricket::MEDIA_TYPE_VIDEO:
5438 return !GetVideoTransceiver()->internal()->senders().empty();
5439 case cricket::MEDIA_TYPE_DATA:
5440 return false;
5441 }
5442 RTC_NOTREACHED();
5443 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005444}
5445
Steve Anton4171afb2017-11-20 10:20:22 -08005446rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5447PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005448 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005449 for (auto sender : transceiver->internal()->senders()) {
5450 if (sender->track() == track) {
5451 return sender;
5452 }
5453 }
5454 }
5455 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005456}
5457
Steve Anton4171afb2017-11-20 10:20:22 -08005458rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5459PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005460 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005461 for (auto sender : transceiver->internal()->senders()) {
5462 if (sender->id() == sender_id) {
5463 return sender;
5464 }
5465 }
5466 }
5467 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005468}
5469
Steve Anton4171afb2017-11-20 10:20:22 -08005470rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5471PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005472 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005473 for (auto receiver : transceiver->internal()->receivers()) {
5474 if (receiver->id() == receiver_id) {
5475 return receiver;
5476 }
5477 }
5478 }
5479 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005480}
5481
Steve Anton4171afb2017-11-20 10:20:22 -08005482std::vector<PeerConnection::RtpSenderInfo>*
5483PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5484 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5485 media_type == cricket::MEDIA_TYPE_VIDEO);
5486 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5487 ? &remote_audio_sender_infos_
5488 : &remote_video_sender_infos_;
5489}
5490
5491std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005492 cricket::MediaType media_type) {
5493 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5494 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005495 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5496 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005497}
5498
Steve Anton4171afb2017-11-20 10:20:22 -08005499const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5500 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005501 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005502 const std::string sender_id) const {
5503 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005504 if (sender_info.stream_id == stream_id &&
5505 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005506 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005507 }
5508 }
5509 return nullptr;
5510}
5511
5512DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5513 for (const auto& channel : sctp_data_channels_) {
5514 if (channel->id() == sid) {
5515 return channel;
5516 }
5517 }
5518 return nullptr;
5519}
5520
Karl Wibergfb3be392019-03-22 14:13:22 +01005521PeerConnection::InitializePortAllocatorResult
5522PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005523 const cricket::ServerAddresses& stun_servers,
5524 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005525 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005526 RTC_DCHECK_RUN_ON(network_thread());
5527
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005528 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005529 // To handle both internal and externally created port allocator, we will
5530 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005531 int port_allocator_flags = port_allocator_->flags();
5532 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5533 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5534 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005535 // If the disable-IPv6 flag was specified, we'll not override it
5536 // by experiment.
5537 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005538 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005539 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5540 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005541 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005542 }
5543
zhihuangb09b3f92017-03-07 14:40:51 -08005544 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005545 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005546 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005547 }
5548
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005549 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005550 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005551 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005552 }
5553
honghaiz60347052016-05-31 18:29:12 -07005554 if (configuration.candidate_network_policy ==
5555 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005556 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005557 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005558 }
5559
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005560 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005561 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005562 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5563 }
5564
Karl Wibergfb3be392019-03-22 14:13:22 +01005565 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005566 // No step delay is used while allocating ports.
5567 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005568 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005569 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005570 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005571
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005572 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005573 for (auto& turn_server : turn_servers_copy) {
5574 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005575 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005576 // Call this last since it may create pooled allocator sessions using the
5577 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005578 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005579 stun_servers, std::move(turn_servers_copy),
5580 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5581 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005582 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005583
5584 InitializePortAllocatorResult res;
5585 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5586 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005587}
5588
deadbeef91dd5672016-05-18 16:55:30 -07005589bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005590 const cricket::ServerAddresses& stun_servers,
5591 const std::vector<cricket::RelayServerConfig>& turn_servers,
5592 IceTransportsType type,
5593 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005594 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005595 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005596 absl::optional<int> stun_candidate_keepalive_interval,
5597 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005598 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005599 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005600 // According to JSEP, after setLocalDescription, changing the candidate pool
5601 // size is not allowed, and changing the set of ICE servers will not result
5602 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005603 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005604 port_allocator_->FreezeCandidatePool();
5605 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005606 // Add the custom tls turn servers if they exist.
5607 auto turn_servers_copy = turn_servers;
5608 for (auto& turn_server : turn_servers_copy) {
5609 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5610 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005611 // Call this last since it may create pooled allocator sessions using the
5612 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005613 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005614 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5615 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005616}
5617
Steve Antonba818672017-11-06 10:21:57 -08005618cricket::ChannelManager* PeerConnection::channel_manager() const {
5619 return factory_->channel_manager();
5620}
5621
Elad Alon99c3fe52017-10-13 16:29:40 +02005622bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005623 std::unique_ptr<RtcEventLogOutput> output,
5624 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005625 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005626 if (!event_log_) {
5627 return false;
5628 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005629 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005630}
5631
5632void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005633 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005634 if (event_log_) {
5635 event_log_->StopLogging();
5636 }
ivoc14d5dbe2016-07-04 07:06:55 -07005637}
nisseeaabdf62017-05-05 02:23:02 -07005638
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005639cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005640 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005641 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005642 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005643 if (channel && channel->content_name() == content_name) {
5644 return channel;
5645 }
Steve Anton75737c02017-11-06 10:37:17 -08005646 }
5647 if (rtp_data_channel() &&
5648 rtp_data_channel()->content_name() == content_name) {
5649 return rtp_data_channel();
5650 }
5651 return nullptr;
5652}
5653
5654bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005655 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005656 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005657 RTC_LOG(LS_INFO)
5658 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005659 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005660 return false;
5661 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005662 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005663 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005664 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005665 return false;
5666 }
5667
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005668 absl::optional<rtc::SSLRole> dtls_role;
5669 if (sctp_mid_) {
5670 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5671 } else if (is_caller_) {
5672 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5673 }
Zhi Huange830e682018-03-30 10:48:35 -07005674 if (dtls_role) {
5675 *role = *dtls_role;
5676 return true;
5677 }
5678 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005679}
5680
5681bool PeerConnection::GetSslRole(const std::string& content_name,
5682 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005683 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005684 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005685 RTC_LOG(LS_INFO)
5686 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005687 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005688 return false;
5689 }
5690
Zhi Huange830e682018-03-30 10:48:35 -07005691 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5692 if (dtls_role) {
5693 *role = *dtls_role;
5694 return true;
5695 }
5696 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005697}
5698
Steve Antonf8470812017-12-04 10:46:21 -08005699void PeerConnection::SetSessionError(SessionError error,
5700 const std::string& error_desc) {
5701 RTC_DCHECK_RUN_ON(signaling_thread());
5702 if (error != session_error_) {
5703 session_error_ = error;
5704 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005705 }
5706}
5707
Zhi Huange830e682018-03-30 10:48:35 -07005708RTCError PeerConnection::UpdateSessionState(
5709 SdpType type,
5710 cricket::ContentSource source,
5711 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005712 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005713
5714 // If there's already a pending error then no state transition should happen.
5715 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005716 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005717
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005718 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005719 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005720 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005721 }
5722
5723 // Update the signaling state according to the specified state machine (see
5724 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005725 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005726 ChangeSignalingState(source == cricket::CS_LOCAL
5727 ? PeerConnectionInterface::kHaveLocalOffer
5728 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005729 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005730 ChangeSignalingState(source == cricket::CS_LOCAL
5731 ? PeerConnectionInterface::kHaveLocalPrAnswer
5732 : PeerConnectionInterface::kHaveRemotePrAnswer);
5733 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005734 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005735 ChangeSignalingState(PeerConnectionInterface::kStable);
5736 }
5737
5738 // Update internal objects according to the session description's media
5739 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005740 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005741 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005742 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005743 }
5744
Steve Anton8a006912017-12-04 15:25:56 -08005745 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005746}
5747
Steve Anton8a006912017-12-04 15:25:56 -08005748RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005749 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005750 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005751 const SessionDescriptionInterface* sdesc =
5752 (source == cricket::CS_LOCAL ? local_description()
5753 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005754 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005755
5756 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005757 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005758 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005759 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005760 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005761 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005762 continue;
5763 }
5764 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005765 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005766 if (!content_desc) {
5767 continue;
5768 }
5769 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005770 bool success = (source == cricket::CS_LOCAL)
5771 ? channel->SetLocalContent(content_desc, type, &error)
5772 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005773 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005774 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005775 }
5776 }
5777
5778 // If using the RtpDataChannel, push down the new SDP section for it too.
5779 if (rtp_data_channel_) {
5780 const ContentInfo* data_content =
5781 cricket::GetFirstDataContent(sdesc->description());
5782 if (data_content && !data_content->rejected) {
5783 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005784 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005785 if (data_desc) {
5786 std::string error;
5787 bool success =
5788 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005789 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005790 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005791 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005793 }
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
5795 }
5796 }
Steve Antoned10bd92017-12-05 10:52:59 -08005797
Steve Anton75737c02017-11-06 10:37:17 -08005798 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5799 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005800 if (sctp_transport_ && local_description() && remote_description()) {
5801 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5802 local_description()->description());
5803 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5804 remote_description()->description());
5805 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005806 int max_message_size;
5807 // A remote max message size of zero means "any size supported".
5808 // We configure the connection with our own max message size.
5809 if (remote_sctp_description->max_message_size() == 0) {
5810 max_message_size = local_sctp_description->max_message_size();
5811 } else {
5812 max_message_size =
5813 std::min(local_sctp_description->max_message_size(),
5814 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005815 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005816 sctp_transport_->Start(local_sctp_description->port(),
5817 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005818 }
Steve Anton75737c02017-11-06 10:37:17 -08005819 }
Steve Antoned10bd92017-12-05 10:52:59 -08005820
Steve Anton8a006912017-12-04 15:25:56 -08005821 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005822}
5823
Steve Anton8a006912017-12-04 15:25:56 -08005824RTCError PeerConnection::PushdownTransportDescription(
5825 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005826 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005827 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005828
Zhi Huange830e682018-03-30 10:48:35 -07005829 if (source == cricket::CS_LOCAL) {
5830 const SessionDescriptionInterface* sdesc = local_description();
5831 RTC_DCHECK(sdesc);
5832 return transport_controller_->SetLocalDescription(type,
5833 sdesc->description());
5834 } else {
5835 const SessionDescriptionInterface* sdesc = remote_description();
5836 RTC_DCHECK(sdesc);
5837 return transport_controller_->SetRemoteDescription(type,
5838 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005839 }
Steve Anton75737c02017-11-06 10:37:17 -08005840}
5841
5842bool PeerConnection::GetTransportDescription(
5843 const SessionDescription* description,
5844 const std::string& content_name,
5845 cricket::TransportDescription* tdesc) {
5846 if (!description || !tdesc) {
5847 return false;
5848 }
5849 const TransportInfo* transport_info =
5850 description->GetTransportInfoByName(content_name);
5851 if (!transport_info) {
5852 return false;
5853 }
5854 *tdesc = transport_info->description;
5855 return true;
5856}
5857
Steve Anton75737c02017-11-06 10:37:17 -08005858cricket::IceConfig PeerConnection::ParseIceConfig(
5859 const PeerConnectionInterface::RTCConfiguration& config) const {
5860 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005861 switch (config.continual_gathering_policy) {
5862 case PeerConnectionInterface::GATHER_ONCE:
5863 gathering_policy = cricket::GATHER_ONCE;
5864 break;
5865 case PeerConnectionInterface::GATHER_CONTINUALLY:
5866 gathering_policy = cricket::GATHER_CONTINUALLY;
5867 break;
5868 default:
5869 RTC_NOTREACHED();
5870 gathering_policy = cricket::GATHER_ONCE;
5871 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005872
Steve Anton75737c02017-11-06 10:37:17 -08005873 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005874 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5875 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005876 ice_config.prioritize_most_likely_candidate_pairs =
5877 config.prioritize_most_likely_ice_candidate_pairs;
5878 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005879 RTCConfigurationToIceConfigOptionalInt(
5880 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005881 ice_config.continual_gathering_policy = gathering_policy;
5882 ice_config.presume_writable_when_fully_relayed =
5883 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005884 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5885 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005886 ice_config.ice_check_interval_strong_connectivity =
5887 config.ice_check_interval_strong_connectivity;
5888 ice_config.ice_check_interval_weak_connectivity =
5889 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005890 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005891 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5892 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005893 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005894 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005895 ice_config.regather_all_networks_interval_range =
5896 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005897 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005898 return ice_config;
5899}
5900
Steve Anton75737c02017-11-06 10:37:17 -08005901bool PeerConnection::SendData(const cricket::SendDataParams& params,
5902 const rtc::CopyOnWriteBuffer& payload,
5903 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005904 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005905 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5906 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5907 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005908 return false;
5909 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005910 if (media_transport_) {
5911 SendDataParams send_params;
5912 send_params.type = ToWebrtcDataMessageType(params.type);
5913 send_params.ordered = params.ordered;
5914 if (params.max_rtx_count >= 0) {
5915 send_params.max_rtx_count = params.max_rtx_count;
5916 } else if (params.max_rtx_ms >= 0) {
5917 send_params.max_rtx_ms = params.max_rtx_ms;
5918 }
5919 return media_transport_->SendData(params.sid, send_params, payload).ok();
5920 }
Steve Anton75737c02017-11-06 10:37:17 -08005921 return rtp_data_channel_
5922 ? rtp_data_channel_->SendData(params, payload, result)
5923 : network_thread()->Invoke<bool>(
5924 RTC_FROM_HERE,
5925 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005926 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005927}
5928
5929bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005930 RTC_DCHECK_RUN_ON(signaling_thread());
5931 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005932 // Don't log an error here, because DataChannels are expected to call
5933 // ConnectDataChannel in this state. It's the only way to initially tell
5934 // whether or not the underlying transport is ready.
5935 return false;
5936 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005937 if (media_transport_) {
5938 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5939 &DataChannel::OnChannelReady);
5940 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5941 &DataChannel::OnDataReceived);
5942 SignalMediaTransportChannelClosing_s.connect(
5943 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5944 SignalMediaTransportChannelClosed_s.connect(
5945 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5946 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005947 rtp_data_channel_->SignalReadyToSendData.connect(
5948 webrtc_data_channel, &DataChannel::OnChannelReady);
5949 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5950 &DataChannel::OnDataReceived);
5951 } else {
5952 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5953 &DataChannel::OnChannelReady);
5954 SignalSctpDataReceived.connect(webrtc_data_channel,
5955 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005956 SignalSctpClosingProcedureStartedRemotely.connect(
5957 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5958 SignalSctpClosingProcedureComplete.connect(
5959 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005960 }
5961 return true;
5962}
5963
5964void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005965 RTC_DCHECK_RUN_ON(signaling_thread());
5966 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005967 RTC_LOG(LS_ERROR)
5968 << "DisconnectDataChannel called when rtp_data_channel_ and "
5969 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005970 return;
5971 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005972 if (media_transport_) {
5973 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5974 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5975 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5976 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5977 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005978 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5979 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5980 } else {
5981 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5982 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005983 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5984 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005985 }
5986}
5987
5988void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005989 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005990 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005991 return;
5992 }
Steve Anton75737c02017-11-06 10:37:17 -08005993 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005994 RTC_LOG(LS_ERROR)
5995 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005996 return;
5997 }
5998 network_thread()->Invoke<void>(
5999 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006000 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006001}
6002
6003void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006004 if (media_transport_) {
6005 media_transport_->CloseChannel(sid);
6006 return;
6007 }
Steve Anton75737c02017-11-06 10:37:17 -08006008 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006009 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006010 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006011 return;
6012 }
6013 network_thread()->Invoke<void>(
6014 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006015 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006016}
6017
6018bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006019 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006020 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006021 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08006022 sctp_ready_to_send_data_;
6023}
6024
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006025void PeerConnection::OnDataReceived(int channel_id,
6026 DataMessageType type,
6027 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006028 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006029 cricket::ReceiveDataParams params;
6030 params.sid = channel_id;
6031 params.type = ToCricketDataMessageType(type);
6032 media_transport_invoker_->AsyncInvoke<void>(
6033 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6034 RTC_DCHECK_RUN_ON(signaling_thread());
6035 if (!HandleOpenMessage_s(params, buffer)) {
6036 SignalMediaTransportReceivedData_s(params, buffer);
6037 }
6038 });
6039}
6040
6041void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006042 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006043 media_transport_invoker_->AsyncInvoke<void>(
6044 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6045 RTC_DCHECK_RUN_ON(signaling_thread());
6046 SignalMediaTransportChannelClosing_s(channel_id);
6047 });
6048}
6049
6050void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006051 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006052 media_transport_invoker_->AsyncInvoke<void>(
6053 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6054 RTC_DCHECK_RUN_ON(signaling_thread());
6055 SignalMediaTransportChannelClosed_s(channel_id);
6056 });
6057}
6058
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006059absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006060 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006061 if (sctp_mid_ && transport_controller_) {
6062 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6063 if (dtls_transport) {
6064 return dtls_transport->transport_name();
6065 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006066 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006067 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006068 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006069}
6070
Qingsi Wang72a43a12018-02-20 16:03:18 -08006071cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6072 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006073 network_thread()->Invoke<void>(
6074 RTC_FROM_HERE,
6075 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6076 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006077 return candidate_states_list;
6078}
6079
Steve Anton5dfde182018-02-06 10:34:40 -08006080std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6081 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006082 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006083 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006084 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006085 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006086 if (channel) {
6087 transport_names_by_mid[channel->content_name()] =
6088 channel->transport_name();
6089 }
Steve Anton75737c02017-11-06 10:37:17 -08006090 }
Steve Anton5dfde182018-02-06 10:34:40 -08006091 if (rtp_data_channel_) {
6092 transport_names_by_mid[rtp_data_channel_->content_name()] =
6093 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006094 }
6095 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006096 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006097 RTC_DCHECK(transport_name);
6098 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006099 }
Steve Anton5dfde182018-02-06 10:34:40 -08006100 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006101}
6102
Steve Anton5dfde182018-02-06 10:34:40 -08006103std::map<std::string, cricket::TransportStats>
6104PeerConnection::GetTransportStatsByNames(
6105 const std::set<std::string>& transport_names) {
6106 if (!network_thread()->IsCurrent()) {
6107 return network_thread()
6108 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6109 RTC_FROM_HERE,
6110 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006111 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006112 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006113 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6114 for (const std::string& transport_name : transport_names) {
6115 cricket::TransportStats transport_stats;
6116 bool success =
6117 transport_controller_->GetStats(transport_name, &transport_stats);
6118 if (success) {
6119 transport_stats_by_name[transport_name] = std::move(transport_stats);
6120 } else {
6121 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6122 << transport_name;
6123 }
6124 }
6125 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006126}
6127
6128bool PeerConnection::GetLocalCertificate(
6129 const std::string& transport_name,
6130 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006131 if (!certificate) {
6132 return false;
6133 }
6134 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6135 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006136}
6137
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006138std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006139 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006140 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006141}
6142
6143cricket::DataChannelType PeerConnection::data_channel_type() const {
6144 return data_channel_type_;
6145}
6146
6147bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006148 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006149 return pending_ice_restarts_.find(content_name) !=
6150 pending_ice_restarts_.end();
6151}
6152
Steve Anton75737c02017-11-06 10:37:17 -08006153bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6154 return transport_controller_->NeedsIceRestart(content_name);
6155}
6156
6157void PeerConnection::OnCertificateReady(
6158 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6159 transport_controller_->SetLocalCertificate(certificate);
6160}
6161
6162void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006163 SetSessionError(SessionError::kTransport,
6164 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006165}
6166
Alex Loiko9289eda2018-11-23 16:18:59 +00006167void PeerConnection::OnTransportControllerConnectionState(
6168 cricket::IceConnectionState state) {
6169 switch (state) {
6170 case cricket::kIceConnectionConnecting:
6171 // If the current state is Connected or Completed, then there were
6172 // writable channels but now there are not, so the next state must
6173 // be Disconnected.
6174 // kIceConnectionConnecting is currently used as the default,
6175 // un-connected state by the TransportController, so its only use is
6176 // detecting disconnections.
6177 if (ice_connection_state_ ==
6178 PeerConnectionInterface::kIceConnectionConnected ||
6179 ice_connection_state_ ==
6180 PeerConnectionInterface::kIceConnectionCompleted) {
6181 SetIceConnectionState(
6182 PeerConnectionInterface::kIceConnectionDisconnected);
6183 }
6184 break;
6185 case cricket::kIceConnectionFailed:
6186 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6187 break;
6188 case cricket::kIceConnectionConnected:
6189 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6190 "all transports are writable.";
6191 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6192 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6193 break;
6194 case cricket::kIceConnectionCompleted:
6195 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6196 "all transports are complete.";
6197 if (ice_connection_state_ !=
6198 PeerConnectionInterface::kIceConnectionConnected) {
6199 // If jumping directly from "checking" to "connected",
6200 // signal "connected" first.
6201 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6202 }
6203 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6204 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6205 ReportTransportStats();
6206 break;
6207 default:
6208 RTC_NOTREACHED();
6209 }
6210}
6211
Steve Anton75737c02017-11-06 10:37:17 -08006212void PeerConnection::OnTransportControllerCandidatesGathered(
6213 const std::string& transport_name,
6214 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006215 int sdp_mline_index;
6216 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006217 RTC_LOG(LS_ERROR)
6218 << "OnTransportControllerCandidatesGathered: content name "
6219 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006220 return;
6221 }
6222
6223 for (cricket::Candidates::const_iterator citer = candidates.begin();
6224 citer != candidates.end(); ++citer) {
6225 // Use transport_name as the candidate media id.
6226 std::unique_ptr<JsepIceCandidate> candidate(
6227 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6228 if (local_description()) {
6229 mutable_local_description()->AddCandidate(candidate.get());
6230 }
6231 OnIceCandidate(std::move(candidate));
6232 }
6233}
6234
Eldar Relloda13ea22019-06-01 12:23:43 +03006235void PeerConnection::OnTransportControllerCandidateError(
6236 const cricket::IceCandidateErrorEvent& event) {
6237 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6238 event.error_text);
6239}
6240
Steve Anton75737c02017-11-06 10:37:17 -08006241void PeerConnection::OnTransportControllerCandidatesRemoved(
6242 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006243 // Sanity check.
6244 for (const cricket::Candidate& candidate : candidates) {
6245 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006246 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006247 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006248 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006249 return;
6250 }
6251 }
6252
6253 if (local_description()) {
6254 mutable_local_description()->RemoveCandidates(candidates);
6255 }
6256 OnIceCandidatesRemoved(candidates);
6257}
6258
Alex Drake00c7ecf2019-08-06 10:54:47 -07006259void PeerConnection::OnTransportControllerCandidateChanged(
6260 const cricket::CandidatePairChangeEvent& event) {
6261 OnSelectedCandidatePairChanged(event);
6262}
6263
Steve Anton75737c02017-11-06 10:37:17 -08006264void PeerConnection::OnTransportControllerDtlsHandshakeError(
6265 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006266 RTC_HISTOGRAM_ENUMERATION(
6267 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6268 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006269}
6270
Steve Antoned10bd92017-12-05 10:52:59 -08006271void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006272 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006273 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006274 if (channel && !channel->enabled()) {
6275 channel->Enable(true);
6276 }
Steve Anton75737c02017-11-06 10:37:17 -08006277 }
6278
Steve Anton4171afb2017-11-20 10:20:22 -08006279 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006280 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006281 }
Steve Anton75737c02017-11-06 10:37:17 -08006282}
6283
6284// Returns the media index for a local ice candidate given the content name.
6285bool PeerConnection::GetLocalCandidateMediaIndex(
6286 const std::string& content_name,
6287 int* sdp_mline_index) {
6288 if (!local_description() || !sdp_mline_index) {
6289 return false;
6290 }
6291
6292 bool content_found = false;
6293 const ContentInfos& contents = local_description()->description()->contents();
6294 for (size_t index = 0; index < contents.size(); ++index) {
6295 if (contents[index].name == content_name) {
6296 *sdp_mline_index = static_cast<int>(index);
6297 content_found = true;
6298 break;
6299 }
6300 }
6301 return content_found;
6302}
6303
6304bool PeerConnection::UseCandidatesInSessionDescription(
6305 const SessionDescriptionInterface* remote_desc) {
6306 if (!remote_desc) {
6307 return true;
6308 }
6309 bool ret = true;
6310
6311 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6312 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6313 for (size_t n = 0; n < candidates->count(); ++n) {
6314 const IceCandidateInterface* candidate = candidates->at(n);
6315 bool valid = false;
6316 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6317 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006318 RTC_LOG(LS_INFO)
6319 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006320 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006321 }
6322 continue;
6323 }
6324 ret = UseCandidate(candidate);
6325 if (!ret) {
6326 break;
6327 }
6328 }
6329 }
6330 return ret;
6331}
6332
6333bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006334 RTCErrorOr<const cricket::ContentInfo*> result =
6335 FindContentInfo(remote_description(), candidate);
6336 if (!result.ok()) {
6337 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6338 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006339 return false;
6340 }
Steve Anton75737c02017-11-06 10:37:17 -08006341 std::vector<cricket::Candidate> candidates;
6342 candidates.push_back(candidate->candidate());
6343 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006344 RTCError error = transport_controller_->AddRemoteCandidates(
6345 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006346 if (error.ok()) {
6347 // Candidates successfully submitted for checking.
6348 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6349 ice_connection_state_ ==
6350 PeerConnectionInterface::kIceConnectionDisconnected) {
6351 // If state is New, then the session has just gotten its first remote ICE
6352 // candidates, so go to Checking.
6353 // If state is Disconnected, the session is re-using old candidates or
6354 // receiving additional ones, so go to Checking.
6355 // If state is Connected, stay Connected.
6356 // TODO(bemasc): If state is Connected, and the new candidates are for a
6357 // newly added transport, then the state actually _should_ move to
6358 // checking. Add a way to distinguish that case.
6359 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6360 }
6361 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006362 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006363 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006364 }
6365 return true;
6366}
6367
Guido Urdaneta41633172019-05-23 20:12:29 +02006368RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6369 const SessionDescriptionInterface* description,
6370 const IceCandidateInterface* candidate) {
6371 if (candidate->sdp_mline_index() >= 0) {
6372 size_t mediacontent_index =
6373 static_cast<size_t>(candidate->sdp_mline_index());
6374 size_t content_size = description->description()->contents().size();
6375 if (mediacontent_index < content_size) {
6376 return &description->description()->contents()[mediacontent_index];
6377 } else {
6378 return RTCError(RTCErrorType::INVALID_RANGE,
6379 "Media line index (" +
6380 rtc::ToString(candidate->sdp_mline_index()) +
6381 ") out of range (number of mlines: " +
6382 rtc::ToString(content_size) + ").");
6383 }
6384 } else if (!candidate->sdp_mid().empty()) {
6385 auto& contents = description->description()->contents();
6386 auto it = absl::c_find_if(
6387 contents, [candidate](const cricket::ContentInfo& content_info) {
6388 return content_info.mid() == candidate->sdp_mid();
6389 });
6390 if (it == contents.end()) {
6391 return RTCError(
6392 RTCErrorType::INVALID_PARAMETER,
6393 "Mid " + candidate->sdp_mid() +
6394 " specified but no media section with that mid found.");
6395 } else {
6396 return &*it;
6397 }
6398 }
6399
6400 return RTCError(RTCErrorType::INVALID_PARAMETER,
6401 "Neither sdp_mline_index nor sdp_mid specified.");
6402}
6403
Steve Anton75737c02017-11-06 10:37:17 -08006404void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006405 // Destroy video channel first since it may have a pointer to the
6406 // voice channel.
6407 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006408 if (!video_info || video_info->rejected) {
6409 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006410 }
6411
Steve Anton6fec8802017-12-04 10:37:29 -08006412 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6413 if (!audio_info || audio_info->rejected) {
6414 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006415 }
6416
6417 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6418 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006419 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006420 }
6421}
6422
Steve Antondcc3c022017-12-22 16:02:54 -08006423RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6424 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006425 const cricket::ContentGroup* bundle_group = nullptr;
6426 if (configuration_.bundle_policy ==
6427 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006428 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006429 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6431 "max-bundle configured but session description "
6432 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006433 }
6434 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006435 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006436}
6437
6438RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006439 // Creating the media channels. Transports should already have been created
6440 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006441 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006442 if (voice && !voice->rejected &&
6443 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006444 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006445 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006446 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6447 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006448 }
6449 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6450 }
6451
Steve Antondcc3c022017-12-22 16:02:54 -08006452 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006453 if (video && !video->rejected &&
6454 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006455 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006456 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006457 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6458 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006459 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006460 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006461 }
6462
Steve Antondcc3c022017-12-22 16:02:54 -08006463 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006464 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006465 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006466 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006467 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6468 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006469 }
6470 }
6471
Steve Anton8a006912017-12-04 15:25:56 -08006472 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006473}
6474
Steve Anton4171afb2017-11-20 10:20:22 -08006475// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006476cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006477 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006478 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006479 MediaTransportConfig media_transport_config =
6480 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006481
Steve Anton75737c02017-11-06 10:37:17 -08006482 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006483 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006484 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6485 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006486 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006487 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006488 }
Steve Anton75737c02017-11-06 10:37:17 -08006489 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6490 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006491 voice_channel->SignalSentPacket.connect(this,
6492 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006493 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006494
Steve Antoneda6ccd2017-12-04 10:21:55 -08006495 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006496}
6497
Steve Anton4171afb2017-11-20 10:20:22 -08006498// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006499cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006500 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006501 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006502 MediaTransportConfig media_transport_config =
6503 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006504
Steve Anton75737c02017-11-06 10:37:17 -08006505 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006506 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006507 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6508 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006509 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006510 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006511 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006512 }
Steve Anton75737c02017-11-06 10:37:17 -08006513 video_channel->SignalDtlsSrtpSetupFailure.connect(
6514 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006515 video_channel->SignalSentPacket.connect(this,
6516 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006517 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006518
Steve Antoneda6ccd2017-12-04 10:21:55 -08006519 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006520}
6521
Zhi Huange830e682018-03-30 10:48:35 -07006522bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006523 switch (data_channel_type_) {
6524 case cricket::DCT_MEDIA_TRANSPORT:
6525 if (network_thread()->Invoke<bool>(
6526 RTC_FROM_HERE,
6527 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6528 this, mid))) {
6529 for (const auto& channel : sctp_data_channels_) {
6530 channel->OnTransportChannelCreated();
6531 }
6532 return true;
6533 }
Steve Anton75737c02017-11-06 10:37:17 -08006534 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006535 case cricket::DCT_SCTP:
6536 if (!sctp_factory_) {
6537 RTC_LOG(LS_ERROR)
6538 << "Trying to create SCTP transport, but didn't compile with "
6539 "SCTP support (HAVE_SCTP)";
6540 return false;
6541 }
6542 if (!network_thread()->Invoke<bool>(
6543 RTC_FROM_HERE,
6544 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6545 return false;
6546 }
6547 for (const auto& channel : sctp_data_channels_) {
6548 channel->OnTransportChannelCreated();
6549 }
6550 return true;
6551 case cricket::DCT_RTP:
6552 default:
6553 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6554 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6555 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006556 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006557 if (!rtp_data_channel_) {
6558 return false;
6559 }
6560 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6561 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6562 rtp_data_channel_->SignalSentPacket.connect(
6563 this, &PeerConnection::OnSentPacket_w);
6564 rtp_data_channel_->SetRtpTransport(rtp_transport);
6565 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006566 }
6567
Steve Anton75737c02017-11-06 10:37:17 -08006568 return true;
6569}
6570
6571Call::Stats PeerConnection::GetCallStats() {
6572 if (!worker_thread()->IsCurrent()) {
6573 return worker_thread()->Invoke<Call::Stats>(
6574 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6575 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006576 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006577 if (call_) {
6578 return call_->GetStats();
6579 } else {
6580 return Call::Stats();
6581 }
6582}
6583
Zhi Huange830e682018-03-30 10:48:35 -07006584bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006585 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006586 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006587 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6588 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006589 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006590 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006591 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006592 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6593 sctp_factory_->CreateSctpTransport(dtls_transport);
6594 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006595 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006596 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006597 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006598 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006599 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006600 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6601 // another thread. Would be nice if there was a helper class similar to
6602 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6603 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006604 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006605 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006606 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006607 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006608 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006609 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6610 std::move(cricket_sctp_transport));
6611 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006612 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006613}
6614
6615void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006616 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006617 sctp_transport_->Clear();
6618 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006619 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006620 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006621}
6622
6623void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006624 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006625 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006626 // Note: Cannot use rtc::Bind here because it will grab a reference to
6627 // PeerConnection and potentially cause PeerConnection to live longer than
6628 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6629 // be destroyed before PeerConnection is destroyed, and at that point all
6630 // pending tasks will be cleared.
6631 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6632 OnSctpTransportReadyToSendData_s(true);
6633 });
6634}
6635
6636void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006637 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006638 sctp_ready_to_send_data_ = ready;
6639 SignalSctpReadyToSendData(ready);
6640}
6641
6642void PeerConnection::OnSctpTransportDataReceived_n(
6643 const cricket::ReceiveDataParams& params,
6644 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006645 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006646 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006647 // Note: Cannot use rtc::Bind here because it will grab a reference to
6648 // PeerConnection and potentially cause PeerConnection to live longer than
6649 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6650 // be destroyed before PeerConnection is destroyed, and at that point all
6651 // pending tasks will be cleared.
6652 sctp_invoker_->AsyncInvoke<void>(
6653 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6654 OnSctpTransportDataReceived_s(params, payload);
6655 });
6656}
6657
6658void PeerConnection::OnSctpTransportDataReceived_s(
6659 const cricket::ReceiveDataParams& params,
6660 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006661 RTC_DCHECK_RUN_ON(signaling_thread());
6662 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006663 SignalSctpDataReceived(params, payload);
6664 }
6665}
6666
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006667void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006668 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006669 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006670 sctp_invoker_->AsyncInvoke<void>(
6671 RTC_FROM_HERE, signaling_thread(),
6672 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006673 &SignalSctpClosingProcedureStartedRemotely, sid));
6674}
6675
6676void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006677 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006678 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006679 sctp_invoker_->AsyncInvoke<void>(
6680 RTC_FROM_HERE, signaling_thread(),
6681 rtc::Bind(&sigslot::signal1<int>::operator(),
6682 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006683}
6684
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006685bool PeerConnection::SetupMediaTransportForDataChannels_n(
6686 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006687 media_transport_ =
6688 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006689 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006690 RTC_LOG(LS_ERROR)
6691 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006692 return false;
6693 }
6694
6695 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6696 media_transport_->SetDataSink(this);
6697 media_transport_data_mid_ = mid;
6698 transport_controller_->SignalMediaTransportStateChanged.connect(
6699 this, &PeerConnection::OnMediaTransportStateChanged_n);
6700 // Check the initial state right away, in case transport is already writable.
6701 OnMediaTransportStateChanged_n();
6702 return true;
6703}
6704
6705void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6706 if (!media_transport_) {
6707 return;
6708 }
6709 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6710 media_transport_data_mid_.reset();
6711 media_transport_->SetDataSink(nullptr);
6712 media_transport_invoker_ = nullptr;
6713 media_transport_ = nullptr;
6714}
6715
6716void PeerConnection::OnMediaTransportStateChanged_n() {
6717 if (!media_transport_data_mid_ ||
6718 transport_controller_->GetMediaTransportState(
6719 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6720 return;
6721 }
6722 media_transport_invoker_->AsyncInvoke<void>(
6723 RTC_FROM_HERE, signaling_thread(), [this] {
6724 RTC_DCHECK_RUN_ON(signaling_thread());
6725 media_transport_ready_to_send_data_ = true;
6726 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6727 });
6728}
6729
Steve Anton75737c02017-11-06 10:37:17 -08006730// Returns false if bundle is enabled and rtcp_mux is disabled.
6731bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6732 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6733 if (!bundle_enabled)
6734 return true;
6735
6736 const cricket::ContentGroup* bundle_group =
6737 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6738 RTC_DCHECK(bundle_group != NULL);
6739
6740 const cricket::ContentInfos& contents = desc->contents();
6741 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6742 citer != contents.end(); ++citer) {
6743 const cricket::ContentInfo* content = (&*citer);
6744 RTC_DCHECK(content != NULL);
6745 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006746 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006747 if (!HasRtcpMuxEnabled(content))
6748 return false;
6749 }
6750 }
6751 // RTCP-MUX is enabled in all the contents.
6752 return true;
6753}
6754
6755bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006756 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006757}
6758
Steve Anton06817cd2018-12-18 15:55:30 -08006759static RTCError ValidateMids(const cricket::SessionDescription& description) {
6760 std::set<std::string> mids;
6761 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006762 if (content.name.empty()) {
6763 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6764 "A media section is missing a MID attribute.");
6765 }
Steve Anton06817cd2018-12-18 15:55:30 -08006766 if (!mids.insert(content.name).second) {
6767 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6768 "Duplicate a=mid value '" + content.name + "'.");
6769 }
6770 }
6771 return RTCError::OK();
6772}
6773
Steve Anton8a006912017-12-04 15:25:56 -08006774RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006775 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006776 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006777 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006778 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006779 }
6780
6781 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006782 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006783 }
6784
Steve Anton3828c062017-12-06 10:34:51 -08006785 SdpType type = sdesc->GetType();
6786 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6787 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006788 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006789 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006790 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006791 }
6792
Steve Anton06817cd2018-12-18 15:55:30 -08006793 RTCError error = ValidateMids(*sdesc->description());
6794 if (!error.ok()) {
6795 return error;
6796 }
6797
Steve Anton75737c02017-11-06 10:37:17 -08006798 // Verify crypto settings.
6799 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006800 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6801 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006802 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006803 if (!crypto_error.ok()) {
6804 return crypto_error;
6805 }
Steve Anton75737c02017-11-06 10:37:17 -08006806 }
6807
6808 // Verify ice-ufrag and ice-pwd.
6809 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006810 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6811 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006812 }
6813
6814 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006815 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6816 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006817 }
6818
6819 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6820 // m-lines that do not rtcp-mux enabled.
6821
6822 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006823 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006824 // With an answer we want to compare the new answer session description with
6825 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006826 const cricket::SessionDescription* offer_desc =
6827 (source == cricket::CS_LOCAL) ? remote_description()->description()
6828 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006829 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6830 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6831 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006832 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6833 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006834 }
6835 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006836 // The re-offers should respect the order of m= sections in current
6837 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006838 // With a re-offer, either the current local or current remote descriptions
6839 // could be the most up to date, so we would like to check against both of
6840 // them if they exist. It could be the case that one of them has a 0 port
6841 // for a media section, but the other does not. This is important to check
6842 // against in the case that we are recycling an m= section.
6843 const cricket::SessionDescription* current_desc = nullptr;
6844 const cricket::SessionDescription* secondary_current_desc = nullptr;
6845 if (local_description()) {
6846 current_desc = local_description()->description();
6847 if (remote_description()) {
6848 secondary_current_desc = remote_description()->description();
6849 }
6850 } else if (remote_description()) {
6851 current_desc = remote_description()->description();
6852 }
Steve Anton75737c02017-11-06 10:37:17 -08006853 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006854 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6855 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006856 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6857 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006858 }
6859 }
6860
Steve Antonba42e992018-04-09 14:10:01 -07006861 if (IsUnifiedPlan()) {
6862 // Ensure that each audio and video media section has at most one
6863 // "StreamParams". This will return an error if receiving a session
6864 // description from a "Plan B" endpoint which adds multiple tracks of the
6865 // same type. With Unified Plan, there can only be at most one track per
6866 // media section.
6867 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006868 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006869 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6870 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6871 desc.streams().size() > 1u) {
6872 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6873 "Media section has more than one track specified "
6874 "with a=ssrc lines which is not supported with "
6875 "Unified Plan.");
6876 }
6877 }
6878 }
6879
Steve Anton8a006912017-12-04 15:25:56 -08006880 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006881}
6882
Steve Anton3828c062017-12-06 10:34:51 -08006883bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006884 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006885 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006886 return (state == PeerConnectionInterface::kStable) ||
6887 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006888 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006889 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006890 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6891 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6892 }
6893}
6894
Steve Anton3828c062017-12-06 10:34:51 -08006895bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006896 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006897 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006898 return (state == PeerConnectionInterface::kStable) ||
6899 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006900 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006901 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006902 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6903 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6904 }
6905}
6906
Steve Antonf8470812017-12-04 10:46:21 -08006907const char* PeerConnection::SessionErrorToString(SessionError error) const {
6908 switch (error) {
6909 case SessionError::kNone:
6910 return "ERROR_NONE";
6911 case SessionError::kContent:
6912 return "ERROR_CONTENT";
6913 case SessionError::kTransport:
6914 return "ERROR_TRANSPORT";
6915 }
6916 RTC_NOTREACHED();
6917 return "";
6918}
6919
Steve Anton75737c02017-11-06 10:37:17 -08006920std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006921 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006922 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6923 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006924 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006925}
6926
Steve Anton8e20f172018-03-06 10:55:04 -08006927void PeerConnection::ReportSdpFormatReceived(
6928 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006929 int num_audio_mlines = 0;
6930 int num_video_mlines = 0;
6931 int num_audio_tracks = 0;
6932 int num_video_tracks = 0;
6933 for (const ContentInfo& content : remote_offer.description()->contents()) {
6934 cricket::MediaType media_type = content.media_description()->type();
6935 int num_tracks = std::max(
6936 1, static_cast<int>(content.media_description()->streams().size()));
6937 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6938 num_audio_mlines += 1;
6939 num_audio_tracks += num_tracks;
6940 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6941 num_video_mlines += 1;
6942 num_video_tracks += num_tracks;
6943 }
6944 }
6945 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6946 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6947 format = kSdpFormatReceivedComplexUnifiedPlan;
6948 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6949 format = kSdpFormatReceivedComplexPlanB;
6950 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6951 format = kSdpFormatReceivedSimple;
6952 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006953 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6954 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006955}
6956
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006957void PeerConnection::NoteUsageEvent(UsageEvent event) {
6958 RTC_DCHECK_RUN_ON(signaling_thread());
6959 usage_event_accumulator_ |= static_cast<int>(event);
6960}
6961
6962void PeerConnection::ReportUsagePattern() const {
6963 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006964 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6965 usage_event_accumulator_,
6966 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006967 const int bad_bits =
6968 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6969 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6970 const int good_bits =
6971 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6972 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6973 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6974 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6975 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006976 // If called after close(), we can't report, because observer may have
6977 // been deallocated, and therefore pointer is null. Write to log instead.
6978 if (observer_) {
6979 Observer()->OnInterestingUsage(usage_event_accumulator_);
6980 } else {
6981 RTC_LOG(LS_INFO) << "Interesting usage signature "
6982 << usage_event_accumulator_
6983 << " observed after observer shutdown";
6984 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006985 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006986}
6987
Steve Anton0ffaaa22018-02-23 10:31:30 -08006988void PeerConnection::ReportNegotiatedSdpSemantics(
6989 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006990 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006991 switch (answer.description()->msid_signaling()) {
6992 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006993 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006994 break;
6995 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006996 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006997 break;
6998 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006999 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007000 break;
7001 case cricket::kMsidSignalingMediaSection |
7002 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007003 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007004 break;
7005 default:
7006 RTC_NOTREACHED();
7007 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007008 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7009 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007010}
7011
Steve Anton75737c02017-11-06 10:37:17 -08007012// We need to check the local/remote description for the Transport instead of
7013// the session, because a new Transport added during renegotiation may have
7014// them unset while the session has them set from the previous negotiation.
7015// Not doing so may trigger the auto generation of transport description and
7016// mess up DTLS identity information, ICE credential, etc.
7017bool PeerConnection::ReadyToUseRemoteCandidate(
7018 const IceCandidateInterface* candidate,
7019 const SessionDescriptionInterface* remote_desc,
7020 bool* valid) {
7021 *valid = true;
7022
7023 const SessionDescriptionInterface* current_remote_desc =
7024 remote_desc ? remote_desc : remote_description();
7025
7026 if (!current_remote_desc) {
7027 return false;
7028 }
7029
Guido Urdaneta41633172019-05-23 20:12:29 +02007030 RTCErrorOr<const cricket::ContentInfo*> result =
7031 FindContentInfo(current_remote_desc, candidate);
7032 if (!result.ok()) {
7033 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7034 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007035
7036 *valid = false;
7037 return false;
7038 }
7039
Guido Urdaneta41633172019-05-23 20:12:29 +02007040 std::string transport_name = GetTransportName(result.value()->name);
7041 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007042}
7043
7044bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007045 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007046 (dtls_enabled_ ||
7047 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007048}
7049
7050void PeerConnection::OnTransportControllerGatheringState(
7051 cricket::IceGatheringState state) {
7052 RTC_DCHECK(signaling_thread()->IsCurrent());
7053 if (state == cricket::kIceGatheringGathering) {
7054 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7055 } else if (state == cricket::kIceGatheringComplete) {
7056 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7057 }
7058}
7059
7060void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007061 std::map<std::string, std::set<cricket::MediaType>>
7062 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007063 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007064 if (transceiver->internal()->channel()) {
7065 const std::string& transport_name =
7066 transceiver->internal()->channel()->transport_name();
7067 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007068 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007069 }
Steve Anton75737c02017-11-06 10:37:17 -08007070 }
7071 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007072 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7073 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007074 }
Zhi Huange830e682018-03-30 10:48:35 -07007075
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007076 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007077 if (transport_name) {
7078 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007079 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007080 }
Zhi Huange830e682018-03-30 10:48:35 -07007081
Steve Antonc7b964c2018-02-01 14:39:45 -08007082 for (const auto& entry : media_types_by_transport_name) {
7083 const std::string& transport_name = entry.first;
7084 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007085 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007086 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007087 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007088 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007089 }
7090 }
7091}
7092// Walk through the ConnectionInfos to gather best connection usage
7093// for IPv4 and IPv6.
7094void PeerConnection::ReportBestConnectionState(
7095 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007096 for (const cricket::TransportChannelStats& channel_stats :
7097 stats.channel_stats) {
7098 for (const cricket::ConnectionInfo& connection_info :
7099 channel_stats.connection_infos) {
7100 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007101 continue;
7102 }
7103
Steve Antonc7b964c2018-02-01 14:39:45 -08007104 const cricket::Candidate& local = connection_info.local_candidate;
7105 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007106
7107 // Increment the counter for IceCandidatePairType.
7108 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7109 (local.type() == RELAY_PORT_TYPE &&
7110 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007111 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7112 GetIceCandidatePairCounter(local, remote),
7113 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007114 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007115 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7116 GetIceCandidatePairCounter(local, remote),
7117 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007118 } else {
7119 RTC_CHECK(0);
7120 }
Steve Anton75737c02017-11-06 10:37:17 -08007121
7122 // Increment the counter for IP type.
7123 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007124 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7125 kBestConnections_IPv4,
7126 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007127 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007128 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7129 kBestConnections_IPv6,
7130 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007131 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007132 RTC_CHECK(!local.address().hostname().empty() &&
7133 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007134 }
7135
7136 return;
7137 }
7138 }
7139}
7140
7141void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007142 const cricket::TransportStats& stats,
7143 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007144 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7145 return;
7146 }
7147
7148 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7149 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7150 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7151 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7152 return;
7153 }
7154
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007155 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7156 for (cricket::MediaType media_type : media_types) {
7157 switch (media_type) {
7158 case cricket::MEDIA_TYPE_AUDIO:
7159 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7160 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7161 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7162 break;
7163 case cricket::MEDIA_TYPE_VIDEO:
7164 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7165 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7166 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7167 break;
7168 case cricket::MEDIA_TYPE_DATA:
7169 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7170 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7171 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7172 break;
7173 default:
7174 RTC_NOTREACHED();
7175 continue;
7176 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007177 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007178 }
7179
7180 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7181 for (cricket::MediaType media_type : media_types) {
7182 switch (media_type) {
7183 case cricket::MEDIA_TYPE_AUDIO:
7184 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7185 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7186 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7187 break;
7188 case cricket::MEDIA_TYPE_VIDEO:
7189 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7190 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7191 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7192 break;
7193 case cricket::MEDIA_TYPE_DATA:
7194 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7195 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7196 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7197 break;
7198 default:
7199 RTC_NOTREACHED();
7200 continue;
7201 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007202 }
Steve Anton75737c02017-11-06 10:37:17 -08007203 }
7204}
7205
7206void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007207 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007208 RTC_DCHECK(call_);
7209 call_->OnSentPacket(sent_packet);
7210}
7211
7212const std::string PeerConnection::GetTransportName(
7213 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007214 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007215 if (channel) {
7216 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007217 }
Steve Anton6fec8802017-12-04 10:37:29 -08007218 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007219 RTC_DCHECK(sctp_mid_);
7220 if (content_name == *sctp_mid_) {
7221 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007222 }
7223 }
7224 // Return an empty string if failed to retrieve the transport name.
7225 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007226}
7227
Steve Anton6fec8802017-12-04 10:37:29 -08007228void PeerConnection::DestroyTransceiverChannel(
7229 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7230 transceiver) {
7231 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007232
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007233 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007234 if (channel) {
7235 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007236 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007237 }
7238}
7239
7240void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007241 if (rtp_data_channel_) {
7242 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007243 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007244 rtp_data_channel_ = nullptr;
7245 }
7246
7247 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7248 // grab a reference to this PeerConnection. If this is called from the
7249 // PeerConnection destructor, the RefCountedObject vtable will have already
7250 // been destroyed (since it is a subclass of PeerConnection) and using
7251 // rtc::Bind will cause "Pure virtual function called" error to appear.
7252
7253 if (sctp_transport_) {
7254 OnDataChannelDestroyed();
7255 network_thread()->Invoke<void>(RTC_FROM_HERE,
7256 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007257 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007258 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007259
7260 if (media_transport_) {
7261 OnDataChannelDestroyed();
7262 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7263 RTC_DCHECK_RUN_ON(network_thread());
7264 TeardownMediaTransportForDataChannels_n();
7265 });
7266 }
Steve Anton6fec8802017-12-04 10:37:29 -08007267}
7268
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007269void PeerConnection::DestroyChannelInterface(
7270 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007271 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007272 switch (channel->media_type()) {
7273 case cricket::MEDIA_TYPE_AUDIO:
7274 channel_manager()->DestroyVoiceChannel(
7275 static_cast<cricket::VoiceChannel*>(channel));
7276 break;
7277 case cricket::MEDIA_TYPE_VIDEO:
7278 channel_manager()->DestroyVideoChannel(
7279 static_cast<cricket::VideoChannel*>(channel));
7280 break;
7281 case cricket::MEDIA_TYPE_DATA:
7282 channel_manager()->DestroyRtpDataChannel(
7283 static_cast<cricket::RtpDataChannel*>(channel));
7284 break;
7285 default:
7286 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7287 break;
7288 }
Zhi Huange830e682018-03-30 10:48:35 -07007289}
Steve Anton6fec8802017-12-04 10:37:29 -08007290
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007291bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007292 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007293 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007294 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007295 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007296 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007297 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007298 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007299 auto base_channel = GetChannel(mid);
7300 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007301 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007302 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007303 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007304 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007305 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007306
Karl Wiberg5966c502019-02-21 23:55:09 +01007307 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007308 // Only pass media transport to call object if media transport is used
7309 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007310 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007311 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007312
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007313 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007314}
7315
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007316void PeerConnection::OnSetStreams() {
7317 RTC_DCHECK_RUN_ON(signaling_thread());
7318 if (IsUnifiedPlan())
7319 UpdateNegotiationNeeded();
7320}
7321
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007322PeerConnectionObserver* PeerConnection::Observer() const {
7323 // In earlier production code, the pointer was not cleared on close,
7324 // which might have led to undefined behavior if the observer was not
7325 // deallocated, or strange crashes if it was.
7326 // We use CHECK in order to catch such behavior if it exists.
7327 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7328 RTC_CHECK(observer_);
7329 return observer_;
7330}
7331
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007332CryptoOptions PeerConnection::GetCryptoOptions() {
7333 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7334 // after it has been removed.
7335 return configuration_.crypto_options.has_value()
7336 ? *configuration_.crypto_options
7337 : factory_->options().crypto_options;
7338}
7339
Harald Alvestrand89061872018-01-02 14:08:34 +01007340void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007341 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007342 if (stats_collector_) {
7343 stats_collector_->ClearCachedStatsReport();
7344 }
7345}
7346
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007347void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007348 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7349 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007350}
7351
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007352void PeerConnection::UpdateNegotiationNeeded() {
7353 RTC_DCHECK_RUN_ON(signaling_thread());
7354 if (!IsUnifiedPlan()) {
7355 Observer()->OnRenegotiationNeeded();
7356 return;
7357 }
7358
7359 // If connection's [[IsClosed]] slot is true, abort these steps.
7360 if (IsClosed())
7361 return;
7362
7363 // If connection's signaling state is not "stable", abort these steps.
7364 if (signaling_state() != kStable)
7365 return;
7366
7367 // NOTE
7368 // The negotiation-needed flag will be updated once the state transitions to
7369 // "stable", as part of the steps for setting an RTCSessionDescription.
7370
7371 // If the result of checking if negotiation is needed is false, clear the
7372 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7373 // to false, and abort these steps.
7374 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7375 if (!is_negotiation_needed) {
7376 is_negotiation_needed_ = false;
7377 return;
7378 }
7379
7380 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7381 // steps.
7382 if (is_negotiation_needed_)
7383 return;
7384
7385 // Set connection's [[NegotiationNeeded]] slot to true.
7386 is_negotiation_needed_ = true;
7387
7388 // Queue a task that runs the following steps:
7389 // If connection's [[IsClosed]] slot is true, abort these steps.
7390 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7391 // Fire an event named negotiationneeded at connection.
7392 Observer()->OnRenegotiationNeeded();
7393}
7394
7395bool PeerConnection::CheckIfNegotiationIsNeeded() {
7396 RTC_DCHECK_RUN_ON(signaling_thread());
7397 // 1. If any implementation-specific negotiation is required, as described at
7398 // the start of this section, return true.
7399
Henrik Boström79b69802019-07-18 11:16:56 +02007400 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7401 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7402 return true;
7403 }
7404
7405 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007406 const SessionDescriptionInterface* description = current_local_description();
7407 if (!description)
7408 return true;
7409
Henrik Boström79b69802019-07-18 11:16:56 +02007410 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007411 // description has been negotiated yet for data, return true.
7412 if (!sctp_data_channels_.empty()) {
7413 if (!cricket::GetFirstDataContent(description->description()->contents()))
7414 return true;
7415 }
7416
Henrik Boström79b69802019-07-18 11:16:56 +02007417 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007418 // following checks:
7419 for (const auto& transceiver : transceivers_) {
7420 const ContentInfo* current_local_msection =
7421 FindTransceiverMSection(transceiver.get(), description);
7422
7423 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7424 transceiver.get(), current_remote_description());
7425
Henrik Boström79b69802019-07-18 11:16:56 +02007426 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007427 // but the associated m= section is not yet rejected in
7428 // connection.[[CurrentLocalDescription]] or
7429 // connection.[[CurrentRemoteDescription]], return true.
7430 if (transceiver->stopped()) {
7431 if (current_local_msection && !current_local_msection->rejected &&
7432 ((current_remote_msection && !current_remote_msection->rejected) ||
7433 !current_remote_msection)) {
7434 return true;
7435 }
7436 continue;
7437 }
7438
Henrik Boström79b69802019-07-18 11:16:56 +02007439 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007440 // section in description, return true.
7441 if (!current_local_msection)
7442 return true;
7443
7444 const MediaContentDescription* current_local_media_description =
7445 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007446 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007447 // in description then perform the following checks:
7448
Henrik Boström79b69802019-07-18 11:16:56 +02007449 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007450 // associated m= section in description either doesn't contain a single
7451 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7452 // m= section, or the MSID values themselves, differ from what is in
7453 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7454 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7455 if (current_local_media_description->streams().size() == 0)
7456 return true;
7457
7458 std::vector<std::string> msection_msids;
7459 for (const auto& stream : current_local_media_description->streams()) {
7460 for (const std::string& msid : stream.stream_ids())
7461 msection_msids.push_back(msid);
7462 }
7463
7464 std::vector<std::string> transceiver_msids =
7465 transceiver->sender()->stream_ids();
7466 if (msection_msids.size() != transceiver_msids.size())
7467 return true;
7468
7469 absl::c_sort(transceiver_msids);
7470 absl::c_sort(msection_msids);
7471 if (transceiver_msids != msection_msids)
7472 return true;
7473 }
7474
Henrik Boström79b69802019-07-18 11:16:56 +02007475 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007476 // associated m= section in neither connection.[[CurrentLocalDescription]]
7477 // nor connection.[[CurrentRemoteDescription]] matches
7478 // transceiver.[[Direction]], return true.
7479 if (description->GetType() == SdpType::kOffer) {
7480 if (!current_remote_description())
7481 return true;
7482
7483 if (!current_remote_msection)
7484 return true;
7485
7486 RtpTransceiverDirection current_local_direction =
7487 current_local_media_description->direction();
7488 RtpTransceiverDirection current_remote_direction =
7489 current_remote_msection->media_description()->direction();
7490 if (transceiver->direction() != current_local_direction &&
7491 transceiver->direction() !=
7492 RtpTransceiverDirectionReversed(current_remote_direction)) {
7493 return true;
7494 }
7495 }
7496
Henrik Boström79b69802019-07-18 11:16:56 +02007497 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007498 // associated m= section in the description does not match
7499 // transceiver.[[Direction]] intersected with the offered direction (as
7500 // described in [JSEP] (section 5.3.1.)), return true.
7501 if (description->GetType() == SdpType::kAnswer) {
7502 if (!remote_description())
7503 return true;
7504
7505 const ContentInfo* offered_remote_msection =
7506 FindTransceiverMSection(transceiver.get(), remote_description());
7507
7508 RtpTransceiverDirection offered_direction =
7509 offered_remote_msection
7510 ? offered_remote_msection->media_description()->direction()
7511 : RtpTransceiverDirection::kInactive;
7512
7513 if (current_local_media_description->direction() !=
7514 (RtpTransceiverDirectionIntersection(
7515 transceiver->direction(),
7516 RtpTransceiverDirectionReversed(offered_direction)))) {
7517 return true;
7518 }
7519 }
7520 }
7521
7522 // If all the preceding checks were performed and true was not returned,
7523 // nothing remains to be negotiated; return false.
7524 return false;
7525}
7526
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007527} // namespace webrtc