blob: 3c03e392e66c60214c299e264f71d3600304f1d4 [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);
1142
1143 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001144
deadbeefab9b2d12015-10-14 11:33:11 -07001145 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001146 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147
Steve Antonba818672017-11-06 10:21:57 -08001148 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001149 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001150
Steve Anton75737c02017-11-06 10:37:17 -08001151 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1152 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1153 if (!configuration.certificates.empty()) {
1154 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1155 // just picking the first one. The decision should be made based on the DTLS
1156 // handshake. The DTLS negotiations need to know about all certificates.
1157 certificate = configuration.certificates[0];
1158 }
1159
Steve Antond25da372017-11-06 14:50:29 -08001160 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001161
1162 if (options.disable_encryption) {
1163 dtls_enabled_ = false;
1164 } else {
1165 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001166 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001167 // |configuration| can override the default |dtls_enabled_| value.
1168 if (configuration.enable_dtls_srtp) {
1169 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1170 }
1171 }
1172
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001173 if (configuration.use_media_transport_for_data_channels) {
1174 if (configuration.enable_rtp_data_channel) {
1175 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1176 "use_media_transport_for_data_channels are "
1177 "incompatible and cannot both be set to true";
1178 return false;
1179 }
1180 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1181 } else if (configuration.enable_rtp_data_channel) {
1182 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1183 // set. It takes precendence over the disable_sctp_data_channels
1184 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001185 data_channel_type_ = cricket::DCT_RTP;
1186 } else {
1187 // DTLS has to be enabled to use SCTP.
1188 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1189 data_channel_type_ = cricket::DCT_SCTP;
1190 }
1191 }
1192
1193 video_options_.screencast_min_bitrate_kbps =
1194 configuration.screencast_min_bitrate;
1195 audio_options_.combined_audio_video_bwe =
1196 configuration.combined_audio_video_bwe;
1197
1198 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001199 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001200
1201 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001202 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001203
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001204 audio_options_.audio_jitter_buffer_min_delay_ms =
1205 configuration.audio_jitter_buffer_min_delay_ms;
1206
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001207 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1208 configuration.audio_jitter_buffer_enable_rtx_handling;
1209
Steve Anton75737c02017-11-06 10:37:17 -08001210 // Whether the certificate generator/certificate is null or not determines
1211 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1212 // the right instructions by clearing the variables if needed.
1213 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001214 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001215 certificate = nullptr;
1216 } else if (certificate) {
1217 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001218 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001219 }
1220
1221 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1222 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001223 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001224 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1225 this, &PeerConnection::OnCertificateReady);
1226
1227 if (options.disable_encryption) {
1228 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1229 }
1230
1231 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001232 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001233 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001234
Steve Anton4171afb2017-11-20 10:20:22 -08001235 // Add default audio/video transceivers for Plan B SDP.
1236 if (!IsUnifiedPlan()) {
1237 transceivers_.push_back(
1238 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1239 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1240 transceivers_.push_back(
1241 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1242 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1243 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001244 int delay_ms =
1245 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001246 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1247 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001248
1249 if (dependencies.video_bitrate_allocator_factory) {
1250 video_bitrate_allocator_factory_ =
1251 std::move(dependencies.video_bitrate_allocator_factory);
1252 } else {
1253 video_bitrate_allocator_factory_ =
1254 CreateBuiltinVideoBitrateAllocatorFactory();
1255 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 return true;
1257}
1258
Steve Anton038834f2017-07-14 15:59:59 -07001259RTCError PeerConnection::ValidateConfiguration(
1260 const RTCConfiguration& config) const {
1261 if (config.ice_regather_interval_range &&
1262 config.continual_gathering_policy == GATHER_ONCE) {
1263 return RTCError(RTCErrorType::INVALID_PARAMETER,
1264 "ice_regather_interval_range specified but continual "
1265 "gathering policy is GATHER_ONCE");
1266 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001267 auto result =
1268 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1269 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001270}
1271
Yves Gerey665174f2018-06-19 15:03:05 +02001272rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001273 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001274 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1275 "Plan SdpSemantics. Please use GetSenders "
1276 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001277 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278}
1279
Yves Gerey665174f2018-06-19 15:03:05 +02001280rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001281 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001282 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1283 "Plan SdpSemantics. Please use GetReceivers "
1284 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001285 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286}
1287
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001288bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001289 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001290 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1291 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001292 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 if (IsClosed()) {
1294 return false;
1295 }
deadbeefab9b2d12015-10-14 11:33:11 -07001296 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 return false;
1298 }
deadbeefab9b2d12015-10-14 11:33:11 -07001299
1300 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001301 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1302 observer->SignalAudioTrackAdded.connect(this,
1303 &PeerConnection::OnAudioTrackAdded);
1304 observer->SignalAudioTrackRemoved.connect(
1305 this, &PeerConnection::OnAudioTrackRemoved);
1306 observer->SignalVideoTrackAdded.connect(this,
1307 &PeerConnection::OnVideoTrackAdded);
1308 observer->SignalVideoTrackRemoved.connect(
1309 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001310 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001311
deadbeefab9b2d12015-10-14 11:33:11 -07001312 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001313 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001314 }
1315 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001316 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001317 }
1318
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001319 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001320 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321 return true;
1322}
1323
1324void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001325 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001326 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1327 "Plan SdpSemantics. Please use RemoveTrack "
1328 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001329 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001330 if (!IsClosed()) {
1331 for (const auto& track : local_stream->GetAudioTracks()) {
1332 RemoveAudioTrack(track.get(), local_stream);
1333 }
1334 for (const auto& track : local_stream->GetVideoTracks()) {
1335 RemoveVideoTrack(track.get(), local_stream);
1336 }
deadbeefab9b2d12015-10-14 11:33:11 -07001337 }
deadbeefab9b2d12015-10-14 11:33:11 -07001338 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001339 stream_observers_.erase(
1340 std::remove_if(
1341 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001342 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001343 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001344 }),
1345 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001346
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 if (IsClosed()) {
1348 return;
1349 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001350 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351}
1352
Steve Anton2d6c76a2018-01-05 17:10:52 -08001353RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001354 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001355 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001356 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001357 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001358 if (!track) {
1359 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1360 }
1361 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1362 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1364 "Track has invalid kind: " + track->kind());
1365 }
Steve Antonf9381f02017-12-14 10:23:57 -08001366 if (IsClosed()) {
1367 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1368 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001369 }
Steve Anton4171afb2017-11-20 10:20:22 -08001370 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001371 LOG_AND_RETURN_ERROR(
1372 RTCErrorType::INVALID_PARAMETER,
1373 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001374 }
Steve Antonf9381f02017-12-14 10:23:57 -08001375 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001376 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1377 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001378 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001379 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001380 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001381 }
1382 return sender_or_error;
1383}
deadbeefe1f9d832016-01-14 15:35:42 -08001384
Steve Antonf9381f02017-12-14 10:23:57 -08001385RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1386PeerConnection::AddTrackPlanB(
1387 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001388 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001389 if (stream_ids.size() > 1u) {
1390 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1391 "AddTrack with more than one stream is not "
1392 "supported with Plan B semantics.");
1393 }
1394 std::vector<std::string> adjusted_stream_ids = stream_ids;
1395 if (adjusted_stream_ids.empty()) {
1396 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1397 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 cricket::MediaType media_type =
1399 (track->kind() == MediaStreamTrackInterface::kAudioKind
1400 ? cricket::MEDIA_TYPE_AUDIO
1401 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001402 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001403 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001404 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001405 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001406 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001407 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001408 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001409 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001410 if (sender_info) {
1411 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001412 }
Steve Antonf9381f02017-12-14 10:23:57 -08001413 } else {
1414 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001415 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001416 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001417 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001418 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001419 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001420 if (sender_info) {
1421 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001422 }
deadbeefe1f9d832016-01-14 15:35:42 -08001423 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001424 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001425}
deadbeefe1f9d832016-01-14 15:35:42 -08001426
Steve Antonf9381f02017-12-14 10:23:57 -08001427RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1428PeerConnection::AddTrackUnifiedPlan(
1429 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001430 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001431 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1432 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001433 RTC_LOG(LS_INFO) << "Reusing an existing "
1434 << cricket::MediaTypeToString(transceiver->media_type())
1435 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001436 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001437 transceiver->internal()->set_direction(
1438 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001439 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001440 transceiver->internal()->set_direction(
1441 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001442 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001443 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001444 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001445 } else {
1446 cricket::MediaType media_type =
1447 (track->kind() == MediaStreamTrackInterface::kAudioKind
1448 ? cricket::MEDIA_TYPE_AUDIO
1449 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001450 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1451 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001452 std::string sender_id = track->id();
1453 // Avoid creating a sender with an existing ID by generating a random ID.
1454 // This can happen if this is the second time AddTrack has created a sender
1455 // for this track.
1456 if (FindSenderById(sender_id)) {
1457 sender_id = rtc::CreateRandomUuid();
1458 }
Florent Castelli892acf02018-10-01 22:47:20 +02001459 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001460 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1461 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001462 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001463 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001464 }
Steve Antonf9381f02017-12-14 10:23:57 -08001465 return transceiver->sender();
1466}
1467
1468rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1469PeerConnection::FindFirstTransceiverForAddedTrack(
1470 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1471 RTC_DCHECK(track);
1472 for (auto transceiver : transceivers_) {
1473 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001474 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001475 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001476 !transceiver->internal()->has_ever_been_used_to_send() &&
1477 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001478 return transceiver;
1479 }
1480 }
1481 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001482}
1483
1484bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1485 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001486 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001487}
1488
Steve Anton24db5732018-07-23 10:27:33 -07001489RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001490 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001491 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001492 if (!sender) {
1493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1494 }
deadbeefe1f9d832016-01-14 15:35:42 -08001495 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001496 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1497 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001498 }
Steve Antonf9381f02017-12-14 10:23:57 -08001499 if (IsUnifiedPlan()) {
1500 auto transceiver = FindTransceiverBySender(sender);
1501 if (!transceiver || !sender->track()) {
1502 return RTCError::OK();
1503 }
1504 sender->SetTrack(nullptr);
1505 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001506 transceiver->internal()->set_direction(
1507 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001508 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001509 transceiver->internal()->set_direction(
1510 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001511 }
Steve Anton4171afb2017-11-20 10:20:22 -08001512 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001513 bool removed;
1514 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1515 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1516 } else {
1517 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1518 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1519 }
1520 if (!removed) {
1521 LOG_AND_RETURN_ERROR(
1522 RTCErrorType::INVALID_PARAMETER,
1523 "Couldn't find sender " + sender->id() + " to remove.");
1524 }
Steve Anton4171afb2017-11-20 10:20:22 -08001525 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001526 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001527 return RTCError::OK();
1528}
1529
1530rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1531PeerConnection::FindTransceiverBySender(
1532 rtc::scoped_refptr<RtpSenderInterface> sender) {
1533 for (auto transceiver : transceivers_) {
1534 if (transceiver->sender() == sender) {
1535 return transceiver;
1536 }
1537 }
1538 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001539}
1540
Steve Anton9158ef62017-11-27 13:01:52 -08001541RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1542PeerConnection::AddTransceiver(
1543 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1544 return AddTransceiver(track, RtpTransceiverInit());
1545}
1546
1547RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1548PeerConnection::AddTransceiver(
1549 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1550 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001551 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001552 RTC_CHECK(IsUnifiedPlan())
1553 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001554 if (!track) {
1555 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1556 }
1557 cricket::MediaType media_type;
1558 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1559 media_type = cricket::MEDIA_TYPE_AUDIO;
1560 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1561 media_type = cricket::MEDIA_TYPE_VIDEO;
1562 } else {
1563 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1564 "Track kind is not audio or video");
1565 }
1566 return AddTransceiver(media_type, track, init);
1567}
1568
1569RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1570PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1571 return AddTransceiver(media_type, RtpTransceiverInit());
1572}
1573
1574RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1575PeerConnection::AddTransceiver(cricket::MediaType media_type,
1576 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001577 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001578 RTC_CHECK(IsUnifiedPlan())
1579 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001580 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1581 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1582 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1583 "media type is not audio or video");
1584 }
1585 return AddTransceiver(media_type, nullptr, init);
1586}
1587
1588RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1589PeerConnection::AddTransceiver(
1590 cricket::MediaType media_type,
1591 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001592 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001593 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001594 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1595 media_type == cricket::MEDIA_TYPE_VIDEO));
1596 if (track) {
1597 RTC_DCHECK_EQ(media_type,
1598 (track->kind() == MediaStreamTrackInterface::kAudioKind
1599 ? cricket::MEDIA_TYPE_AUDIO
1600 : cricket::MEDIA_TYPE_VIDEO));
1601 }
1602
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001603 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1604 init.send_encodings.size(), 0, 7, 8);
1605
Amit Hilbuchaa584152019-02-06 17:09:52 -08001606 size_t num_rids = absl::c_count_if(init.send_encodings,
1607 [](const RtpEncodingParameters& encoding) {
1608 return !encoding.rid.empty();
1609 });
1610 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001611 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001612 RTCErrorType::INVALID_PARAMETER,
1613 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001614 }
1615
Amit Hilbuchf4770402019-04-08 14:11:57 -07001616 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1617 [](const RtpEncodingParameters& encoding) {
1618 return !IsLegalRsidName(encoding.rid);
1619 })) {
1620 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1621 "Invalid RID value provided.");
1622 }
1623
Amit Hilbuchaa584152019-02-06 17:09:52 -08001624 if (absl::c_any_of(init.send_encodings,
1625 [](const RtpEncodingParameters& encoding) {
1626 return encoding.ssrc.has_value();
1627 })) {
1628 LOG_AND_RETURN_ERROR(
1629 RTCErrorType::UNSUPPORTED_PARAMETER,
1630 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001631 }
1632
1633 RtpParameters parameters;
1634 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001635
1636 // Encodings are dropped from the tail if too many are provided.
1637 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1638 parameters.encodings.erase(
1639 parameters.encodings.begin() + kMaxSimulcastStreams,
1640 parameters.encodings.end());
1641 }
1642
1643 // Single RID should be removed.
1644 if (parameters.encodings.size() == 1 &&
1645 !parameters.encodings[0].rid.empty()) {
1646 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1647 parameters.encodings[0].rid.clear();
1648 }
1649
1650 // If RIDs were not provided, they are generated for simulcast scenario.
1651 if (parameters.encodings.size() > 1 && num_rids == 0) {
1652 rtc::UniqueStringGenerator rid_generator;
1653 for (RtpEncodingParameters& encoding : parameters.encodings) {
1654 encoding.rid = rid_generator();
1655 }
1656 }
1657
Florent Castelli892acf02018-10-01 22:47:20 +02001658 if (UnimplementedRtpParameterHasValue(parameters)) {
1659 LOG_AND_RETURN_ERROR(
1660 RTCErrorType::UNSUPPORTED_PARAMETER,
1661 "Attempted to set an unimplemented parameter of RtpParameters.");
1662 }
Steve Anton9158ef62017-11-27 13:01:52 -08001663
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001664 auto result = cricket::CheckRtpParametersValues(parameters);
1665 if (!result.ok()) {
1666 LOG_AND_RETURN_ERROR(result.type(), result.message());
1667 }
1668
Steve Anton3d954a62018-04-02 11:27:23 -07001669 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1670 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001671 // Set the sender ID equal to the track ID if the track is specified unless
1672 // that sender ID is already in use.
1673 std::string sender_id =
1674 (track && !FindSenderById(track->id()) ? track->id()
1675 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001676 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001677 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001678 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1679 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1680 transceiver->internal()->set_direction(init.direction);
1681
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001682 if (update_negotiation_needed) {
1683 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001684 }
Steve Antonf9381f02017-12-14 10:23:57 -08001685
1686 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1687}
1688
Steve Anton02ee47c2018-01-10 16:26:06 -08001689rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1690PeerConnection::CreateSender(
1691 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001692 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001693 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001694 const std::vector<std::string>& stream_ids,
1695 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001696 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001697 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001698 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1699 RTC_DCHECK(!track ||
1700 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1701 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1702 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001703 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001704 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001705 } else {
1706 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1707 RTC_DCHECK(!track ||
1708 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1709 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001710 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001711 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001712 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001713 bool set_track_succeeded = sender->SetTrack(track);
1714 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001715 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001716 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001717 return sender;
1718}
1719
1720rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1721PeerConnection::CreateReceiver(cricket::MediaType media_type,
1722 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001723 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1724 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001725 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001726 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001727 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1728 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001729 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001730 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001731 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001732 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001733 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1734 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001735 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001736 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001737 return receiver;
1738}
1739
1740rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1741PeerConnection::CreateAndAddTransceiver(
1742 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1743 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1744 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001745 // Ensure that the new sender does not have an ID that is already in use by
1746 // another sender.
1747 // Allow receiver IDs to conflict since those come from remote SDP (which
1748 // could be invalid, but should not cause a crash).
1749 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001750 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001751 signaling_thread(),
1752 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001753 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001754 transceiver->internal()->SignalNegotiationNeeded.connect(
1755 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001756 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001757}
1758
Steve Anton52d86772018-02-20 15:48:12 -08001759void PeerConnection::OnNegotiationNeeded() {
1760 RTC_DCHECK_RUN_ON(signaling_thread());
1761 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001762 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001763}
1764
deadbeeffac06552015-11-25 11:26:01 -08001765rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001766 const std::string& kind,
1767 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001768 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001769 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1770 "Plan SdpSemantics. Please use AddTransceiver "
1771 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001772 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001773 if (IsClosed()) {
1774 return nullptr;
1775 }
Steve Anton4171afb2017-11-20 10:20:22 -08001776
Seth Hampson5b4f0752018-04-02 16:31:36 -07001777 // Internally we need to have one stream with Plan B semantics, so we
1778 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001779 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001780 if (stream_id.empty()) {
1781 stream_ids.push_back(rtc::CreateRandomUuid());
1782 RTC_LOG(LS_INFO)
1783 << "No stream_id specified for sender. Generated stream ID: "
1784 << stream_ids[0];
1785 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001786 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001787 }
1788
Steve Anton4171afb2017-11-20 10:20:22 -08001789 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001790 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001791 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001792 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001793 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001794 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001795 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001796 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001797 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001798 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001799 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001800 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001801 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001802 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001803 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001804 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001805 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001806 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001807 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001808 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001809 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001810
deadbeefe1f9d832016-01-14 15:35:42 -08001811 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001812}
1813
deadbeef70ab1a12015-09-28 16:53:55 -07001814std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1815 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001816 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001817 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001818 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001819 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001820 }
1821 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001822}
1823
Steve Anton4171afb2017-11-20 10:20:22 -08001824std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1825PeerConnection::GetSendersInternal() const {
1826 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1827 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001828 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001829 auto senders = transceiver->internal()->senders();
1830 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1831 }
1832 return all_senders;
1833}
1834
deadbeef70ab1a12015-09-28 16:53:55 -07001835std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1836PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001837 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001838 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001839 for (const auto& receiver : GetReceiversInternal()) {
1840 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001841 }
1842 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001843}
1844
Steve Anton4171afb2017-11-20 10:20:22 -08001845std::vector<
1846 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1847PeerConnection::GetReceiversInternal() const {
1848 std::vector<
1849 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1850 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001851 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001852 auto receivers = transceiver->internal()->receivers();
1853 all_receivers.insert(all_receivers.end(), receivers.begin(),
1854 receivers.end());
1855 }
1856 return all_receivers;
1857}
1858
Steve Anton9158ef62017-11-27 13:01:52 -08001859std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1860PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001861 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001862 RTC_CHECK(IsUnifiedPlan())
1863 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001864 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001865 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001866 all_transceivers.push_back(transceiver);
1867 }
1868 return all_transceivers;
1869}
1870
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001872 MediaStreamTrackInterface* track,
1873 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001874 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001875 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001876 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001877 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 return false;
1879 }
1880
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001881 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001882 // The StatsCollector is used to tell if a track is valid because it may
1883 // remember tracks that the PeerConnection previously removed.
1884 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001885 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1886 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001887 return false;
1888 }
Steve Antonad182762018-09-05 20:22:40 +00001889 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1890 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001891 return true;
1892}
1893
hbos74e1a4f2016-09-15 23:33:01 -07001894void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001895 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001896 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001897 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001898 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001899 stats_collector_->GetStatsReport(callback);
1900}
1901
Henrik Boström1df1bf82018-03-20 13:24:20 +01001902void PeerConnection::GetStats(
1903 rtc::scoped_refptr<RtpSenderInterface> selector,
1904 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1905 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001906 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001907 RTC_DCHECK(callback);
1908 RTC_DCHECK(stats_collector_);
1909 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1910 if (selector) {
1911 for (const auto& proxy_transceiver : transceivers_) {
1912 for (const auto& proxy_sender :
1913 proxy_transceiver->internal()->senders()) {
1914 if (proxy_sender == selector) {
1915 internal_sender = proxy_sender->internal();
1916 break;
1917 }
1918 }
1919 if (internal_sender)
1920 break;
1921 }
1922 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001923 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001924 // belong to the PeerConnection (in Plan B, senders can be removed from the
1925 // PeerConnection). This means that "all the stats objects representing the
1926 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1927 // produces an empty stats report.
1928 stats_collector_->GetStatsReport(internal_sender, callback);
1929}
1930
1931void PeerConnection::GetStats(
1932 rtc::scoped_refptr<RtpReceiverInterface> selector,
1933 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1934 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001935 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001936 RTC_DCHECK(callback);
1937 RTC_DCHECK(stats_collector_);
1938 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1939 if (selector) {
1940 for (const auto& proxy_transceiver : transceivers_) {
1941 for (const auto& proxy_receiver :
1942 proxy_transceiver->internal()->receivers()) {
1943 if (proxy_receiver == selector) {
1944 internal_receiver = proxy_receiver->internal();
1945 break;
1946 }
1947 }
1948 if (internal_receiver)
1949 break;
1950 }
1951 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001952 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001953 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1954 // the PeerConnection). This means that "all the stats objects representing
1955 // the selector" is an empty set. Invoking GetStatsReport() with a null
1956 // selector produces an empty stats report.
1957 stats_collector_->GetStatsReport(internal_receiver, callback);
1958}
1959
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001961 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001962 return signaling_state_;
1963}
1964
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001965PeerConnectionInterface::IceConnectionState
1966PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001967 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001968 return ice_connection_state_;
1969}
1970
Alex Loiko9289eda2018-11-23 16:18:59 +00001971PeerConnectionInterface::IceConnectionState
1972PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001973 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001974 return standardized_ice_connection_state_;
1975}
1976
Jonas Olsson635474e2018-10-18 15:58:17 +02001977PeerConnectionInterface::PeerConnectionState
1978PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001979 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001980 return connection_state_;
1981}
1982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983PeerConnectionInterface::IceGatheringState
1984PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001985 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 return ice_gathering_state_;
1987}
1988
Yves Gerey665174f2018-06-19 15:03:05 +02001989rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990 const std::string& label,
1991 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001992 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001993 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001994
deadbeefab9b2d12015-10-14 11:33:11 -07001995 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001996
kwibergd1fe2812016-04-27 06:47:29 -07001997 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001998 if (config) {
1999 internal_config.reset(new InternalDataChannelInit(*config));
2000 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002001 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002002 InternalCreateDataChannel(label, internal_config.get()));
2003 if (!channel.get()) {
2004 return nullptr;
2005 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002007 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2008 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002009 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002010 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002011 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002012 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 return DataChannelProxy::Create(signaling_thread(), channel.get());
2014}
2015
Henrik Boström79b69802019-07-18 11:16:56 +02002016void PeerConnection::RestartIce() {
2017 RTC_DCHECK_RUN_ON(signaling_thread());
2018 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2019 current_local_description_.get(), pending_local_description_.get());
2020 UpdateNegotiationNeeded();
2021}
2022
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002023void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002024 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002025 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002026 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002027
nisse7ce109a2017-01-31 00:57:56 -08002028 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002029 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002030 return;
2031 }
deadbeefab9b2d12015-10-14 11:33:11 -07002032
Steve Anton8d3444d2017-10-20 15:30:51 -07002033 if (IsClosed()) {
2034 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002035 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002036 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002037 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002038 return;
2039 }
2040
Steve Anton25ca0ac2019-06-25 10:40:48 -07002041 // If a session error has occurred the PeerConnection is in a possibly
2042 // inconsistent state so fail right away.
2043 if (session_error() != SessionError::kNone) {
2044 std::string error_message = GetSessionErrorMsg();
2045 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2046 PostCreateSessionDescriptionFailure(
2047 observer,
2048 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2049 return;
2050 }
2051
zhihuang1c378ed2017-08-17 14:10:50 -07002052 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002053 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002054 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002055 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002056 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002057 return;
2058 }
2059
Steve Anton22da89f2018-01-25 13:58:07 -08002060 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2061 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2062 if (IsUnifiedPlan()) {
2063 RTCError error = HandleLegacyOfferOptions(options);
2064 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002065 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002066 return;
2067 }
2068 }
2069
zhihuang1c378ed2017-08-17 14:10:50 -07002070 cricket::MediaSessionOptions session_options;
2071 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002072 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002073}
2074
Steve Anton22da89f2018-01-25 13:58:07 -08002075RTCError PeerConnection::HandleLegacyOfferOptions(
2076 const RTCOfferAnswerOptions& options) {
2077 RTC_DCHECK(IsUnifiedPlan());
2078
2079 if (options.offer_to_receive_audio == 0) {
2080 RemoveRecvDirectionFromReceivingTransceiversOfType(
2081 cricket::MEDIA_TYPE_AUDIO);
2082 } else if (options.offer_to_receive_audio == 1) {
2083 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2084 } else if (options.offer_to_receive_audio > 1) {
2085 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2086 "offer_to_receive_audio > 1 is not supported.");
2087 }
2088
2089 if (options.offer_to_receive_video == 0) {
2090 RemoveRecvDirectionFromReceivingTransceiversOfType(
2091 cricket::MEDIA_TYPE_VIDEO);
2092 } else if (options.offer_to_receive_video == 1) {
2093 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2094 } else if (options.offer_to_receive_video > 1) {
2095 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2096 "offer_to_receive_video > 1 is not supported.");
2097 }
2098
2099 return RTCError::OK();
2100}
2101
2102void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2103 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002104 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002105 RtpTransceiverDirection new_direction =
2106 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2107 if (new_direction != transceiver->direction()) {
2108 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2109 << " transceiver (MID="
2110 << transceiver->mid().value_or("<not set>") << ") from "
2111 << RtpTransceiverDirectionToString(
2112 transceiver->direction())
2113 << " to "
2114 << RtpTransceiverDirectionToString(new_direction)
2115 << " since CreateOffer specified offer_to_receive=0";
2116 transceiver->internal()->set_direction(new_direction);
2117 }
Steve Anton22da89f2018-01-25 13:58:07 -08002118 }
2119}
2120
2121void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2122 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002123 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002124 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002125 RTC_LOG(LS_INFO)
2126 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2127 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002128 RtpTransceiverInit init;
2129 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002130 AddTransceiver(media_type, nullptr, init,
2131 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002132 }
2133}
2134
2135std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2136PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2137 std::vector<
2138 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2139 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002140 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002141 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002142 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2143 receiving_transceivers.push_back(transceiver);
2144 }
2145 }
2146 return receiving_transceivers;
2147}
2148
htaa2a49d92016-03-04 02:51:39 -08002149void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2150 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002151 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002152 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002153 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002154 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002155 return;
2156 }
2157
Steve Anton25ca0ac2019-06-25 10:40:48 -07002158 // If a session error has occurred the PeerConnection is in a possibly
2159 // inconsistent state so fail right away.
2160 if (session_error() != SessionError::kNone) {
2161 std::string error_message = GetSessionErrorMsg();
2162 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2163 PostCreateSessionDescriptionFailure(
2164 observer,
2165 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2166 return;
2167 }
2168
Steve Antondffead82018-02-06 10:31:29 -08002169 if (!(signaling_state_ == kHaveRemoteOffer ||
2170 signaling_state_ == kHaveLocalPrAnswer)) {
2171 std::string error =
2172 "PeerConnection cannot create an answer in a state other than "
2173 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002174 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002175 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002176 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002177 return;
2178 }
2179
Steve Antondffead82018-02-06 10:31:29 -08002180 // The remote description should be set if we're in the right state.
2181 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002182
Steve Anton22da89f2018-01-25 13:58:07 -08002183 if (IsUnifiedPlan()) {
2184 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2185 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2186 "supported with Unified Plan semantics. Use the "
2187 "RtpTransceiver API instead.";
2188 }
2189 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2190 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2191 "supported with Unified Plan semantics. Use the "
2192 "RtpTransceiver API instead.";
2193 }
2194 }
2195
htaa2a49d92016-03-04 02:51:39 -08002196 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002197 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002198
Steve Antond25da372017-11-06 14:50:29 -08002199 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200}
2201
2202void PeerConnection::SetLocalDescription(
2203 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002204 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002205 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002206 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002207
Steve Anton80dd7b52018-02-16 17:08:42 -08002208 // The SetLocalDescription contract is that we take ownership of the session
2209 // description regardless of the outcome, so wrap it in a unique_ptr right
2210 // away. Ideally, SetLocalDescription's signature will be changed to take the
2211 // description as a unique_ptr argument to formalize this agreement.
2212 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2213
nisse7ce109a2017-01-31 00:57:56 -08002214 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002215 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002216 return;
2217 }
Steve Anton8a006912017-12-04 15:25:56 -08002218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002220 PostSetSessionDescriptionFailure(
2221 observer,
2222 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223 return;
2224 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002225
Steve Anton80dd7b52018-02-16 17:08:42 -08002226 // If a session error has occurred the PeerConnection is in a possibly
2227 // inconsistent state so fail right away.
2228 if (session_error() != SessionError::kNone) {
2229 std::string error_message = GetSessionErrorMsg();
2230 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002231 PostSetSessionDescriptionFailure(
2232 observer,
2233 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002234 return;
2235 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002236
Steve Anton80dd7b52018-02-16 17:08:42 -08002237 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2238 if (!error.ok()) {
2239 std::string error_message = GetSetDescriptionErrorMessage(
2240 cricket::CS_LOCAL, desc->GetType(), error);
2241 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002242 PostSetSessionDescriptionFailure(
2243 observer,
2244 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002245 return;
2246 }
2247
2248 // Grab the description type before moving ownership to ApplyLocalDescription,
2249 // which may destroy it before returning.
2250 const SdpType type = desc->GetType();
2251
2252 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002253 // |desc| may be destroyed at this point.
2254
2255 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002256 // If ApplyLocalDescription fails, the PeerConnection could be in an
2257 // inconsistent state, so act conservatively here and set the session error
2258 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2259 SetSessionError(SessionError::kContent, error.message());
2260 std::string error_message =
2261 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2262 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002263 PostSetSessionDescriptionFailure(
2264 observer,
2265 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002266 return;
2267 }
Steve Anton8a006912017-12-04 15:25:56 -08002268 RTC_DCHECK(local_description());
2269
2270 PostSetSessionDescriptionSuccess(observer);
2271
Steve Antonad182762018-09-05 20:22:40 +00002272 // MaybeStartGathering needs to be called after posting
2273 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2274 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002275 transport_controller_->MaybeStartGathering();
2276
Steve Antona3a92c22017-12-07 10:27:41 -08002277 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002278 // TODO(deadbeef): We already had to hop to the network thread for
2279 // MaybeStartGathering...
2280 network_thread()->Invoke<void>(
2281 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2282 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002283 // Make UMA notes about what was agreed to.
2284 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002285 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002286
2287 if (IsUnifiedPlan()) {
2288 bool was_negotiation_needed = is_negotiation_needed_;
2289 UpdateNegotiationNeeded();
2290 if (signaling_state() == kStable && was_negotiation_needed &&
2291 is_negotiation_needed_) {
2292 Observer()->OnRenegotiationNeeded();
2293 }
2294 }
2295
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002296 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002297}
2298
2299RTCError PeerConnection::ApplyLocalDescription(
2300 std::unique_ptr<SessionDescriptionInterface> desc) {
2301 RTC_DCHECK_RUN_ON(signaling_thread());
2302 RTC_DCHECK(desc);
2303
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304 // Update stats here so that we have the most recent stats for tracks and
2305 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002306 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002307
Steve Antondcc3c022017-12-22 16:02:54 -08002308 // Take a reference to the old local description since it's used below to
2309 // compare against the new local description. When setting the new local
2310 // description, grab ownership of the replaced session description in case it
2311 // is the same as |old_local_description|, to keep it alive for the duration
2312 // of the method.
2313 const SessionDescriptionInterface* old_local_description =
2314 local_description();
2315 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002316 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002317 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002318 replaced_local_description = pending_local_description_
2319 ? std::move(pending_local_description_)
2320 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002321 current_local_description_ = std::move(desc);
2322 pending_local_description_ = nullptr;
2323 current_remote_description_ = std::move(pending_remote_description_);
2324 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002325 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002326 pending_local_description_ = std::move(desc);
2327 }
2328 // The session description to apply now must be accessed by
2329 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002330 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002331
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002332 // Report statistics about any use of simulcast.
2333 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2334 *local_description()->description());
2335
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002336 if (!is_caller_) {
2337 if (remote_description()) {
2338 // Remote description was applied first, so this PC is the callee.
2339 is_caller_ = false;
2340 } else {
2341 // Local description is applied first, so this PC is the caller.
2342 is_caller_ = true;
2343 }
2344 }
2345
Zhi Huange830e682018-03-30 10:48:35 -07002346 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2347 if (!error.ok()) {
2348 return error;
2349 }
2350
Steve Antondcc3c022017-12-22 16:02:54 -08002351 if (IsUnifiedPlan()) {
2352 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002353 cricket::CS_LOCAL, *local_description(), old_local_description,
2354 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002355 if (!error.ok()) {
2356 return error;
2357 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002358 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2359 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002360 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002361 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2362 // Note that code paths that don't set MID won't be able to use
2363 // information about DTLS transports.
2364 if (transceiver->mid()) {
2365 auto dtls_transport =
2366 LookupDtlsTransportByMidInternal(*transceiver->mid());
2367 transceiver->internal()->sender_internal()->set_transport(
2368 dtls_transport);
2369 transceiver->internal()->receiver_internal()->set_transport(
2370 dtls_transport);
2371 }
2372
Steve Antondcc3c022017-12-22 16:02:54 -08002373 const ContentInfo* content =
2374 FindMediaSectionForTransceiver(transceiver, local_description());
2375 if (!content) {
2376 continue;
2377 }
2378 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002379 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2380 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002381 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002382 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2383 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2384 // "recvonly", process the removal of a remote track for the media
2385 // description, given transceiver, removeList, and muteTracks.
2386 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2387 (transceiver->internal()->fired_direction() &&
2388 RtpTransceiverDirectionHasRecv(
2389 *transceiver->internal()->fired_direction()))) {
2390 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2391 &removed_streams);
2392 }
2393 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2394 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002395 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002396 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002397 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002398 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002399 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002400 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002401 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002402 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002403 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002404 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002405 }
2406 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002407 // Media channels will be created only when offer is set. These may use new
2408 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002409 if (type == SdpType::kOffer) {
2410 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2411 // description is applied. Restore back to old description.
2412 RTCError error = CreateChannels(*local_description()->description());
2413 if (!error.ok()) {
2414 return error;
2415 }
2416 }
Steve Antondcc3c022017-12-22 16:02:54 -08002417 // Remove unused channels if MediaContentDescription is rejected.
2418 RemoveUnusedChannels(local_description()->description());
2419 }
Steve Anton8a006912017-12-04 15:25:56 -08002420
Zhi Huange830e682018-03-30 10:48:35 -07002421 error = UpdateSessionState(type, cricket::CS_LOCAL,
2422 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002423 if (!error.ok()) {
2424 return error;
2425 }
Steve Antondcc3c022017-12-22 16:02:54 -08002426
Steve Anton8a006912017-12-04 15:25:56 -08002427 if (remote_description()) {
2428 // Now that we have a local description, we can push down remote candidates.
2429 UseCandidatesInSessionDescription(remote_description());
2430 }
2431
2432 pending_ice_restarts_.clear();
2433 if (session_error() != SessionError::kNone) {
2434 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2435 }
2436
deadbeefab9b2d12015-10-14 11:33:11 -07002437 // If setting the description decided our SSL role, allocate any necessary
2438 // SCTP sids.
2439 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002440 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002441 AllocateSctpSids(role);
2442 }
2443
Steve Antond3679212018-01-17 17:41:02 -08002444 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002445 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002446 const ContentInfo* content =
2447 FindMediaSectionForTransceiver(transceiver, local_description());
2448 if (!content) {
2449 continue;
2450 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002451 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2452 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002453 // 0 is a special value meaning "this sender has no associated send
2454 // stream". Need to call this so the sender won't attempt to configure
2455 // a no longer existing stream and run into DCHECKs in the lower
2456 // layers.
2457 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002458 } else {
2459 // Get the StreamParams from the channel which could generate SSRCs.
2460 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002461 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002462 streams[0].stream_ids());
2463 transceiver->internal()->sender_internal()->SetSsrc(
2464 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002465 }
2466 }
2467 } else {
2468 // Plan B semantics.
2469
Steve Antondcc3c022017-12-22 16:02:54 -08002470 // Update state and SSRC of local MediaStreams and DataChannels based on the
2471 // local session description.
2472 const cricket::ContentInfo* audio_content =
2473 GetFirstAudioContent(local_description()->description());
2474 if (audio_content) {
2475 if (audio_content->rejected) {
2476 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2477 } else {
2478 const cricket::AudioContentDescription* audio_desc =
2479 audio_content->media_description()->as_audio();
2480 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2481 }
deadbeeffaac4972015-11-12 15:33:07 -08002482 }
deadbeefab9b2d12015-10-14 11:33:11 -07002483
Steve Antondcc3c022017-12-22 16:02:54 -08002484 const cricket::ContentInfo* video_content =
2485 GetFirstVideoContent(local_description()->description());
2486 if (video_content) {
2487 if (video_content->rejected) {
2488 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2489 } else {
2490 const cricket::VideoContentDescription* video_desc =
2491 video_content->media_description()->as_video();
2492 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2493 }
deadbeeffaac4972015-11-12 15:33:07 -08002494 }
deadbeefab9b2d12015-10-14 11:33:11 -07002495 }
2496
2497 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002498 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002499 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002500 const cricket::RtpDataContentDescription* rtp_data_desc =
2501 data_content->media_description()->as_rtp_data();
2502 // rtp_data_desc will be null if this is an SCTP description.
2503 if (rtp_data_desc) {
2504 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002505 }
2506 }
2507
Henrik Boström79b69802019-07-18 11:16:56 +02002508 if (type == SdpType::kAnswer &&
2509 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2510 *current_local_description_)) {
2511 local_ice_credentials_to_replace_->ClearIceCredentials();
2512 }
2513
Steve Anton8a006912017-12-04 15:25:56 -08002514 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002515}
2516
Steve Anton06817cd2018-12-18 15:55:30 -08002517// The SDP parser used to populate these values by default for the 'content
2518// name' if an a=mid line was absent.
2519static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2520 switch (media_type) {
2521 case cricket::MEDIA_TYPE_AUDIO:
2522 return cricket::CN_AUDIO;
2523 case cricket::MEDIA_TYPE_VIDEO:
2524 return cricket::CN_VIDEO;
2525 case cricket::MEDIA_TYPE_DATA:
2526 return cricket::CN_DATA;
2527 }
2528 RTC_NOTREACHED();
2529 return "";
2530}
2531
2532void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002533 cricket::SessionDescription* new_remote_description) {
2534 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002535 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002536 const cricket::ContentInfos& local_contents =
2537 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002538 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002539 const cricket::ContentInfos& remote_contents =
2540 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002541 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002542 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2543 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002544 if (!content.name.empty()) {
2545 continue;
2546 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002547 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002548 absl::string_view source_explanation;
2549 if (IsUnifiedPlan()) {
2550 if (i < local_contents.size()) {
2551 new_mid = local_contents[i].name;
2552 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002553 } else if (i < remote_contents.size()) {
2554 new_mid = remote_contents[i].name;
2555 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002556 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002557 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002558 source_explanation = "generated just now";
2559 }
2560 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002561 new_mid = std::string(
2562 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002563 source_explanation = "to match pre-existing behavior";
2564 }
Steve Antond7180cc2019-02-07 10:44:53 -08002565 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002566 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002567 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002568 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2569 << " is missing an a=mid line. Filling in the value '"
2570 << new_mid << "' " << source_explanation << ".";
2571 }
2572}
2573
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002574void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002575 SetSessionDescriptionObserver* observer,
2576 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002577 SetRemoteDescription(
2578 std::unique_ptr<SessionDescriptionInterface>(desc),
2579 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2580 new SetRemoteDescriptionObserverAdapter(this, observer)));
2581}
2582
2583void PeerConnection::SetRemoteDescription(
2584 std::unique_ptr<SessionDescriptionInterface> desc,
2585 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002586 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002587 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002588
nisse7ce109a2017-01-31 00:57:56 -08002589 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002590 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002591 return;
2592 }
Steve Anton8a006912017-12-04 15:25:56 -08002593
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002595 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002596 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002597 return;
2598 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002599
Steve Anton80dd7b52018-02-16 17:08:42 -08002600 // If a session error has occurred the PeerConnection is in a possibly
2601 // inconsistent state so fail right away.
2602 if (session_error() != SessionError::kNone) {
2603 std::string error_message = GetSessionErrorMsg();
2604 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2605 observer->OnSetRemoteDescriptionComplete(
2606 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2607 return;
2608 }
Steve Anton71439a62018-02-15 11:53:06 -08002609
Steve Antonba42e992018-04-09 14:10:01 -07002610 if (desc->GetType() == SdpType::kOffer) {
2611 // Report to UMA the format of the received offer.
2612 ReportSdpFormatReceived(*desc);
2613 }
2614
Steve Anton06817cd2018-12-18 15:55:30 -08002615 // Handle remote descriptions missing a=mid lines for interop with legacy end
2616 // points.
2617 FillInMissingRemoteMids(desc->description());
2618
Steve Anton80dd7b52018-02-16 17:08:42 -08002619 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002620 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002621 std::string error_message = GetSetDescriptionErrorMessage(
2622 cricket::CS_REMOTE, desc->GetType(), error);
2623 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002624 observer->OnSetRemoteDescriptionComplete(
2625 RTCError(error.type(), std::move(error_message)));
2626 return;
2627 }
Steve Anton71439a62018-02-15 11:53:06 -08002628
Steve Anton80dd7b52018-02-16 17:08:42 -08002629 // Grab the description type before moving ownership to
2630 // ApplyRemoteDescription, which may destroy it before returning.
2631 const SdpType type = desc->GetType();
2632
2633 error = ApplyRemoteDescription(std::move(desc));
2634 // |desc| may be destroyed at this point.
2635
2636 if (!error.ok()) {
2637 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2638 // inconsistent state, so act conservatively here and set the session error
2639 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2640 SetSessionError(SessionError::kContent, error.message());
2641 std::string error_message =
2642 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2643 RTC_LOG(LS_ERROR) << error_message;
2644 observer->OnSetRemoteDescriptionComplete(
2645 RTCError(error.type(), std::move(error_message)));
2646 return;
2647 }
2648 RTC_DCHECK(remote_description());
2649
2650 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002651 // TODO(deadbeef): We already had to hop to the network thread for
2652 // MaybeStartGathering...
2653 network_thread()->Invoke<void>(
2654 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2655 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002656 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002657 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002658 }
2659
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002660 if (IsUnifiedPlan()) {
2661 bool was_negotiation_needed = is_negotiation_needed_;
2662 UpdateNegotiationNeeded();
2663 if (signaling_state() == kStable && was_negotiation_needed &&
2664 is_negotiation_needed_) {
2665 Observer()->OnRenegotiationNeeded();
2666 }
2667 }
2668
Steve Anton8a006912017-12-04 15:25:56 -08002669 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002670 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002671}
2672
2673RTCError PeerConnection::ApplyRemoteDescription(
2674 std::unique_ptr<SessionDescriptionInterface> desc) {
2675 RTC_DCHECK_RUN_ON(signaling_thread());
2676 RTC_DCHECK(desc);
2677
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002678 // Update stats here so that we have the most recent stats for tracks and
2679 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002680 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002681
Steve Antondcc3c022017-12-22 16:02:54 -08002682 // Take a reference to the old remote description since it's used below to
2683 // compare against the new remote description. When setting the new remote
2684 // description, grab ownership of the replaced session description in case it
2685 // is the same as |old_remote_description|, to keep it alive for the duration
2686 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002687 const SessionDescriptionInterface* old_remote_description =
2688 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002689 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002690 SdpType type = desc->GetType();
2691 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002692 replaced_remote_description = pending_remote_description_
2693 ? std::move(pending_remote_description_)
2694 : std::move(current_remote_description_);
2695 current_remote_description_ = std::move(desc);
2696 pending_remote_description_ = nullptr;
2697 current_local_description_ = std::move(pending_local_description_);
2698 } else {
2699 replaced_remote_description = std::move(pending_remote_description_);
2700 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 }
Steve Anton8a006912017-12-04 15:25:56 -08002702 // The session description to apply now must be accessed by
2703 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002704 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002706 // Report statistics about any use of simulcast.
2707 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2708 *remote_description()->description());
2709
Zhi Huange830e682018-03-30 10:48:35 -07002710 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2711 if (!error.ok()) {
2712 return error;
2713 }
Steve Anton8a006912017-12-04 15:25:56 -08002714 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002715 if (IsUnifiedPlan()) {
2716 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002717 cricket::CS_REMOTE, *remote_description(), local_description(),
2718 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002719 if (!error.ok()) {
2720 return error;
2721 }
Steve Antondcc3c022017-12-22 16:02:54 -08002722 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002723 // Media channels will be created only when offer is set. These may use new
2724 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002725 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002726 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002727 // description is applied. Restore back to old description.
2728 RTCError error = CreateChannels(*remote_description()->description());
2729 if (!error.ok()) {
2730 return error;
2731 }
2732 }
Steve Antondcc3c022017-12-22 16:02:54 -08002733 // Remove unused channels if MediaContentDescription is rejected.
2734 RemoveUnusedChannels(remote_description()->description());
2735 }
Steve Anton8a006912017-12-04 15:25:56 -08002736
Zhi Huange830e682018-03-30 10:48:35 -07002737 // NOTE: Candidates allocation will be initiated only when
2738 // SetLocalDescription is called.
2739 error = UpdateSessionState(type, cricket::CS_REMOTE,
2740 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002741 if (!error.ok()) {
2742 return error;
2743 }
2744
2745 if (local_description() &&
2746 !UseCandidatesInSessionDescription(remote_description())) {
2747 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2748 }
2749
2750 if (old_remote_description) {
2751 for (const cricket::ContentInfo& content :
2752 old_remote_description->description()->contents()) {
2753 // Check if this new SessionDescription contains new ICE ufrag and
2754 // password that indicates the remote peer requests an ICE restart.
2755 // TODO(deadbeef): When we start storing both the current and pending
2756 // remote description, this should reset pending_ice_restarts and compare
2757 // against the current description.
2758 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2759 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002760 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002761 pending_ice_restarts_.insert(content.name);
2762 }
2763 } else {
2764 // We retain all received candidates only if ICE is not restarted.
2765 // When ICE is restarted, all previous candidates belong to an old
2766 // generation and should not be kept.
2767 // TODO(deadbeef): This goes against the W3C spec which says the remote
2768 // description should only contain candidates from the last set remote
2769 // description plus any candidates added since then. We should remove
2770 // this once we're sure it won't break anything.
2771 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2772 old_remote_description, content.name, mutable_remote_description());
2773 }
2774 }
2775 }
2776
2777 if (session_error() != SessionError::kNone) {
2778 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2779 }
2780
2781 // Set the the ICE connection state to connecting since the connection may
2782 // become writable with peer reflexive candidates before any remote candidate
2783 // is signaled.
2784 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2785 // is to have a new signal the indicates a change in checking state from the
2786 // transport and expose a new checking() member from transport that can be
2787 // read to determine the current checking state. The existing SignalConnecting
2788 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002789 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002790 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002791 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2792 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2793 }
2794
deadbeefab9b2d12015-10-14 11:33:11 -07002795 // If setting the description decided our SSL role, allocate any necessary
2796 // SCTP sids.
2797 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002798 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002799 AllocateSctpSids(role);
2800 }
2801
Steve Antondcc3c022017-12-22 16:02:54 -08002802 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002803 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002804 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002805 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002806 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002807 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002808 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002809 const ContentInfo* content =
2810 FindMediaSectionForTransceiver(transceiver, remote_description());
2811 if (!content) {
2812 continue;
2813 }
2814 const MediaContentDescription* media_desc = content->media_description();
2815 RtpTransceiverDirection local_direction =
2816 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002817 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2818 // RTCSessionDescription: Set the associated remote streams given
2819 // transceiver.[[Receiver]], msids, addList, and removeList".
2820 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2821 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2822 std::vector<std::string> stream_ids;
2823 if (!media_desc->streams().empty()) {
2824 // The remote description has signaled the stream IDs.
2825 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002826 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002827 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2828 << " (" << GetStreamIdsString(stream_ids) << ").";
2829 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2830 stream_ids, &added_streams,
2831 &removed_streams);
2832 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2833 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2834 // and transceiver's current direction is neither sendrecv nor recvonly,
2835 // process the addition of a remote track for the media description.
2836 if (!transceiver->fired_direction() ||
2837 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2838 RTC_LOG(LS_INFO)
2839 << "Processing the addition of a remote track for MID="
2840 << content->name << ".";
2841 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002842 }
Steve Antondcc3c022017-12-22 16:02:54 -08002843 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002844 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002845 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2846 // removal of a remote track for the media description, given transceiver,
2847 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002848 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002849 (transceiver->fired_direction() &&
2850 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2851 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2852 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002853 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002854 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002855 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002856 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002857 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002858 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002859 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002860 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002861 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002862 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2863 if (transceiver->mid()) {
2864 auto dtls_transport =
2865 LookupDtlsTransportByMidInternal(*transceiver->mid());
2866 transceiver->internal()->sender_internal()->set_transport(
2867 dtls_transport);
2868 transceiver->internal()->receiver_internal()->set_transport(
2869 dtls_transport);
2870 }
Steve Antondcc3c022017-12-22 16:02:54 -08002871 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002872 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002873 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002874 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002875 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2876 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002877 transceiver->Stop();
2878 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002879 if (!content->rejected &&
2880 RtpTransceiverDirectionHasRecv(local_direction)) {
2881 // Set ssrc to 0 in the case of an unsignalled ssrc.
2882 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002883 if (!media_desc->streams().empty() &&
2884 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002885 ssrc = media_desc->streams()[0].first_ssrc();
2886 }
2887 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002888 }
Steve Antondcc3c022017-12-22 16:02:54 -08002889 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002890 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002891 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002892 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002893 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002894 observer->OnTrack(transceiver);
2895 observer->OnAddTrack(transceiver->receiver(),
2896 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002897 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002898 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002899 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002900 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002901 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002902 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002903 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002904 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002905 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002906 }
Steve Antondcc3c022017-12-22 16:02:54 -08002907 }
2908
Henrik Boströmfdb92012017-11-09 19:55:44 +01002909 const cricket::ContentInfo* audio_content =
2910 GetFirstAudioContent(remote_description()->description());
2911 const cricket::ContentInfo* video_content =
2912 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002913 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002914 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002915 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002916 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002917 const cricket::RtpDataContentDescription* rtp_data_desc =
2918 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002919
2920 // Check if the descriptions include streams, just in case the peer supports
2921 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002922 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002923 (audio_desc && !audio_desc->streams().empty()) ||
2924 (video_desc && !video_desc->streams().empty())) {
2925 remote_peer_supports_msid_ = true;
2926 }
deadbeefab9b2d12015-10-14 11:33:11 -07002927
2928 // We wait to signal new streams until we finish processing the description,
2929 // since only at that point will new streams have all their tracks.
2930 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2931
Steve Antondcc3c022017-12-22 16:02:54 -08002932 if (!IsUnifiedPlan()) {
2933 // TODO(steveanton): When removing RTP senders/receivers in response to a
2934 // rejected media section, there is some cleanup logic that expects the
2935 // voice/ video channel to still be set. But in this method the voice/video
2936 // channel would have been destroyed by the SetRemoteDescription caller
2937 // above so the cleanup that relies on them fails to run. The RemoveSenders
2938 // calls should be moved to right before the DestroyChannel calls to fix
2939 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002940
Steve Antondcc3c022017-12-22 16:02:54 -08002941 // Find all audio rtp streams and create corresponding remote AudioTracks
2942 // and MediaStreams.
2943 if (audio_content) {
2944 if (audio_content->rejected) {
2945 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2946 } else {
2947 bool default_audio_track_needed =
2948 !remote_peer_supports_msid_ &&
2949 RtpTransceiverDirectionHasSend(audio_desc->direction());
2950 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2951 default_audio_track_needed, audio_desc->type(),
2952 new_streams);
2953 }
deadbeeffaac4972015-11-12 15:33:07 -08002954 }
deadbeefab9b2d12015-10-14 11:33:11 -07002955
Steve Antondcc3c022017-12-22 16:02:54 -08002956 // Find all video rtp streams and create corresponding remote VideoTracks
2957 // and MediaStreams.
2958 if (video_content) {
2959 if (video_content->rejected) {
2960 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2961 } else {
2962 bool default_video_track_needed =
2963 !remote_peer_supports_msid_ &&
2964 RtpTransceiverDirectionHasSend(video_desc->direction());
2965 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2966 default_video_track_needed, video_desc->type(),
2967 new_streams);
2968 }
deadbeeffaac4972015-11-12 15:33:07 -08002969 }
deadbeefab9b2d12015-10-14 11:33:11 -07002970
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002971 // If this is an RTP data transport, update the DataChannels with the
2972 // information from the remote peer.
2973 if (rtp_data_desc) {
2974 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002975 }
deadbeefab9b2d12015-10-14 11:33:11 -07002976
Steve Antondcc3c022017-12-22 16:02:54 -08002977 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002978 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002979 for (size_t i = 0; i < new_streams->count(); ++i) {
2980 MediaStreamInterface* new_stream = new_streams->at(i);
2981 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002982 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002983 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2984 }
deadbeefab9b2d12015-10-14 11:33:11 -07002985
Steve Antondcc3c022017-12-22 16:02:54 -08002986 UpdateEndedRemoteMediaStreams();
2987 }
deadbeefab9b2d12015-10-14 11:33:11 -07002988
Henrik Boström79b69802019-07-18 11:16:56 +02002989 if (type == SdpType::kAnswer &&
2990 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2991 *current_local_description_)) {
2992 local_ice_credentials_to_replace_->ClearIceCredentials();
2993 }
2994
Steve Anton8a006912017-12-04 15:25:56 -08002995 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002996}
2997
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002998void PeerConnection::SetAssociatedRemoteStreams(
2999 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3000 const std::vector<std::string>& stream_ids,
3001 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3002 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3003 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3004 for (const std::string& stream_id : stream_ids) {
3005 rtc::scoped_refptr<MediaStreamInterface> stream =
3006 remote_streams_->find(stream_id);
3007 if (!stream) {
3008 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3009 MediaStream::Create(stream_id));
3010 remote_streams_->AddStream(stream);
3011 added_streams->push_back(stream);
3012 }
3013 media_streams.push_back(stream);
3014 }
3015 // Special case: "a=msid" missing, use random stream ID.
3016 if (media_streams.empty() &&
3017 !(remote_description()->description()->msid_signaling() &
3018 cricket::kMsidSignalingMediaSection)) {
3019 if (!missing_msid_default_stream_) {
3020 missing_msid_default_stream_ = MediaStreamProxy::Create(
3021 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3022 added_streams->push_back(missing_msid_default_stream_);
3023 }
3024 media_streams.push_back(missing_msid_default_stream_);
3025 }
3026 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3027 receiver->streams();
3028 // SetStreams() will add/remove the receiver's track to/from the streams. This
3029 // differs from the spec - the spec uses an "addList" and "removeList" to
3030 // update the stream-track relationships in a later step. We do this earlier,
3031 // changing the order of things, but the end-result is the same.
3032 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3033 // instead. https://crbug.com/webrtc/9480
3034 receiver->SetStreams(media_streams);
3035 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3036}
3037
Steve Anton0f5400a2018-07-17 14:25:36 -07003038void PeerConnection::ProcessRemovalOfRemoteTrack(
3039 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3040 transceiver,
3041 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3042 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3043 RTC_DCHECK(transceiver->mid());
3044 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3045 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003046 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003047 transceiver->internal()->receiver_internal()->streams();
3048 // This will remove the remote track from the streams.
3049 transceiver->internal()->receiver_internal()->set_stream_ids({});
3050 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003051 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3052}
3053
3054void PeerConnection::RemoveRemoteStreamsIfEmpty(
3055 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3056 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3057 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3058 // streams, see if the stream was removed by checking if this was the last
3059 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003060 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003061 if (remote_stream->GetAudioTracks().empty() &&
3062 remote_stream->GetVideoTracks().empty()) {
3063 remote_streams_->RemoveStream(remote_stream);
3064 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003065 }
3066 }
3067}
3068
Steve Antondcc3c022017-12-22 16:02:54 -08003069RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3070 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003071 const SessionDescriptionInterface& new_session,
3072 const SessionDescriptionInterface* old_local_description,
3073 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003074 RTC_DCHECK(IsUnifiedPlan());
3075
Steve Anton7464fca2018-01-19 11:10:37 -08003076 const cricket::ContentGroup* bundle_group = nullptr;
3077 if (new_session.GetType() == SdpType::kOffer) {
3078 auto bundle_group_or_error =
3079 GetEarlyBundleGroup(*new_session.description());
3080 if (!bundle_group_or_error.ok()) {
3081 return bundle_group_or_error.MoveError();
3082 }
3083 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003084 }
Steve Antondcc3c022017-12-22 16:02:54 -08003085
Steve Antondcc3c022017-12-22 16:02:54 -08003086 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003087 for (size_t i = 0; i < new_contents.size(); ++i) {
3088 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003089 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003090 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003091 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3092 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003093 const cricket::ContentInfo* old_local_content = nullptr;
3094 if (old_local_description &&
3095 i < old_local_description->description()->contents().size()) {
3096 old_local_content =
3097 &old_local_description->description()->contents()[i];
3098 }
3099 const cricket::ContentInfo* old_remote_content = nullptr;
3100 if (old_remote_description &&
3101 i < old_remote_description->description()->contents().size()) {
3102 old_remote_content =
3103 &old_remote_description->description()->contents()[i];
3104 }
Steve Antondcc3c022017-12-22 16:02:54 -08003105 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003106 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3107 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003108 if (!transceiver_or_error.ok()) {
3109 return transceiver_or_error.MoveError();
3110 }
3111 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003112 RTCError error =
3113 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3114 if (!error.ok()) {
3115 return error;
3116 }
3117 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003118 if (GetDataMid() && new_content.name != *GetDataMid()) {
3119 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003120 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3121 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003122 continue;
3123 }
3124 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3125 if (!error.ok()) {
3126 return error;
3127 }
Steve Antondcc3c022017-12-22 16:02:54 -08003128 } else {
3129 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3130 "Unknown section type.");
3131 }
3132 }
3133
3134 return RTCError::OK();
3135}
3136
3137RTCError PeerConnection::UpdateTransceiverChannel(
3138 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3139 transceiver,
3140 const cricket::ContentInfo& content,
3141 const cricket::ContentGroup* bundle_group) {
3142 RTC_DCHECK(IsUnifiedPlan());
3143 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003144 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003145 if (content.rejected) {
3146 if (channel) {
3147 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003148 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003149 }
3150 } else {
3151 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003152 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003153 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003154 } else {
Steve Anton69470252018-02-09 11:43:08 -08003155 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003156 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003157 }
3158 if (!channel) {
3159 LOG_AND_RETURN_ERROR(
3160 RTCErrorType::INTERNAL_ERROR,
3161 "Failed to create channel for mid=" + content.name);
3162 }
3163 transceiver->internal()->SetChannel(channel);
3164 }
3165 }
3166 return RTCError::OK();
3167}
3168
Steve Antonfa2260d2017-12-28 16:38:23 -08003169RTCError PeerConnection::UpdateDataChannel(
3170 cricket::ContentSource source,
3171 const cricket::ContentInfo& content,
3172 const cricket::ContentGroup* bundle_group) {
3173 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003174 // If data channels are disabled, ignore this media section. CreateAnswer
3175 // will take care of rejecting it.
3176 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003177 }
3178 if (content.rejected) {
3179 DestroyDataChannel();
3180 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003181 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003182 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003183 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3184 "Failed to create data channel.");
3185 }
3186 }
3187 if (source == cricket::CS_REMOTE) {
3188 const MediaContentDescription* data_desc = content.media_description();
3189 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3190 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3191 }
3192 }
3193 }
3194 return RTCError::OK();
3195}
3196
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003197// This method will extract any send encodings that were sent by the remote
3198// connection. This is currently only relevant for Simulcast scenario (where
3199// the number of layers may be communicated by the server).
3200static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3201 const MediaContentDescription& desc) {
3202 if (!desc.HasSimulcast()) {
3203 return {};
3204 }
3205 std::vector<RtpEncodingParameters> result;
3206 const SimulcastDescription& simulcast = desc.simulcast_description();
3207
3208 // This is a remote description, the parameters we are after should appear
3209 // as receive streams.
3210 for (const auto& alternatives : simulcast.receive_layers()) {
3211 RTC_DCHECK(!alternatives.empty());
3212 // There is currently no way to specify or choose from alternatives.
3213 // We will always use the first alternative, which is the most preferred.
3214 const SimulcastLayer& layer = alternatives[0];
3215 RtpEncodingParameters parameters;
3216 parameters.rid = layer.rid;
3217 parameters.active = !layer.is_paused;
3218 result.push_back(parameters);
3219 }
3220
3221 return result;
3222}
3223
3224static RTCError UpdateSimulcastLayerStatusInSender(
3225 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003226 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003227 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003228 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003229 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003230
3231 // The simulcast envelope cannot be changed, only the status of the streams.
3232 // So we will iterate over the send encodings rather than the layers.
3233 for (RtpEncodingParameters& encoding : parameters.encodings) {
3234 auto iter = std::find_if(layers.begin(), layers.end(),
3235 [&encoding](const SimulcastLayer& layer) {
3236 return layer.rid == encoding.rid;
3237 });
3238 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003239 if (iter == layers.end()) {
3240 disabled_layers.push_back(encoding.rid);
3241 continue;
3242 }
3243
3244 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003245 }
3246
Amit Hilbuch619b2942019-02-26 15:55:19 -08003247 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003248 if (result.ok()) {
3249 result = sender->DisableEncodingLayers(disabled_layers);
3250 }
3251
3252 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003253}
3254
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003255static bool SimulcastIsRejected(
3256 const ContentInfo* local_content,
3257 const MediaContentDescription& answer_media_desc) {
3258 bool simulcast_offered = local_content &&
3259 local_content->media_description() &&
3260 local_content->media_description()->HasSimulcast();
3261 bool simulcast_answered = answer_media_desc.HasSimulcast();
3262 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3263 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3264 return simulcast_offered && (!simulcast_answered || !rids_supported);
3265}
3266
Amit Hilbuch2297d332019-02-19 12:49:22 -08003267static RTCError DisableSimulcastInSender(
3268 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003269 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003270 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003271 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003272 return RTCError::OK();
3273 }
3274
Amit Hilbuch2297d332019-02-19 12:49:22 -08003275 std::vector<std::string> disabled_layers;
3276 std::transform(
3277 parameters.encodings.begin() + 1, parameters.encodings.end(),
3278 std::back_inserter(disabled_layers),
3279 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3280 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003281}
3282
Steve Antondcc3c022017-12-22 16:02:54 -08003283RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3284PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003285 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003286 size_t mline_index,
3287 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003288 const ContentInfo* old_local_content,
3289 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003290 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003291 // If this is an offer then the m= section might be recycled. If the m=
3292 // section is being recycled (defined as: rejected in the current local or
3293 // remote description and not rejected in new description), dissociate the
3294 // currently associated RtpTransceiver by setting its mid property to null,
3295 // and discard the mapping between the transceiver and its m= section index.
3296 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3297 old_remote_content)) {
3298 // We want to dissociate the transceiver that has the rejected mid.
3299 const std::string& old_mid =
3300 (old_local_content && old_local_content->rejected)
3301 ? old_local_content->name
3302 : old_remote_content->name;
3303 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003304 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003305 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3306 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003307 old_transceiver->internal()->set_mid(absl::nullopt);
3308 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003309 }
3310 }
3311 const MediaContentDescription* media_desc = content.media_description();
3312 auto transceiver = GetAssociatedTransceiver(content.name);
3313 if (source == cricket::CS_LOCAL) {
3314 // Find the RtpTransceiver that corresponds to this m= section, using the
3315 // mapping between transceivers and m= section indices established when
3316 // creating the offer.
3317 if (!transceiver) {
3318 transceiver = GetTransceiverByMLineIndex(mline_index);
3319 }
3320 if (!transceiver) {
3321 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3322 "Unknown transceiver");
3323 }
3324 } else {
3325 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3326 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3327 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003328 // When simulcast is requested, a transceiver cannot be associated because
3329 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003330 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003331 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3332 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003333 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3334 }
3335 // If no RtpTransceiver was found in the previous step, create one with a
3336 // recvonly direction.
3337 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003338 RTC_LOG(LS_INFO) << "Adding "
3339 << cricket::MediaTypeToString(media_desc->type())
3340 << " transceiver for MID=" << content.name
3341 << " at i=" << mline_index
3342 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003343 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003344 std::vector<RtpEncodingParameters> send_encodings =
3345 GetSendEncodingsFromRemoteDescription(*media_desc);
3346 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3347 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003348 std::string receiver_id;
3349 if (!media_desc->streams().empty()) {
3350 receiver_id = media_desc->streams()[0].id;
3351 } else {
3352 receiver_id = rtc::CreateRandomUuid();
3353 }
3354 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003355 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003356 transceiver->internal()->set_direction(
3357 RtpTransceiverDirection::kRecvOnly);
3358 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003359
3360 // Check if the offer indicated simulcast but the answer rejected it.
3361 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003362 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003363 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003364 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003365 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003366 if (!error.ok()) {
3367 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3368 return std::move(error);
3369 }
3370 }
Steve Antondcc3c022017-12-22 16:02:54 -08003371 }
3372 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003373 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003374 LOG_AND_RETURN_ERROR(
3375 RTCErrorType::INVALID_PARAMETER,
3376 "Transceiver type does not match media description type.");
3377 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003378 if (media_desc->HasSimulcast()) {
3379 std::vector<SimulcastLayer> layers =
3380 source == cricket::CS_LOCAL
3381 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3382 : media_desc->simulcast_description()
3383 .receive_layers()
3384 .GetAllLayers();
3385 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003386 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003387 if (!error.ok()) {
3388 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3389 return std::move(error);
3390 }
3391 }
Steve Antondcc3c022017-12-22 16:02:54 -08003392 // Associate the found or created RtpTransceiver with the m= section by
3393 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3394 // section, and establish a mapping between the transceiver and the index of
3395 // the m= section.
3396 transceiver->internal()->set_mid(content.name);
3397 transceiver->internal()->set_mline_index(mline_index);
3398 return std::move(transceiver);
3399}
3400
3401rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3402PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3403 RTC_DCHECK(IsUnifiedPlan());
3404 for (auto transceiver : transceivers_) {
3405 if (transceiver->mid() == mid) {
3406 return transceiver;
3407 }
3408 }
3409 return nullptr;
3410}
3411
3412rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3413PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3414 RTC_DCHECK(IsUnifiedPlan());
3415 for (auto transceiver : transceivers_) {
3416 if (transceiver->internal()->mline_index() == mline_index) {
3417 return transceiver;
3418 }
3419 }
3420 return nullptr;
3421}
3422
3423rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3424PeerConnection::FindAvailableTransceiverToReceive(
3425 cricket::MediaType media_type) const {
3426 RTC_DCHECK(IsUnifiedPlan());
3427 // From JSEP section 5.10 (Applying a Remote Description):
3428 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3429 // the same type that were added to the PeerConnection by addTrack and are not
3430 // associated with any m= section and are not stopped, find the first such
3431 // RtpTransceiver.
3432 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003433 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003434 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3435 !transceiver->stopped()) {
3436 return transceiver;
3437 }
3438 }
3439 return nullptr;
3440}
3441
Steve Antoned10bd92017-12-05 10:52:59 -08003442const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3443 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3444 transceiver,
3445 const SessionDescriptionInterface* sdesc) const {
3446 RTC_DCHECK(transceiver);
3447 RTC_DCHECK(sdesc);
3448 if (IsUnifiedPlan()) {
3449 if (!transceiver->internal()->mid()) {
3450 // This transceiver is not associated with a media section yet.
3451 return nullptr;
3452 }
3453 return sdesc->description()->GetContentByName(
3454 *transceiver->internal()->mid());
3455 } else {
3456 // Plan B only allows at most one audio and one video section, so use the
3457 // first media section of that type.
3458 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003459 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003460 }
3461}
3462
deadbeef46c73892016-11-16 19:42:04 -08003463PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003464 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003465 return configuration_;
3466}
3467
deadbeef293e9262017-01-11 12:28:30 -08003468bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3469 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003470 RTC_DCHECK_RUN_ON(signaling_thread());
3471 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003472 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003473 if (IsClosed()) {
3474 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3475 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3476 }
3477
Qingsi Wanga2d60672018-04-11 16:57:45 -07003478 // According to JSEP, after setLocalDescription, changing the candidate pool
3479 // size is not allowed, and changing the set of ICE servers will not result
3480 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003481 if (local_description() && configuration.ice_candidate_pool_size !=
3482 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003483 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3484 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003485 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003486 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003487
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003488 if (local_description() &&
3489 configuration.use_media_transport != configuration_.use_media_transport) {
3490 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3491 "SetLocalDescription.";
3492 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3493 }
3494
3495 if (remote_description() &&
3496 configuration.use_media_transport != configuration_.use_media_transport) {
3497 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3498 "SetRemoteDescription.";
3499 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3500 }
3501
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003502 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003503 configuration.use_media_transport_for_data_channels !=
3504 configuration_.use_media_transport_for_data_channels) {
3505 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3506 "after calling SetLocalDescription.";
3507 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3508 }
3509
3510 if (remote_description() &&
3511 configuration.use_media_transport_for_data_channels !=
3512 configuration_.use_media_transport_for_data_channels) {
3513 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3514 "after calling SetRemoteDescription.";
3515 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3516 }
3517
3518 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003519 configuration.crypto_options != configuration_.crypto_options) {
3520 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3521 "SetLocalDescription.";
3522 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3523 }
3524
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003525 if (local_description() && configuration.use_datagram_transport !=
3526 configuration_.use_datagram_transport) {
3527 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3528 "after calling SetLocalDescription.";
3529 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3530 }
3531
3532 if (remote_description() && configuration.use_datagram_transport !=
3533 configuration_.use_datagram_transport) {
3534 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3535 "after calling SetRemoteDescription.";
3536 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3537 }
3538
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003539 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003540 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003541 (configuration.use_datagram_transport &&
3542 *configuration.use_datagram_transport)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003543 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3544 << "Media transport requires MaxBundle policy.";
3545 }
3546
deadbeef293e9262017-01-11 12:28:30 -08003547 // The simplest (and most future-compatible) way to tell if the config was
3548 // modified in an invalid way is to copy each property we do support
3549 // modifying, then use operator==. There are far more properties we don't
3550 // support modifying than those we do, and more could be added.
3551 RTCConfiguration modified_config = configuration_;
3552 modified_config.servers = configuration.servers;
3553 modified_config.type = configuration.type;
3554 modified_config.ice_candidate_pool_size =
3555 configuration.ice_candidate_pool_size;
3556 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003557 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3558 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003559 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003560 modified_config.ice_check_interval_strong_connectivity =
3561 configuration.ice_check_interval_strong_connectivity;
3562 modified_config.ice_check_interval_weak_connectivity =
3563 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003564 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3565 modified_config.ice_unwritable_min_checks =
3566 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003567 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003568 modified_config.stun_candidate_keepalive_interval =
3569 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003570 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003571 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003572 modified_config.active_reset_srtp_params =
3573 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003574 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003575 modified_config.use_media_transport_for_data_channels =
3576 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003577 modified_config.use_datagram_transport = configuration.use_datagram_transport;
deadbeef293e9262017-01-11 12:28:30 -08003578 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003579 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003580 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3581 }
3582
Steve Anton038834f2017-07-14 15:59:59 -07003583 // Validate the modified configuration.
3584 RTCError validate_error = ValidateConfiguration(modified_config);
3585 if (!validate_error.ok()) {
3586 return SafeSetError(std::move(validate_error), error);
3587 }
3588
deadbeef293e9262017-01-11 12:28:30 -08003589 // Note that this isn't possible through chromium, since it's an unsigned
3590 // short in WebIDL.
3591 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003592 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003593 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3594 }
3595
3596 // Parse ICE servers before hopping to network thread.
3597 cricket::ServerAddresses stun_servers;
3598 std::vector<cricket::RelayServerConfig> turn_servers;
3599 RTCErrorType parse_error =
3600 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3601 if (parse_error != RTCErrorType::NONE) {
3602 return SafeSetError(parse_error, error);
3603 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003604 // Note if STUN or TURN servers were supplied.
3605 if (!stun_servers.empty()) {
3606 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3607 }
3608 if (!turn_servers.empty()) {
3609 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3610 }
deadbeef293e9262017-01-11 12:28:30 -08003611
3612 // In theory this shouldn't fail.
3613 if (!network_thread()->Invoke<bool>(
3614 RTC_FROM_HERE,
3615 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3616 stun_servers, turn_servers, modified_config.type,
3617 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003618 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003619 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003620 modified_config.stun_candidate_keepalive_interval,
3621 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003622 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003623 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3624 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003625
deadbeefd1a38b52016-12-10 13:15:33 -08003626 // As described in JSEP, calling setConfiguration with new ICE servers or
3627 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3628 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003629 if (modified_config.servers != configuration_.servers ||
3630 modified_config.type != configuration_.type ||
3631 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003632 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003633 }
skvladd1f5fda2017-02-03 16:54:05 -08003634
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003635 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003636
3637 use_datagram_transport_ = datagram_transport_config_.enabled &&
3638 modified_config.use_datagram_transport.value_or(
3639 datagram_transport_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003640 transport_controller_->SetMediaTransportSettings(
3641 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003642 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003643 use_datagram_transport_);
skvladd1f5fda2017-02-03 16:54:05 -08003644
Zhi Huangb57e1692018-06-12 11:41:11 -07003645 if (configuration_.active_reset_srtp_params !=
3646 modified_config.active_reset_srtp_params) {
3647 transport_controller_->SetActiveResetSrtpParams(
3648 modified_config.active_reset_srtp_params);
3649 }
3650
deadbeef293e9262017-01-11 12:28:30 -08003651 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003652 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003653 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003654}
3655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003656bool PeerConnection::AddIceCandidate(
3657 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003658 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003659 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003660 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003661 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003662 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003663 return false;
3664 }
Steve Antond25da372017-11-06 14:50:29 -08003665
3666 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003667 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003668 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003669 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003670 return false;
3671 }
3672
3673 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003674 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003675 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003676 return false;
3677 }
3678
3679 bool valid = false;
3680 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3681 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003682 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003683 return false;
3684 }
3685
3686 // Add this candidate to the remote session description.
3687 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003688 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003689 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003690 return false;
3691 }
3692
3693 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003694 bool result = UseCandidate(ice_candidate);
3695 if (result) {
3696 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003697 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3698 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3699 }
3700 if (ice_candidate->candidate().address().IsPrivateIP()) {
3701 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3702 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003703 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3704 } else {
3705 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3706 }
3707 return result;
Steve Antond25da372017-11-06 14:50:29 -08003708 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003709 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003710 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003711 return true;
3712 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003713}
3714
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003715bool PeerConnection::RemoveIceCandidates(
3716 const std::vector<cricket::Candidate>& candidates) {
3717 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003718 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003719 if (IsClosed()) {
3720 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3721 return false;
3722 }
3723
Steve Antond25da372017-11-06 14:50:29 -08003724 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003725 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3726 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003727 return false;
3728 }
3729
3730 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003731 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003732 return false;
3733 }
3734
3735 size_t number_removed =
3736 mutable_remote_description()->RemoveCandidates(candidates);
3737 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003738 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003739 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003740 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003741 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003742 }
3743
3744 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003745 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3746 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003747 RTC_LOG(LS_ERROR)
3748 << "RemoveIceCandidates: Error when removing remote candidates: "
3749 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003750 }
3751 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003752}
3753
Niels Möller0c4f7be2018-05-07 14:01:37 +02003754RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003755 if (!worker_thread()->IsCurrent()) {
3756 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003757 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003758 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003759 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003760
Niels Möller0c4f7be2018-05-07 14:01:37 +02003761 const bool has_min = bitrate.min_bitrate_bps.has_value();
3762 const bool has_start = bitrate.start_bitrate_bps.has_value();
3763 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003764 if (has_min && *bitrate.min_bitrate_bps < 0) {
3765 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3766 "min_bitrate_bps <= 0");
3767 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003768 if (has_start) {
3769 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003771 "start_bitrate_bps < min_bitrate_bps");
3772 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003773 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3774 "curent_bitrate_bps < 0");
3775 }
3776 }
3777 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003778 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003779 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003780 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003781 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3782 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3783 "max_bitrate_bps < min_bitrate_bps");
3784 } else if (*bitrate.max_bitrate_bps < 0) {
3785 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3786 "max_bitrate_bps < 0");
3787 }
3788 }
3789
zstein4b979802017-06-02 14:37:37 -07003790 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003791 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003792
3793 return RTCError::OK();
3794}
3795
henrika5f6bf242017-11-01 11:06:56 +01003796void PeerConnection::SetAudioPlayout(bool playout) {
3797 if (!worker_thread()->IsCurrent()) {
3798 worker_thread()->Invoke<void>(
3799 RTC_FROM_HERE,
3800 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3801 return;
3802 }
3803 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003804 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003805 audio_state->SetPlayout(playout);
3806}
3807
3808void PeerConnection::SetAudioRecording(bool recording) {
3809 if (!worker_thread()->IsCurrent()) {
3810 worker_thread()->Invoke<void>(
3811 RTC_FROM_HERE,
3812 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3813 return;
3814 }
3815 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003816 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003817 audio_state->SetRecording(recording);
3818}
3819
Steve Anton8c0f7a72017-10-03 10:03:10 -07003820std::unique_ptr<rtc::SSLCertificate>
3821PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003822 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3823 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003824 return nullptr;
3825 }
Steve Antonf25303e2018-10-16 15:23:31 -07003826 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003827}
3828
Zhi Huang70b820f2018-01-27 14:16:15 -08003829std::unique_ptr<rtc::SSLCertChain>
3830PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003831 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003832 auto audio_transceiver = GetFirstAudioTransceiver();
3833 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003834 return nullptr;
3835 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003836 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003837 audio_transceiver->internal()->channel()->transport_name());
3838}
3839
3840rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3841PeerConnection::GetFirstAudioTransceiver() const {
3842 for (auto transceiver : transceivers_) {
3843 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3844 return transceiver;
3845 }
3846 }
3847 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003848}
3849
Bjorn Tereliusde939432017-11-20 17:38:14 +01003850bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3851 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003852 // TODO(eladalon): In C++14, this can be done with a lambda.
3853 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003854 bool operator()() {
3855 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3856 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003857 PeerConnection* const pc;
3858 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003859 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003860 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003861 return worker_thread()->Invoke<bool>(
3862 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003863}
3864
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003865bool PeerConnection::StartRtcEventLog(
3866 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003867 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3868 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3869 output_period_ms = 5000;
3870 }
3871 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003872}
3873
ivoc14d5dbe2016-07-04 07:06:55 -07003874void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003875 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003876 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3877}
3878
Harald Alvestrandad88c882018-11-28 16:47:46 +01003879rtc::scoped_refptr<DtlsTransportInterface>
3880PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003881 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003882 return transport_controller_->LookupDtlsTransportByMid(mid);
3883}
3884
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003885rtc::scoped_refptr<DtlsTransport>
3886PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003887 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003888 return transport_controller_->LookupDtlsTransportByMid(mid);
3889}
3890
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003891rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3892 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003893 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003894 return sctp_transport_;
3895}
3896
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003897const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003898 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003899 return pending_local_description_ ? pending_local_description_.get()
3900 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003901}
3902
3903const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003904 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003905 return pending_remote_description_ ? pending_remote_description_.get()
3906 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003907}
3908
deadbeeffe4a8a42016-12-20 17:56:17 -08003909const SessionDescriptionInterface* PeerConnection::current_local_description()
3910 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003911 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003912 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003913}
3914
3915const SessionDescriptionInterface* PeerConnection::current_remote_description()
3916 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003917 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003918 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003919}
3920
3921const SessionDescriptionInterface* PeerConnection::pending_local_description()
3922 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003923 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003924 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003925}
3926
3927const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3928 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003929 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003930 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003931}
3932
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003933void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003934 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003935 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003936 // Update stats here so that we have the most recent stats for tracks and
3937 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003938 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003939
Steve Anton75737c02017-11-06 10:37:17 -08003940 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003941 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003942
Mirko Bonadei739baf02019-01-27 17:29:42 +01003943 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003944 transceiver->Stop();
3945 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003946
3947 // Ensure that all asynchronous stats requests are completed before destroying
3948 // the transport controller below.
3949 if (stats_collector_) {
3950 stats_collector_->WaitForPendingRequest();
3951 }
3952
3953 // Don't destroy BaseChannels until after stats has been cleaned up so that
3954 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003955 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003956
Qingsi Wang93a84392018-01-30 17:13:09 -08003957 // The event log is used in the transport controller, which must be outlived
3958 // by the former. CreateOffer by the peer connection is implemented
3959 // asynchronously and if the peer connection is closed without resetting the
3960 // WebRTC session description factory, the session description factory would
3961 // call the transport controller.
3962 webrtc_session_desc_factory_.reset();
3963 transport_controller_.reset();
3964
deadbeef42a42632017-03-10 15:18:00 -08003965 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003966 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3967 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003968
Steve Anton978b8762017-09-29 12:15:02 -07003969 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003970 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003971 call_.reset();
3972 // The event log must outlive call (and any other object that uses it).
3973 event_log_.reset();
3974 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003975 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003976 // The .h file says that observer can be discarded after close() returns.
3977 // Make sure this is true.
3978 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003979}
3980
Steve Antonad182762018-09-05 20:22:40 +00003981void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003982 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003983 switch (msg->message_id) {
3984 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3985 SetSessionDescriptionMsg* param =
3986 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3987 param->observer->OnSuccess();
3988 delete param;
3989 break;
3990 }
3991 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3992 SetSessionDescriptionMsg* param =
3993 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3994 param->observer->OnFailure(std::move(param->error));
3995 delete param;
3996 break;
3997 }
3998 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3999 CreateSessionDescriptionMsg* param =
4000 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4001 param->observer->OnFailure(std::move(param->error));
4002 delete param;
4003 break;
4004 }
4005 case MSG_GETSTATS: {
4006 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4007 StatsReports reports;
4008 stats_->GetStats(param->track, &reports);
4009 param->observer->OnComplete(reports);
4010 delete param;
4011 break;
4012 }
4013 case MSG_FREE_DATACHANNELS: {
4014 sctp_data_channels_to_free_.clear();
4015 break;
4016 }
4017 case MSG_REPORT_USAGE_PATTERN: {
4018 ReportUsagePattern();
4019 break;
4020 }
4021 default:
4022 RTC_NOTREACHED() << "Not implemented";
4023 break;
4024 }
4025}
4026
Steve Antonafb0bb72018-02-20 11:35:37 -08004027cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4028 RTC_DCHECK(!IsUnifiedPlan());
4029 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4030 GetAudioTransceiver()->internal()->channel());
4031 if (voice_channel) {
4032 return voice_channel->media_channel();
4033 } else {
4034 return nullptr;
4035 }
4036}
4037
4038cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4039 RTC_DCHECK(!IsUnifiedPlan());
4040 auto* video_channel = static_cast<cricket::VideoChannel*>(
4041 GetVideoTransceiver()->internal()->channel());
4042 if (video_channel) {
4043 return video_channel->media_channel();
4044 } else {
4045 return nullptr;
4046 }
4047}
4048
Steve Anton4171afb2017-11-20 10:20:22 -08004049void PeerConnection::CreateAudioReceiver(
4050 MediaStreamInterface* stream,
4051 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004052 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4053 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004054 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4055 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004056 auto* audio_receiver = new AudioRtpReceiver(
4057 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004058 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004059 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4060 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4061 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004062 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004063 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004064 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004065}
4066
Steve Anton4171afb2017-11-20 10:20:22 -08004067void PeerConnection::CreateVideoReceiver(
4068 MediaStreamInterface* stream,
4069 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004070 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4071 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004072 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4073 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004074 auto* video_receiver = new VideoRtpReceiver(
4075 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004076 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004077 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4078 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4079 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004080 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004081 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004082 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004083}
4084
deadbeef70ab1a12015-09-28 16:53:55 -07004085// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4086// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004087rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004088 const RtpSenderInfo& remote_sender_info) {
4089 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4090 if (!receiver) {
4091 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4092 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004093 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004094 }
Steve Anton4171afb2017-11-20 10:20:22 -08004095 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4096 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4097 } else {
4098 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4099 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004100 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004101}
4102
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004103void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4104 MediaStreamInterface* stream) {
4105 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004106 RTC_DCHECK(track);
4107 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004108 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004109 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004110 // We already have a sender for this track, so just change the stream_id
4111 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004112 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004113 return;
4114 }
4115
4116 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004117 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004118 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004119 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004120 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004121 // If the sender has already been configured in SDP, we call SetSsrc,
4122 // which will connect the sender to the underlying transport. This can
4123 // occur if a local session description that contains the ID of the sender
4124 // is set before AddStream is called. It can also occur if the local
4125 // session description is not changed and RemoveStream is called, and
4126 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004127 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004128 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004129 if (sender_info) {
4130 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004131 }
4132}
4133
4134// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4135// indefinitely, when we have unified plan SDP.
4136void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4137 MediaStreamInterface* stream) {
4138 RTC_DCHECK(!IsClosed());
4139 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004140 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004141 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4142 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004143 return;
4144 }
Steve Anton4171afb2017-11-20 10:20:22 -08004145 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004146}
4147
4148void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4149 MediaStreamInterface* stream) {
4150 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004151 RTC_DCHECK(track);
4152 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004153 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004154 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004155 // We already have a sender for this track, so just change the stream_id
4156 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004157 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004158 return;
4159 }
4160
4161 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004162 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004163 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004164 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004165 GetVideoTransceiver()->internal()->AddSender(new_sender);
4166 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004167 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004168 if (sender_info) {
4169 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004170 }
4171}
4172
4173void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4174 MediaStreamInterface* stream) {
4175 RTC_DCHECK(!IsClosed());
4176 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004177 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004178 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4179 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004180 return;
4181 }
Steve Anton4171afb2017-11-20 10:20:22 -08004182 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004183}
4184
Steve Antonba818672017-11-06 10:21:57 -08004185void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004186 if (ice_connection_state_ == new_state) {
4187 return;
4188 }
4189
deadbeefcbecd352015-09-23 11:50:27 -07004190 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004191 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004192 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004193 return;
4194 }
Steve Antonba818672017-11-06 10:21:57 -08004195
Mirko Bonadei675513b2017-11-09 11:09:25 +01004196 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4197 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004198 RTC_DCHECK(ice_connection_state_ !=
4199 PeerConnectionInterface::kIceConnectionClosed);
4200
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004201 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004202 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004203}
4204
Alex Loiko9289eda2018-11-23 16:18:59 +00004205void PeerConnection::SetStandardizedIceConnectionState(
4206 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004207 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004208 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004209 }
4210
4211 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004212 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004213 }
4214
4215 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4216 << standardized_ice_connection_state_ << " => " << new_state;
4217
Alex Loiko9289eda2018-11-23 16:18:59 +00004218 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004219 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004220}
4221
Jonas Olsson635474e2018-10-18 15:58:17 +02004222void PeerConnection::SetConnectionState(
4223 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004224 if (connection_state_ == new_state)
4225 return;
4226 if (IsClosed())
4227 return;
4228 connection_state_ = new_state;
4229 Observer()->OnConnectionChange(new_state);
4230}
4231
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004232void PeerConnection::OnIceGatheringChange(
4233 PeerConnectionInterface::IceGatheringState new_state) {
4234 if (IsClosed()) {
4235 return;
4236 }
4237 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004238 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004239}
4240
jbauch81bf7b02017-03-25 08:31:12 -07004241void PeerConnection::OnIceCandidate(
4242 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004243 if (IsClosed()) {
4244 return;
4245 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004246 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004247 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4248 candidate->candidate().address().IsPrivateIP()) {
4249 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4250 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004251 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4252 candidate->candidate().address().IsUnresolvedIP()) {
4253 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4254 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004255 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004256}
4257
Eldar Relloda13ea22019-06-01 12:23:43 +03004258void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4259 const std::string& url,
4260 int error_code,
4261 const std::string& error_text) {
4262 if (IsClosed()) {
4263 return;
4264 }
4265 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4266}
4267
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004268void PeerConnection::OnIceCandidatesRemoved(
4269 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004270 if (IsClosed()) {
4271 return;
4272 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004273 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004274}
4275
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004276void PeerConnection::ChangeSignalingState(
4277 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004278 if (signaling_state_ == signaling_state) {
4279 return;
4280 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004281 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4282 << GetSignalingStateString(signaling_state_)
4283 << " New state: "
4284 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004285 signaling_state_ = signaling_state;
4286 if (signaling_state == kClosed) {
4287 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004288 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004289 standardized_ice_connection_state_ =
4290 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004291 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4292 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004293 if (ice_gathering_state_ != kIceGatheringComplete) {
4294 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004295 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004296 }
4297 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004298 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004299}
4300
deadbeefeb459812015-12-15 19:24:43 -08004301void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4302 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004303 if (IsClosed()) {
4304 return;
4305 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004306 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004307 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004308}
4309
deadbeefeb459812015-12-15 19:24:43 -08004310void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4311 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004312 if (IsClosed()) {
4313 return;
4314 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004315 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004316 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004317}
4318
4319void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4320 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004321 if (IsClosed()) {
4322 return;
4323 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004324 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004325 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004326}
4327
4328void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4329 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004330 if (IsClosed()) {
4331 return;
4332 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004333 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004334 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004335}
4336
Henrik Boström31638672017-11-23 17:48:32 +01004337void PeerConnection::PostSetSessionDescriptionSuccess(
4338 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004339 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4340 signaling_thread()->Post(RTC_FROM_HERE, this,
4341 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004342}
4343
deadbeefab9b2d12015-10-14 11:33:11 -07004344void PeerConnection::PostSetSessionDescriptionFailure(
4345 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004346 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004347 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004348 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4349 msg->error = std::move(error);
4350 signaling_thread()->Post(RTC_FROM_HERE, this,
4351 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004352}
4353
4354void PeerConnection::PostCreateSessionDescriptionFailure(
4355 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004356 RTCError error) {
4357 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004358 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4359 msg->error = std::move(error);
4360 signaling_thread()->Post(RTC_FROM_HERE, this,
4361 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004362}
4363
zhihuang1c378ed2017-08-17 14:10:50 -07004364void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004365 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004366 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004367 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004368
Steve Antondcc3c022017-12-22 16:02:54 -08004369 if (IsUnifiedPlan()) {
4370 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4371 } else {
4372 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4373 }
4374
Steve Antonfa2260d2017-12-28 16:38:23 -08004375 // Intentionally unset the data channel type for RTP data channel with the
4376 // second condition. Otherwise the RTP data channels would be successfully
4377 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4378 // when building with chromium. We want to leave RTP data channels broken, so
4379 // people won't try to use them.
4380 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4381 session_options->data_channel_type = data_channel_type();
4382 }
4383
Steve Antondcc3c022017-12-22 16:02:54 -08004384 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004385 bool ice_restart = offer_answer_options.ice_restart ||
4386 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004387 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004388 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004389 options.transport_options.enable_ice_renomination =
4390 configuration_.enable_ice_renomination;
4391 }
4392
4393 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004394 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004395 session_options->pooled_ice_credentials =
4396 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4397 RTC_FROM_HERE,
4398 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4399 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004400 session_options->offer_extmap_allow_mixed =
4401 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004402
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004403 if (configuration_.use_media_transport ||
4404 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004405 session_options->media_transport_settings =
4406 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4407 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004408
4409 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004410 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004411 for (auto& options : session_options->media_description_options) {
4412 options.transport_options.opaque_parameters =
4413 transport_controller_->GetTransportParameters(options.mid);
4414 }
4415 }
4416
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004417 // Allow fallback for using obsolete SCTP syntax.
4418 // Note that the default in |session_options| is true, while
4419 // the default in |options| is false.
4420 session_options->use_obsolete_sctp_sdp =
4421 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004422}
4423
4424void PeerConnection::GetOptionsForPlanBOffer(
4425 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4426 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004427 // Figure out transceiver directional preferences.
4428 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4429 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4430
4431 // By default, generate sendrecv/recvonly m= sections.
4432 bool recv_audio = true;
4433 bool recv_video = true;
4434
4435 // By default, only offer a new m= section if we have media to send with it.
4436 bool offer_new_audio_description = send_audio;
4437 bool offer_new_video_description = send_video;
4438 bool offer_new_data_description = HasDataChannels();
4439
4440 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004441 if (offer_answer_options.offer_to_receive_audio !=
4442 RTCOfferAnswerOptions::kUndefined) {
4443 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004444 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004445 offer_new_audio_description ||
4446 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004447 }
Steve Antondcc3c022017-12-22 16:02:54 -08004448 if (offer_answer_options.offer_to_receive_video !=
4449 RTCOfferAnswerOptions::kUndefined) {
4450 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004451 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004452 offer_new_video_description ||
4453 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004454 }
4455
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004456 absl::optional<size_t> audio_index;
4457 absl::optional<size_t> video_index;
4458 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004459 // If a current description exists, generate m= sections in the same order,
4460 // using the first audio/video/data section that appears and rejecting
4461 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004462 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004463 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004464 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004465 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4466 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4467 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004468 }
4469
zhihuang1c378ed2017-08-17 14:10:50 -07004470 // Add audio/video/data m= sections to the end if needed.
4471 if (!audio_index && offer_new_audio_description) {
4472 session_options->media_description_options.push_back(
4473 cricket::MediaDescriptionOptions(
4474 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004475 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4476 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004477 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004478 }
zhihuang1c378ed2017-08-17 14:10:50 -07004479 if (!video_index && offer_new_video_description) {
4480 session_options->media_description_options.push_back(
4481 cricket::MediaDescriptionOptions(
4482 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004483 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4484 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004485 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004486 }
zhihuang1c378ed2017-08-17 14:10:50 -07004487 if (!data_index && offer_new_data_description) {
4488 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004489 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004490 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004491 }
4492
4493 cricket::MediaDescriptionOptions* audio_media_description_options =
4494 !audio_index ? nullptr
4495 : &session_options->media_description_options[*audio_index];
4496 cricket::MediaDescriptionOptions* video_media_description_options =
4497 !video_index ? nullptr
4498 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004499
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004500 AddPlanBRtpSenderOptions(GetSendersInternal(),
4501 audio_media_description_options,
4502 video_media_description_options,
4503 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004504}
4505
Steve Antondcc3c022017-12-22 16:02:54 -08004506static cricket::MediaDescriptionOptions
4507GetMediaDescriptionOptionsForTransceiver(
4508 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4509 transceiver,
4510 const std::string& mid) {
4511 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004512 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004513 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004514 media_description_options.codec_preferences =
4515 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004516 // This behavior is specified in JSEP. The gist is that:
4517 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4518 // sendrecv.
4519 // 2. If the MSID is included, then it must be included in any subsequent
4520 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004521 if (transceiver->stopped() ||
4522 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4523 !transceiver->internal()->has_ever_been_used_to_send())) {
4524 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004525 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004526
4527 cricket::SenderOptions sender_options;
4528 sender_options.track_id = transceiver->sender()->id();
4529 sender_options.stream_ids = transceiver->sender()->stream_ids();
4530
4531 // The following sets up RIDs and Simulcast.
4532 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004533 RtpParameters send_parameters =
4534 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004535 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4536 send_parameters.encodings.end(),
4537 [](const RtpEncodingParameters& encoding) {
4538 return !encoding.rid.empty();
4539 });
4540
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004541 std::vector<RidDescription> send_rids;
4542 SimulcastLayerList send_layers;
4543 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4544 if (encoding.rid.empty()) {
4545 continue;
4546 }
4547 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4548 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4549 }
4550
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004551 if (has_rids) {
4552 sender_options.rids = send_rids;
4553 }
4554
4555 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004556 // When RIDs are configured, we must set num_sim_layers to 0 to.
4557 // Otherwise, num_sim_layers must be 1 because either there is no
4558 // simulcast, or simulcast is acheived by munging the SDP.
4559 sender_options.num_sim_layers = has_rids ? 0 : 1;
4560 media_description_options.sender_options.push_back(sender_options);
4561
Steve Antondcc3c022017-12-22 16:02:54 -08004562 return media_description_options;
4563}
4564
Steve Anton5c72e712018-12-10 14:25:30 -08004565// Returns the ContentInfo at mline index |i|, or null if none exists.
4566static const ContentInfo* GetContentByIndex(
4567 const SessionDescriptionInterface* sdesc,
4568 size_t i) {
4569 if (!sdesc) {
4570 return nullptr;
4571 }
4572 const ContentInfos& contents = sdesc->description()->contents();
4573 return (i < contents.size() ? &contents[i] : nullptr);
4574}
4575
Steve Antondcc3c022017-12-22 16:02:54 -08004576void PeerConnection::GetOptionsForUnifiedPlanOffer(
4577 const RTCOfferAnswerOptions& offer_answer_options,
4578 cricket::MediaSessionOptions* session_options) {
4579 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4580 // Offers) and 5.2.2 (Subsequent Offers).
4581 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004582 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004583 const ContentInfos& local_contents =
4584 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004585 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004586 const ContentInfos& remote_contents =
4587 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004588 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004589 // The mline indices that can be recycled. New transceivers should reuse these
4590 // slots first.
4591 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004592 // First, go through each media section that exists in either the local or
4593 // remote description and generate a media section in this offer for the
4594 // associated transceiver. If a media section can be recycled, generate a
4595 // default, rejected media section here that can be later overwritten.
4596 for (size_t i = 0;
4597 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4598 // Either |local_content| or |remote_content| is non-null.
4599 const ContentInfo* local_content =
4600 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004601 const ContentInfo* current_local_content =
4602 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004603 const ContentInfo* remote_content =
4604 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004605 const ContentInfo* current_remote_content =
4606 GetContentByIndex(current_remote_description(), i);
4607 bool had_been_rejected =
4608 (current_local_content && current_local_content->rejected) ||
4609 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004610 const std::string& mid =
4611 (local_content ? local_content->name : remote_content->name);
4612 cricket::MediaType media_type =
4613 (local_content ? local_content->media_description()->type()
4614 : remote_content->media_description()->type());
4615 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4616 media_type == cricket::MEDIA_TYPE_VIDEO) {
4617 auto transceiver = GetAssociatedTransceiver(mid);
4618 RTC_CHECK(transceiver);
4619 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004620 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004621 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004622 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004623 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4624 RtpTransceiverDirection::kInactive,
4625 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004626 recycleable_mline_indices.push(i);
4627 } else {
4628 session_options->media_description_options.push_back(
4629 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4630 // CreateOffer shouldn't really cause any state changes in
4631 // PeerConnection, but we need a way to match new transceivers to new
4632 // media sections in SetLocalDescription and JSEP specifies this is done
4633 // by recording the index of the media section generated for the
4634 // transceiver in the offer.
4635 transceiver->internal()->set_mline_index(i);
4636 }
4637 } else {
4638 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004639 RTC_CHECK(GetDataMid());
4640 if (had_been_rejected || mid != *GetDataMid()) {
4641 session_options->media_description_options.push_back(
4642 GetMediaDescriptionOptionsForRejectedData(mid));
4643 } else {
4644 session_options->media_description_options.push_back(
4645 GetMediaDescriptionOptionsForActiveData(mid));
4646 }
Steve Antondcc3c022017-12-22 16:02:54 -08004647 }
4648 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004649
Steve Antondcc3c022017-12-22 16:02:54 -08004650 // Next, look for transceivers that are newly added (that is, are not stopped
4651 // and not associated). Reuse media sections marked as recyclable first,
4652 // otherwise append to the end of the offer. New media sections should be
4653 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004654 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004655 if (transceiver->mid() || transceiver->stopped()) {
4656 continue;
4657 }
4658 size_t mline_index;
4659 if (!recycleable_mline_indices.empty()) {
4660 mline_index = recycleable_mline_indices.front();
4661 recycleable_mline_indices.pop();
4662 session_options->media_description_options[mline_index] =
4663 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004664 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004665 } else {
4666 mline_index = session_options->media_description_options.size();
4667 session_options->media_description_options.push_back(
4668 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004669 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004670 }
4671 // See comment above for why CreateOffer changes the transceiver's state.
4672 transceiver->internal()->set_mline_index(mline_index);
4673 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004674 // Lastly, add a m-section if we have local data channels and an m section
4675 // does not already exist.
4676 if (!GetDataMid() && HasDataChannels()) {
4677 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004678 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004679 }
Steve Antondcc3c022017-12-22 16:02:54 -08004680}
4681
4682void PeerConnection::GetOptionsForAnswer(
4683 const RTCOfferAnswerOptions& offer_answer_options,
4684 cricket::MediaSessionOptions* session_options) {
4685 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4686
4687 if (IsUnifiedPlan()) {
4688 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4689 } else {
4690 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4691 }
4692
Steve Antonfa2260d2017-12-28 16:38:23 -08004693 // Intentionally unset the data channel type for RTP data channel. Otherwise
4694 // the RTP data channels would be successfully negotiated by default and the
4695 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4696 // We want to leave RTP data channels broken, so people won't try to use them.
4697 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4698 session_options->data_channel_type = data_channel_type();
4699 }
4700
Steve Antondcc3c022017-12-22 16:02:54 -08004701 // Apply ICE renomination flag.
4702 for (auto& options : session_options->media_description_options) {
4703 options.transport_options.enable_ice_renomination =
4704 configuration_.enable_ice_renomination;
4705 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004706
4707 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004708 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004709 session_options->pooled_ice_credentials =
4710 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4711 RTC_FROM_HERE,
4712 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4713 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004714
4715 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004716 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004717 for (auto& options : session_options->media_description_options) {
4718 options.transport_options.opaque_parameters =
4719 transport_controller_->GetTransportParameters(options.mid);
4720 }
4721 }
deadbeefab9b2d12015-10-14 11:33:11 -07004722}
4723
Steve Antondcc3c022017-12-22 16:02:54 -08004724void PeerConnection::GetOptionsForPlanBAnswer(
4725 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004726 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004727 // Figure out transceiver directional preferences.
4728 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4729 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4730
4731 // By default, generate sendrecv/recvonly m= sections. The direction is also
4732 // restricted by the direction in the offer.
4733 bool recv_audio = true;
4734 bool recv_video = true;
4735
4736 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004737 if (offer_answer_options.offer_to_receive_audio !=
4738 RTCOfferAnswerOptions::kUndefined) {
4739 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004740 }
Steve Antondcc3c022017-12-22 16:02:54 -08004741 if (offer_answer_options.offer_to_receive_video !=
4742 RTCOfferAnswerOptions::kUndefined) {
4743 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004744 }
4745
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004746 absl::optional<size_t> audio_index;
4747 absl::optional<size_t> video_index;
4748 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004749
4750 // Generate m= sections that match those in the offer.
4751 // Note that mediasession.cc will handle intersection our preferred
4752 // direction with the offered direction.
4753 GenerateMediaDescriptionOptions(
4754 remote_description(),
4755 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4756 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4757 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004758
4759 cricket::MediaDescriptionOptions* audio_media_description_options =
4760 !audio_index ? nullptr
4761 : &session_options->media_description_options[*audio_index];
4762 cricket::MediaDescriptionOptions* video_media_description_options =
4763 !video_index ? nullptr
4764 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004765
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004766 AddPlanBRtpSenderOptions(GetSendersInternal(),
4767 audio_media_description_options,
4768 video_media_description_options,
4769 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004770}
zhihuangaf388472016-11-02 16:49:48 -07004771
Steve Antondcc3c022017-12-22 16:02:54 -08004772void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4773 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4774 cricket::MediaSessionOptions* session_options) {
4775 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4776 // Answers) and 5.3.2 (Subsequent Answers).
4777 RTC_DCHECK(remote_description());
4778 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4779 for (const ContentInfo& content :
4780 remote_description()->description()->contents()) {
4781 cricket::MediaType media_type = content.media_description()->type();
4782 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4783 media_type == cricket::MEDIA_TYPE_VIDEO) {
4784 auto transceiver = GetAssociatedTransceiver(content.name);
4785 RTC_CHECK(transceiver);
4786 session_options->media_description_options.push_back(
4787 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4788 } else {
4789 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004790 // Reject all data sections if data channels are disabled.
4791 // Reject a data section if it has already been rejected.
4792 // Reject all data sections except for the first one.
4793 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4794 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004795 session_options->media_description_options.push_back(
4796 GetMediaDescriptionOptionsForRejectedData(content.name));
4797 } else {
4798 session_options->media_description_options.push_back(
4799 GetMediaDescriptionOptionsForActiveData(content.name));
4800 }
Steve Antondcc3c022017-12-22 16:02:54 -08004801 }
4802 }
htaa2a49d92016-03-04 02:51:39 -08004803}
4804
zhihuang1c378ed2017-08-17 14:10:50 -07004805void PeerConnection::GenerateMediaDescriptionOptions(
4806 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004807 RtpTransceiverDirection audio_direction,
4808 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004809 absl::optional<size_t>* audio_index,
4810 absl::optional<size_t>* video_index,
4811 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004812 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004813 for (const cricket::ContentInfo& content :
4814 session_desc->description()->contents()) {
4815 if (IsAudioContent(&content)) {
4816 // If we already have an audio m= section, reject this extra one.
4817 if (*audio_index) {
4818 session_options->media_description_options.push_back(
4819 cricket::MediaDescriptionOptions(
4820 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004821 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004822 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004823 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004824 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004825 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4826 content.name, audio_direction,
4827 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004828 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004829 }
4830 } else if (IsVideoContent(&content)) {
4831 // If we already have an video m= section, reject this extra one.
4832 if (*video_index) {
4833 session_options->media_description_options.push_back(
4834 cricket::MediaDescriptionOptions(
4835 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004836 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004837 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004838 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004839 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004840 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4841 content.name, video_direction,
4842 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004843 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004844 }
4845 } else {
4846 RTC_DCHECK(IsDataContent(&content));
4847 // If we already have an data m= section, reject this extra one.
4848 if (*data_index) {
4849 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004850 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004851 } else {
4852 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004853 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004854 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004855 }
4856 }
htaa2a49d92016-03-04 02:51:39 -08004857 }
deadbeefab9b2d12015-10-14 11:33:11 -07004858}
4859
Steve Antonfa2260d2017-12-28 16:38:23 -08004860cricket::MediaDescriptionOptions
4861PeerConnection::GetMediaDescriptionOptionsForActiveData(
4862 const std::string& mid) const {
4863 // Direction for data sections is meaningless, but legacy endpoints might
4864 // expect sendrecv.
4865 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4866 RtpTransceiverDirection::kSendRecv,
4867 /*stopped=*/false);
4868 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4869 return options;
4870}
4871
4872cricket::MediaDescriptionOptions
4873PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4874 const std::string& mid) const {
4875 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4876 RtpTransceiverDirection::kInactive,
4877 /*stopped=*/true);
4878 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4879 return options;
4880}
4881
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004882absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004883 switch (data_channel_type_) {
4884 case cricket::DCT_RTP:
4885 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004886 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004887 }
4888 return rtp_data_channel_->content_name();
4889 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004890 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004891 case cricket::DCT_MEDIA_TRANSPORT:
4892 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004893 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004894 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004895 }
4896}
4897
Steve Anton4171afb2017-11-20 10:20:22 -08004898void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4899 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4900 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004901 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004902}
4903
Steve Anton4171afb2017-11-20 10:20:22 -08004904void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004905 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004906 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004907 cricket::MediaType media_type,
4908 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004909 RTC_DCHECK(!IsUnifiedPlan());
4910
Steve Anton4171afb2017-11-20 10:20:22 -08004911 std::vector<RtpSenderInfo>* current_senders =
4912 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004913
Steve Anton4171afb2017-11-20 10:20:22 -08004914 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004915 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004916 for (auto sender_it = current_senders->begin();
4917 sender_it != current_senders->end();
4918 /* incremented manually */) {
4919 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004920 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004921 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004922 std::string params_stream_id;
4923 if (params) {
4924 params_stream_id =
4925 (!params->first_stream_id().empty() ? params->first_stream_id()
4926 : kDefaultStreamId);
4927 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004928 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004929 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004930 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004931 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004932 sender_exists) {
4933 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004934 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004935 OnRemoteSenderRemoved(info, media_type);
4936 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004937 }
4938 }
4939
Steve Anton4171afb2017-11-20 10:20:22 -08004940 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004941 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004942 if (!params.has_ssrcs()) {
4943 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4944 // sender, this means it is coming from a Unified Plan endpoint,so we just
4945 // create a default.
4946 default_sender_needed = true;
4947 break;
4948 }
4949
Seth Hampson845e8782018-03-02 11:34:10 -08004950 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004951 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004952 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4953 // not supported in Plan B, we just take the first here and create the
4954 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004955 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004956 (!params.first_stream_id().empty() ? params.first_stream_id()
4957 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004958 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004959 uint32_t ssrc = params.first_ssrc();
4960
4961 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004962 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004963 if (!stream) {
4964 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004965 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004966 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004967 remote_streams_->AddStream(stream);
4968 new_streams->AddStream(stream);
4969 }
4970
Steve Anton4171afb2017-11-20 10:20:22 -08004971 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004972 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004973 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004974 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004975 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004976 }
4977 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004978
Steve Anton4171afb2017-11-20 10:20:22 -08004979 // Add default sender if necessary.
4980 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004981 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004982 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004983 if (!default_stream) {
4984 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004985 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004986 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004987 remote_streams_->AddStream(default_stream);
4988 new_streams->AddStream(default_stream);
4989 }
Steve Anton4171afb2017-11-20 10:20:22 -08004990 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4991 ? kDefaultAudioSenderId
4992 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004993 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004994 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004995 if (!default_sender_info) {
4996 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004997 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004998 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004999 }
5000 }
deadbeefab9b2d12015-10-14 11:33:11 -07005001}
5002
Steve Anton4171afb2017-11-20 10:20:22 -08005003void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5004 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005005 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5006 << " receiver for track_id=" << sender_info.sender_id
5007 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005008
Steve Anton3d954a62018-04-02 11:27:23 -07005009 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005010 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005011 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005012 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005013 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005014 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005015 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005016 }
5017}
5018
Steve Anton4171afb2017-11-20 10:20:22 -08005019void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5020 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005021 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5022 << " receiver for track_id=" << sender_info.sender_id
5023 << " and stream_id=" << sender_info.stream_id;
5024
Seth Hampson845e8782018-03-02 11:34:10 -08005025 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005026
Henrik Boström933d8b02017-10-10 10:05:16 -07005027 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005028 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005029 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5030 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005031 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005032 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005033 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005034 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005035 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005036 }
5037 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005038 // Stopping or destroying a VideoRtpReceiver will end the
5039 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005040 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005041 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005042 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005043 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005044 // There's no guarantee the track is still available, e.g. the track may
5045 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005046 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005047 }
5048 } else {
nisseede5da42017-01-12 05:15:36 -08005049 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005050 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005051 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005052 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005053 }
deadbeefab9b2d12015-10-14 11:33:11 -07005054}
5055
5056void PeerConnection::UpdateEndedRemoteMediaStreams() {
5057 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5058 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5059 MediaStreamInterface* stream = remote_streams_->at(i);
5060 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5061 streams_to_remove.push_back(stream);
5062 }
5063 }
5064
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005065 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005066 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005067 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005068 }
5069}
5070
Steve Anton4171afb2017-11-20 10:20:22 -08005071void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005072 const std::vector<cricket::StreamParams>& streams,
5073 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005074 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005075
Seth Hampson845e8782018-03-02 11:34:10 -08005076 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005077 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005078 for (auto sender_it = current_senders->begin();
5079 sender_it != current_senders->end();
5080 /* incremented manually */) {
5081 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005082 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005083 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5084 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005085 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005086 OnLocalSenderRemoved(info, media_type);
5087 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005088 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005089 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005090 }
5091 }
5092
Steve Anton4171afb2017-11-20 10:20:22 -08005093 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005094 for (const cricket::StreamParams& params : streams) {
5095 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005096 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005097 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005098 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005099 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005100 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005101 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005102 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005103 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005104 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005105 }
5106 }
5107}
5108
Steve Anton4171afb2017-11-20 10:20:22 -08005109void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5110 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005111 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005112 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005113 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005114 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5115 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005116 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005117 return;
5118 }
5119
deadbeeffac06552015-11-25 11:26:01 -08005120 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005121 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005122 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005123 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005124 }
deadbeeffac06552015-11-25 11:26:01 -08005125
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005126 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005127 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005128}
5129
Steve Anton4171afb2017-11-20 10:20:22 -08005130void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5131 cricket::MediaType media_type) {
5132 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005133 if (!sender) {
5134 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005135 // SessionDescriptions has been renegotiated.
5136 return;
5137 }
deadbeeffac06552015-11-25 11:26:01 -08005138
5139 // A sender has been removed from the SessionDescription but it's still
5140 // associated with the PeerConnection. This only occurs if the SDP doesn't
5141 // match with the calls to CreateSender, AddStream and RemoveStream.
5142 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005143 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005144 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005145 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005146 }
deadbeeffac06552015-11-25 11:26:01 -08005147
Steve Anton4171afb2017-11-20 10:20:22 -08005148 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005149}
5150
5151void PeerConnection::UpdateLocalRtpDataChannels(
5152 const cricket::StreamParamsVec& streams) {
5153 std::vector<std::string> existing_channels;
5154
5155 // Find new and active data channels.
5156 for (const cricket::StreamParams& params : streams) {
5157 // |it->sync_label| is actually the data channel label. The reason is that
5158 // we use the same naming of data channels as we do for
5159 // MediaStreams and Tracks.
5160 // For MediaStreams, the sync_label is the MediaStream label and the
5161 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005162 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005163 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005164 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005165 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005166 continue;
5167 }
5168 // Set the SSRC the data channel should use for sending.
5169 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5170 existing_channels.push_back(data_channel_it->first);
5171 }
5172
5173 UpdateClosingRtpDataChannels(existing_channels, true);
5174}
5175
5176void PeerConnection::UpdateRemoteRtpDataChannels(
5177 const cricket::StreamParamsVec& streams) {
5178 std::vector<std::string> existing_channels;
5179
5180 // Find new and active data channels.
5181 for (const cricket::StreamParams& params : streams) {
5182 // The data channel label is either the mslabel or the SSRC if the mslabel
5183 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005184 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005185 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005186 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005187 auto data_channel_it = rtp_data_channels_.find(label);
5188 if (data_channel_it == rtp_data_channels_.end()) {
5189 // This is a new data channel.
5190 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5191 } else {
5192 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5193 }
5194 existing_channels.push_back(label);
5195 }
5196
5197 UpdateClosingRtpDataChannels(existing_channels, false);
5198}
5199
5200void PeerConnection::UpdateClosingRtpDataChannels(
5201 const std::vector<std::string>& active_channels,
5202 bool is_local_update) {
5203 auto it = rtp_data_channels_.begin();
5204 while (it != rtp_data_channels_.end()) {
5205 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005206 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005207 ++it;
5208 continue;
5209 }
5210
5211 if (is_local_update) {
5212 data_channel->SetSendSsrc(0);
5213 } else {
5214 data_channel->RemotePeerRequestClose();
5215 }
5216
5217 if (data_channel->state() == DataChannel::kClosed) {
5218 rtp_data_channels_.erase(it);
5219 it = rtp_data_channels_.begin();
5220 } else {
5221 ++it;
5222 }
5223 }
5224}
5225
5226void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5227 uint32_t remote_ssrc) {
5228 rtc::scoped_refptr<DataChannel> channel(
5229 InternalCreateDataChannel(label, nullptr));
5230 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005231 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005232 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005233 return;
5234 }
5235 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005236 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5237 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005238 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005239}
5240
5241rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5242 const std::string& label,
5243 const InternalDataChannelInit* config) {
5244 if (IsClosed()) {
5245 return nullptr;
5246 }
Steve Anton75737c02017-11-06 10:37:17 -08005247 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005248 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005249 << "InternalCreateDataChannel: Data is not supported in this call.";
5250 return nullptr;
5251 }
5252 InternalDataChannelInit new_config =
5253 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005254 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005255 if (new_config.id < 0) {
5256 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005257 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005258 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005259 RTC_LOG(LS_ERROR)
5260 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005261 return nullptr;
5262 }
5263 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005264 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005265 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005266 return nullptr;
5267 }
5268 }
5269
Steve Anton75737c02017-11-06 10:37:17 -08005270 rtc::scoped_refptr<DataChannel> channel(
5271 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005272 if (!channel) {
5273 sid_allocator_.ReleaseSid(new_config.id);
5274 return nullptr;
5275 }
5276
5277 if (channel->data_channel_type() == cricket::DCT_RTP) {
5278 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005279 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5280 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005281 return nullptr;
5282 }
5283 rtp_data_channels_[channel->label()] = channel;
5284 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005285 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005286 sctp_data_channels_.push_back(channel);
5287 channel->SignalClosed.connect(this,
5288 &PeerConnection::OnSctpDataChannelClosed);
5289 }
5290
Steve Anton2d8609c2018-01-23 16:38:46 -08005291 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005292 return channel;
5293}
5294
5295bool PeerConnection::HasDataChannels() const {
5296 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5297}
5298
5299void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005300 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005301 for (const auto& channel : sctp_data_channels_) {
5302 if (channel->id() < 0) {
5303 int sid;
5304 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005305 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5306 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005307 continue;
5308 }
5309 channel->SetSctpSid(sid);
5310 }
5311 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005312 // Since closing modifies the list of channels, we have to do the actual
5313 // closing outside the loop.
5314 for (const auto& channel : channels_to_close) {
5315 channel->CloseAbruptly();
5316 }
deadbeefab9b2d12015-10-14 11:33:11 -07005317}
5318
5319void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005320 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005321 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5322 ++it) {
5323 if (it->get() == channel) {
5324 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005325 // After the closing procedure is done, it's safe to use this ID for
5326 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005327 sid_allocator_.ReleaseSid(channel->id());
5328 }
deadbeefbd292462015-12-14 18:15:29 -08005329 // Since this method is triggered by a signal from the DataChannel,
5330 // we can't free it directly here; we need to free it asynchronously.
5331 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005332 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005333 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5334 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005335 return;
5336 }
5337 }
5338}
5339
deadbeefab9b2d12015-10-14 11:33:11 -07005340void PeerConnection::OnDataChannelDestroyed() {
5341 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5342 // DataChannel may callback to us and try to modify the list.
5343 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5344 temp_rtp_dcs.swap(rtp_data_channels_);
5345 for (const auto& kv : temp_rtp_dcs) {
5346 kv.second->OnTransportChannelDestroyed();
5347 }
5348
5349 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5350 temp_sctp_dcs.swap(sctp_data_channels_);
5351 for (const auto& channel : temp_sctp_dcs) {
5352 channel->OnTransportChannelDestroyed();
5353 }
5354}
5355
5356void PeerConnection::OnDataChannelOpenMessage(
5357 const std::string& label,
5358 const InternalDataChannelInit& config) {
5359 rtc::scoped_refptr<DataChannel> channel(
5360 InternalCreateDataChannel(label, &config));
5361 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005362 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005363 return;
5364 }
5365
deadbeefa601f5c2016-06-06 14:27:39 -07005366 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5367 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005368 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005369 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005370}
5371
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005372bool PeerConnection::HandleOpenMessage_s(
5373 const cricket::ReceiveDataParams& params,
5374 const rtc::CopyOnWriteBuffer& buffer) {
5375 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5376 // Received OPEN message; parse and signal that a new data channel should
5377 // be created.
5378 std::string label;
5379 InternalDataChannelInit config;
5380 config.id = params.ssrc;
5381 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5382 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5383 << params.ssrc;
5384 return true;
5385 }
5386 config.open_handshake_role = InternalDataChannelInit::kAcker;
5387 OnDataChannelOpenMessage(label, config);
5388 return true;
5389 }
5390 return false;
5391}
5392
Steve Anton4171afb2017-11-20 10:20:22 -08005393rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5394PeerConnection::GetAudioTransceiver() const {
5395 // This method only works with Plan B SDP, where there is a single
5396 // audio/video transceiver.
5397 RTC_DCHECK(!IsUnifiedPlan());
5398 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005399 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005400 return transceiver;
5401 }
5402 }
5403 RTC_NOTREACHED();
5404 return nullptr;
5405}
5406
5407rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5408PeerConnection::GetVideoTransceiver() const {
5409 // This method only works with Plan B SDP, where there is a single
5410 // audio/video transceiver.
5411 RTC_DCHECK(!IsUnifiedPlan());
5412 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005413 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005414 return transceiver;
5415 }
5416 }
5417 RTC_NOTREACHED();
5418 return nullptr;
5419}
5420
5421// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5422// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005423bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005424 switch (type) {
5425 case cricket::MEDIA_TYPE_AUDIO:
5426 return !GetAudioTransceiver()->internal()->senders().empty();
5427 case cricket::MEDIA_TYPE_VIDEO:
5428 return !GetVideoTransceiver()->internal()->senders().empty();
5429 case cricket::MEDIA_TYPE_DATA:
5430 return false;
5431 }
5432 RTC_NOTREACHED();
5433 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005434}
5435
Steve Anton4171afb2017-11-20 10:20:22 -08005436rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5437PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005438 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005439 for (auto sender : transceiver->internal()->senders()) {
5440 if (sender->track() == track) {
5441 return sender;
5442 }
5443 }
5444 }
5445 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005446}
5447
Steve Anton4171afb2017-11-20 10:20:22 -08005448rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5449PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005450 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005451 for (auto sender : transceiver->internal()->senders()) {
5452 if (sender->id() == sender_id) {
5453 return sender;
5454 }
5455 }
5456 }
5457 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005458}
5459
Steve Anton4171afb2017-11-20 10:20:22 -08005460rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5461PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005462 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005463 for (auto receiver : transceiver->internal()->receivers()) {
5464 if (receiver->id() == receiver_id) {
5465 return receiver;
5466 }
5467 }
5468 }
5469 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005470}
5471
Steve Anton4171afb2017-11-20 10:20:22 -08005472std::vector<PeerConnection::RtpSenderInfo>*
5473PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5474 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5475 media_type == cricket::MEDIA_TYPE_VIDEO);
5476 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5477 ? &remote_audio_sender_infos_
5478 : &remote_video_sender_infos_;
5479}
5480
5481std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005482 cricket::MediaType media_type) {
5483 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5484 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005485 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5486 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005487}
5488
Steve Anton4171afb2017-11-20 10:20:22 -08005489const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5490 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005491 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005492 const std::string sender_id) const {
5493 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005494 if (sender_info.stream_id == stream_id &&
5495 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005496 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005497 }
5498 }
5499 return nullptr;
5500}
5501
5502DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5503 for (const auto& channel : sctp_data_channels_) {
5504 if (channel->id() == sid) {
5505 return channel;
5506 }
5507 }
5508 return nullptr;
5509}
5510
Karl Wibergfb3be392019-03-22 14:13:22 +01005511PeerConnection::InitializePortAllocatorResult
5512PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005513 const cricket::ServerAddresses& stun_servers,
5514 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005515 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005516 RTC_DCHECK_RUN_ON(network_thread());
5517
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005518 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005519 // To handle both internal and externally created port allocator, we will
5520 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005521 int port_allocator_flags = port_allocator_->flags();
5522 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5523 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5524 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005525 // If the disable-IPv6 flag was specified, we'll not override it
5526 // by experiment.
5527 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005528 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005529 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5530 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005531 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005532 }
5533
zhihuangb09b3f92017-03-07 14:40:51 -08005534 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005535 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005536 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005537 }
5538
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005539 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005540 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005541 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005542 }
5543
honghaiz60347052016-05-31 18:29:12 -07005544 if (configuration.candidate_network_policy ==
5545 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005546 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005547 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005548 }
5549
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005550 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005551 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005552 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5553 }
5554
Karl Wibergfb3be392019-03-22 14:13:22 +01005555 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005556 // No step delay is used while allocating ports.
5557 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005558 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005559 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005560 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005561
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005562 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005563 for (auto& turn_server : turn_servers_copy) {
5564 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005565 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005566 // Call this last since it may create pooled allocator sessions using the
5567 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005568 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005569 stun_servers, std::move(turn_servers_copy),
5570 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5571 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005572 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005573
5574 InitializePortAllocatorResult res;
5575 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5576 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005577}
5578
deadbeef91dd5672016-05-18 16:55:30 -07005579bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005580 const cricket::ServerAddresses& stun_servers,
5581 const std::vector<cricket::RelayServerConfig>& turn_servers,
5582 IceTransportsType type,
5583 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005584 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005585 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005586 absl::optional<int> stun_candidate_keepalive_interval,
5587 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005588 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005589 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005590 // According to JSEP, after setLocalDescription, changing the candidate pool
5591 // size is not allowed, and changing the set of ICE servers will not result
5592 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005593 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005594 port_allocator_->FreezeCandidatePool();
5595 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005596 // Add the custom tls turn servers if they exist.
5597 auto turn_servers_copy = turn_servers;
5598 for (auto& turn_server : turn_servers_copy) {
5599 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5600 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005601 // Call this last since it may create pooled allocator sessions using the
5602 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005603 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005604 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5605 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005606}
5607
Steve Antonba818672017-11-06 10:21:57 -08005608cricket::ChannelManager* PeerConnection::channel_manager() const {
5609 return factory_->channel_manager();
5610}
5611
Elad Alon99c3fe52017-10-13 16:29:40 +02005612bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005613 std::unique_ptr<RtcEventLogOutput> output,
5614 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005615 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005616 if (!event_log_) {
5617 return false;
5618 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005619 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005620}
5621
5622void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005623 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005624 if (event_log_) {
5625 event_log_->StopLogging();
5626 }
ivoc14d5dbe2016-07-04 07:06:55 -07005627}
nisseeaabdf62017-05-05 02:23:02 -07005628
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005629cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005630 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005631 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005632 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005633 if (channel && channel->content_name() == content_name) {
5634 return channel;
5635 }
Steve Anton75737c02017-11-06 10:37:17 -08005636 }
5637 if (rtp_data_channel() &&
5638 rtp_data_channel()->content_name() == content_name) {
5639 return rtp_data_channel();
5640 }
5641 return nullptr;
5642}
5643
5644bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005645 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005646 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005647 RTC_LOG(LS_INFO)
5648 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005649 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005650 return false;
5651 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005652 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005653 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005654 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005655 return false;
5656 }
5657
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005658 absl::optional<rtc::SSLRole> dtls_role;
5659 if (sctp_mid_) {
5660 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5661 } else if (is_caller_) {
5662 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5663 }
Zhi Huange830e682018-03-30 10:48:35 -07005664 if (dtls_role) {
5665 *role = *dtls_role;
5666 return true;
5667 }
5668 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005669}
5670
5671bool PeerConnection::GetSslRole(const std::string& content_name,
5672 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005673 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005674 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005675 RTC_LOG(LS_INFO)
5676 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005677 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005678 return false;
5679 }
5680
Zhi Huange830e682018-03-30 10:48:35 -07005681 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5682 if (dtls_role) {
5683 *role = *dtls_role;
5684 return true;
5685 }
5686 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005687}
5688
Steve Antonf8470812017-12-04 10:46:21 -08005689void PeerConnection::SetSessionError(SessionError error,
5690 const std::string& error_desc) {
5691 RTC_DCHECK_RUN_ON(signaling_thread());
5692 if (error != session_error_) {
5693 session_error_ = error;
5694 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005695 }
5696}
5697
Zhi Huange830e682018-03-30 10:48:35 -07005698RTCError PeerConnection::UpdateSessionState(
5699 SdpType type,
5700 cricket::ContentSource source,
5701 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005702 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005703
5704 // If there's already a pending error then no state transition should happen.
5705 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005706 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005707
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005708 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005709 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005710 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005711 }
5712
5713 // Update the signaling state according to the specified state machine (see
5714 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005715 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005716 ChangeSignalingState(source == cricket::CS_LOCAL
5717 ? PeerConnectionInterface::kHaveLocalOffer
5718 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005719 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005720 ChangeSignalingState(source == cricket::CS_LOCAL
5721 ? PeerConnectionInterface::kHaveLocalPrAnswer
5722 : PeerConnectionInterface::kHaveRemotePrAnswer);
5723 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005724 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005725 ChangeSignalingState(PeerConnectionInterface::kStable);
5726 }
5727
5728 // Update internal objects according to the session description's media
5729 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005730 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005731 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005732 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005733 }
5734
Steve Anton8a006912017-12-04 15:25:56 -08005735 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005736}
5737
Steve Anton8a006912017-12-04 15:25:56 -08005738RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005739 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005740 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005741 const SessionDescriptionInterface* sdesc =
5742 (source == cricket::CS_LOCAL ? local_description()
5743 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005744 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005745
5746 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005747 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005748 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005749 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005750 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005751 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005752 continue;
5753 }
5754 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005755 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005756 if (!content_desc) {
5757 continue;
5758 }
5759 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005760 bool success = (source == cricket::CS_LOCAL)
5761 ? channel->SetLocalContent(content_desc, type, &error)
5762 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005763 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005764 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005765 }
5766 }
5767
5768 // If using the RtpDataChannel, push down the new SDP section for it too.
5769 if (rtp_data_channel_) {
5770 const ContentInfo* data_content =
5771 cricket::GetFirstDataContent(sdesc->description());
5772 if (data_content && !data_content->rejected) {
5773 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005774 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005775 if (data_desc) {
5776 std::string error;
5777 bool success =
5778 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005779 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005780 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005781 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005782 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005783 }
Steve Anton75737c02017-11-06 10:37:17 -08005784 }
5785 }
5786 }
Steve Antoned10bd92017-12-05 10:52:59 -08005787
Steve Anton75737c02017-11-06 10:37:17 -08005788 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5789 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005790 if (sctp_transport_ && local_description() && remote_description()) {
5791 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5792 local_description()->description());
5793 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5794 remote_description()->description());
5795 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005796 int max_message_size;
5797 // A remote max message size of zero means "any size supported".
5798 // We configure the connection with our own max message size.
5799 if (remote_sctp_description->max_message_size() == 0) {
5800 max_message_size = local_sctp_description->max_message_size();
5801 } else {
5802 max_message_size =
5803 std::min(local_sctp_description->max_message_size(),
5804 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005805 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005806 sctp_transport_->Start(local_sctp_description->port(),
5807 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005808 }
Steve Anton75737c02017-11-06 10:37:17 -08005809 }
Steve Antoned10bd92017-12-05 10:52:59 -08005810
Steve Anton8a006912017-12-04 15:25:56 -08005811 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005812}
5813
Steve Anton8a006912017-12-04 15:25:56 -08005814RTCError PeerConnection::PushdownTransportDescription(
5815 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005816 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005817 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005818
Zhi Huange830e682018-03-30 10:48:35 -07005819 if (source == cricket::CS_LOCAL) {
5820 const SessionDescriptionInterface* sdesc = local_description();
5821 RTC_DCHECK(sdesc);
5822 return transport_controller_->SetLocalDescription(type,
5823 sdesc->description());
5824 } else {
5825 const SessionDescriptionInterface* sdesc = remote_description();
5826 RTC_DCHECK(sdesc);
5827 return transport_controller_->SetRemoteDescription(type,
5828 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005829 }
Steve Anton75737c02017-11-06 10:37:17 -08005830}
5831
5832bool PeerConnection::GetTransportDescription(
5833 const SessionDescription* description,
5834 const std::string& content_name,
5835 cricket::TransportDescription* tdesc) {
5836 if (!description || !tdesc) {
5837 return false;
5838 }
5839 const TransportInfo* transport_info =
5840 description->GetTransportInfoByName(content_name);
5841 if (!transport_info) {
5842 return false;
5843 }
5844 *tdesc = transport_info->description;
5845 return true;
5846}
5847
Steve Anton75737c02017-11-06 10:37:17 -08005848cricket::IceConfig PeerConnection::ParseIceConfig(
5849 const PeerConnectionInterface::RTCConfiguration& config) const {
5850 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005851 switch (config.continual_gathering_policy) {
5852 case PeerConnectionInterface::GATHER_ONCE:
5853 gathering_policy = cricket::GATHER_ONCE;
5854 break;
5855 case PeerConnectionInterface::GATHER_CONTINUALLY:
5856 gathering_policy = cricket::GATHER_CONTINUALLY;
5857 break;
5858 default:
5859 RTC_NOTREACHED();
5860 gathering_policy = cricket::GATHER_ONCE;
5861 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005862
Steve Anton75737c02017-11-06 10:37:17 -08005863 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005864 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5865 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005866 ice_config.prioritize_most_likely_candidate_pairs =
5867 config.prioritize_most_likely_ice_candidate_pairs;
5868 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005869 RTCConfigurationToIceConfigOptionalInt(
5870 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005871 ice_config.continual_gathering_policy = gathering_policy;
5872 ice_config.presume_writable_when_fully_relayed =
5873 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005874 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5875 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005876 ice_config.ice_check_interval_strong_connectivity =
5877 config.ice_check_interval_strong_connectivity;
5878 ice_config.ice_check_interval_weak_connectivity =
5879 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005880 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005881 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5882 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005883 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005884 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005885 ice_config.regather_all_networks_interval_range =
5886 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005887 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005888 return ice_config;
5889}
5890
Steve Anton75737c02017-11-06 10:37:17 -08005891bool PeerConnection::SendData(const cricket::SendDataParams& params,
5892 const rtc::CopyOnWriteBuffer& payload,
5893 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005894 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005895 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5896 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5897 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005898 return false;
5899 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005900 if (media_transport_) {
5901 SendDataParams send_params;
5902 send_params.type = ToWebrtcDataMessageType(params.type);
5903 send_params.ordered = params.ordered;
5904 if (params.max_rtx_count >= 0) {
5905 send_params.max_rtx_count = params.max_rtx_count;
5906 } else if (params.max_rtx_ms >= 0) {
5907 send_params.max_rtx_ms = params.max_rtx_ms;
5908 }
5909 return media_transport_->SendData(params.sid, send_params, payload).ok();
5910 }
Steve Anton75737c02017-11-06 10:37:17 -08005911 return rtp_data_channel_
5912 ? rtp_data_channel_->SendData(params, payload, result)
5913 : network_thread()->Invoke<bool>(
5914 RTC_FROM_HERE,
5915 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005916 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005917}
5918
5919bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005920 RTC_DCHECK_RUN_ON(signaling_thread());
5921 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005922 // Don't log an error here, because DataChannels are expected to call
5923 // ConnectDataChannel in this state. It's the only way to initially tell
5924 // whether or not the underlying transport is ready.
5925 return false;
5926 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005927 if (media_transport_) {
5928 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5929 &DataChannel::OnChannelReady);
5930 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5931 &DataChannel::OnDataReceived);
5932 SignalMediaTransportChannelClosing_s.connect(
5933 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5934 SignalMediaTransportChannelClosed_s.connect(
5935 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5936 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005937 rtp_data_channel_->SignalReadyToSendData.connect(
5938 webrtc_data_channel, &DataChannel::OnChannelReady);
5939 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5940 &DataChannel::OnDataReceived);
5941 } else {
5942 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5943 &DataChannel::OnChannelReady);
5944 SignalSctpDataReceived.connect(webrtc_data_channel,
5945 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005946 SignalSctpClosingProcedureStartedRemotely.connect(
5947 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5948 SignalSctpClosingProcedureComplete.connect(
5949 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005950 }
5951 return true;
5952}
5953
5954void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005955 RTC_DCHECK_RUN_ON(signaling_thread());
5956 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005957 RTC_LOG(LS_ERROR)
5958 << "DisconnectDataChannel called when rtp_data_channel_ and "
5959 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005960 return;
5961 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005962 if (media_transport_) {
5963 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5964 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5965 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5966 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5967 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005968 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5969 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5970 } else {
5971 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5972 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005973 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5974 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005975 }
5976}
5977
5978void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005979 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005980 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005981 return;
5982 }
Steve Anton75737c02017-11-06 10:37:17 -08005983 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005984 RTC_LOG(LS_ERROR)
5985 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005986 return;
5987 }
5988 network_thread()->Invoke<void>(
5989 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005990 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005991}
5992
5993void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005994 if (media_transport_) {
5995 media_transport_->CloseChannel(sid);
5996 return;
5997 }
Steve Anton75737c02017-11-06 10:37:17 -08005998 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005999 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006000 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08006001 return;
6002 }
6003 network_thread()->Invoke<void>(
6004 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006005 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006006}
6007
6008bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006009 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006010 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006011 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08006012 sctp_ready_to_send_data_;
6013}
6014
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006015void PeerConnection::OnDataReceived(int channel_id,
6016 DataMessageType type,
6017 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006018 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006019 cricket::ReceiveDataParams params;
6020 params.sid = channel_id;
6021 params.type = ToCricketDataMessageType(type);
6022 media_transport_invoker_->AsyncInvoke<void>(
6023 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6024 RTC_DCHECK_RUN_ON(signaling_thread());
6025 if (!HandleOpenMessage_s(params, buffer)) {
6026 SignalMediaTransportReceivedData_s(params, buffer);
6027 }
6028 });
6029}
6030
6031void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006032 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006033 media_transport_invoker_->AsyncInvoke<void>(
6034 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6035 RTC_DCHECK_RUN_ON(signaling_thread());
6036 SignalMediaTransportChannelClosing_s(channel_id);
6037 });
6038}
6039
6040void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006041 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006042 media_transport_invoker_->AsyncInvoke<void>(
6043 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6044 RTC_DCHECK_RUN_ON(signaling_thread());
6045 SignalMediaTransportChannelClosed_s(channel_id);
6046 });
6047}
6048
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006049absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006050 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006051 if (sctp_mid_ && transport_controller_) {
6052 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6053 if (dtls_transport) {
6054 return dtls_transport->transport_name();
6055 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006056 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006057 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006058 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006059}
6060
Qingsi Wang72a43a12018-02-20 16:03:18 -08006061cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6062 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006063 network_thread()->Invoke<void>(
6064 RTC_FROM_HERE,
6065 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6066 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006067 return candidate_states_list;
6068}
6069
Steve Anton5dfde182018-02-06 10:34:40 -08006070std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6071 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006072 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006073 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006074 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006075 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006076 if (channel) {
6077 transport_names_by_mid[channel->content_name()] =
6078 channel->transport_name();
6079 }
Steve Anton75737c02017-11-06 10:37:17 -08006080 }
Steve Anton5dfde182018-02-06 10:34:40 -08006081 if (rtp_data_channel_) {
6082 transport_names_by_mid[rtp_data_channel_->content_name()] =
6083 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006084 }
6085 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006086 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006087 RTC_DCHECK(transport_name);
6088 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006089 }
Steve Anton5dfde182018-02-06 10:34:40 -08006090 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006091}
6092
Steve Anton5dfde182018-02-06 10:34:40 -08006093std::map<std::string, cricket::TransportStats>
6094PeerConnection::GetTransportStatsByNames(
6095 const std::set<std::string>& transport_names) {
6096 if (!network_thread()->IsCurrent()) {
6097 return network_thread()
6098 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6099 RTC_FROM_HERE,
6100 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006101 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006102 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006103 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6104 for (const std::string& transport_name : transport_names) {
6105 cricket::TransportStats transport_stats;
6106 bool success =
6107 transport_controller_->GetStats(transport_name, &transport_stats);
6108 if (success) {
6109 transport_stats_by_name[transport_name] = std::move(transport_stats);
6110 } else {
6111 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6112 << transport_name;
6113 }
6114 }
6115 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006116}
6117
6118bool PeerConnection::GetLocalCertificate(
6119 const std::string& transport_name,
6120 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006121 if (!certificate) {
6122 return false;
6123 }
6124 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6125 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006126}
6127
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006128std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006129 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006130 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006131}
6132
6133cricket::DataChannelType PeerConnection::data_channel_type() const {
6134 return data_channel_type_;
6135}
6136
6137bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006138 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006139 return pending_ice_restarts_.find(content_name) !=
6140 pending_ice_restarts_.end();
6141}
6142
Steve Anton75737c02017-11-06 10:37:17 -08006143bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6144 return transport_controller_->NeedsIceRestart(content_name);
6145}
6146
6147void PeerConnection::OnCertificateReady(
6148 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6149 transport_controller_->SetLocalCertificate(certificate);
6150}
6151
6152void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006153 SetSessionError(SessionError::kTransport,
6154 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006155}
6156
Alex Loiko9289eda2018-11-23 16:18:59 +00006157void PeerConnection::OnTransportControllerConnectionState(
6158 cricket::IceConnectionState state) {
6159 switch (state) {
6160 case cricket::kIceConnectionConnecting:
6161 // If the current state is Connected or Completed, then there were
6162 // writable channels but now there are not, so the next state must
6163 // be Disconnected.
6164 // kIceConnectionConnecting is currently used as the default,
6165 // un-connected state by the TransportController, so its only use is
6166 // detecting disconnections.
6167 if (ice_connection_state_ ==
6168 PeerConnectionInterface::kIceConnectionConnected ||
6169 ice_connection_state_ ==
6170 PeerConnectionInterface::kIceConnectionCompleted) {
6171 SetIceConnectionState(
6172 PeerConnectionInterface::kIceConnectionDisconnected);
6173 }
6174 break;
6175 case cricket::kIceConnectionFailed:
6176 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6177 break;
6178 case cricket::kIceConnectionConnected:
6179 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6180 "all transports are writable.";
6181 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6182 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6183 break;
6184 case cricket::kIceConnectionCompleted:
6185 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6186 "all transports are complete.";
6187 if (ice_connection_state_ !=
6188 PeerConnectionInterface::kIceConnectionConnected) {
6189 // If jumping directly from "checking" to "connected",
6190 // signal "connected" first.
6191 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6192 }
6193 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6194 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6195 ReportTransportStats();
6196 break;
6197 default:
6198 RTC_NOTREACHED();
6199 }
6200}
6201
Steve Anton75737c02017-11-06 10:37:17 -08006202void PeerConnection::OnTransportControllerCandidatesGathered(
6203 const std::string& transport_name,
6204 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006205 int sdp_mline_index;
6206 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006207 RTC_LOG(LS_ERROR)
6208 << "OnTransportControllerCandidatesGathered: content name "
6209 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006210 return;
6211 }
6212
6213 for (cricket::Candidates::const_iterator citer = candidates.begin();
6214 citer != candidates.end(); ++citer) {
6215 // Use transport_name as the candidate media id.
6216 std::unique_ptr<JsepIceCandidate> candidate(
6217 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6218 if (local_description()) {
6219 mutable_local_description()->AddCandidate(candidate.get());
6220 }
6221 OnIceCandidate(std::move(candidate));
6222 }
6223}
6224
Eldar Relloda13ea22019-06-01 12:23:43 +03006225void PeerConnection::OnTransportControllerCandidateError(
6226 const cricket::IceCandidateErrorEvent& event) {
6227 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6228 event.error_text);
6229}
6230
Steve Anton75737c02017-11-06 10:37:17 -08006231void PeerConnection::OnTransportControllerCandidatesRemoved(
6232 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006233 // Sanity check.
6234 for (const cricket::Candidate& candidate : candidates) {
6235 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006236 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006237 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006238 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006239 return;
6240 }
6241 }
6242
6243 if (local_description()) {
6244 mutable_local_description()->RemoveCandidates(candidates);
6245 }
6246 OnIceCandidatesRemoved(candidates);
6247}
6248
6249void PeerConnection::OnTransportControllerDtlsHandshakeError(
6250 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006251 RTC_HISTOGRAM_ENUMERATION(
6252 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6253 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006254}
6255
Steve Antoned10bd92017-12-05 10:52:59 -08006256void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006257 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006258 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006259 if (channel && !channel->enabled()) {
6260 channel->Enable(true);
6261 }
Steve Anton75737c02017-11-06 10:37:17 -08006262 }
6263
Steve Anton4171afb2017-11-20 10:20:22 -08006264 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006265 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006266 }
Steve Anton75737c02017-11-06 10:37:17 -08006267}
6268
6269// Returns the media index for a local ice candidate given the content name.
6270bool PeerConnection::GetLocalCandidateMediaIndex(
6271 const std::string& content_name,
6272 int* sdp_mline_index) {
6273 if (!local_description() || !sdp_mline_index) {
6274 return false;
6275 }
6276
6277 bool content_found = false;
6278 const ContentInfos& contents = local_description()->description()->contents();
6279 for (size_t index = 0; index < contents.size(); ++index) {
6280 if (contents[index].name == content_name) {
6281 *sdp_mline_index = static_cast<int>(index);
6282 content_found = true;
6283 break;
6284 }
6285 }
6286 return content_found;
6287}
6288
6289bool PeerConnection::UseCandidatesInSessionDescription(
6290 const SessionDescriptionInterface* remote_desc) {
6291 if (!remote_desc) {
6292 return true;
6293 }
6294 bool ret = true;
6295
6296 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6297 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6298 for (size_t n = 0; n < candidates->count(); ++n) {
6299 const IceCandidateInterface* candidate = candidates->at(n);
6300 bool valid = false;
6301 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6302 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006303 RTC_LOG(LS_INFO)
6304 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006305 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006306 }
6307 continue;
6308 }
6309 ret = UseCandidate(candidate);
6310 if (!ret) {
6311 break;
6312 }
6313 }
6314 }
6315 return ret;
6316}
6317
6318bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006319 RTCErrorOr<const cricket::ContentInfo*> result =
6320 FindContentInfo(remote_description(), candidate);
6321 if (!result.ok()) {
6322 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6323 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006324 return false;
6325 }
Steve Anton75737c02017-11-06 10:37:17 -08006326 std::vector<cricket::Candidate> candidates;
6327 candidates.push_back(candidate->candidate());
6328 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006329 RTCError error = transport_controller_->AddRemoteCandidates(
6330 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006331 if (error.ok()) {
6332 // Candidates successfully submitted for checking.
6333 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6334 ice_connection_state_ ==
6335 PeerConnectionInterface::kIceConnectionDisconnected) {
6336 // If state is New, then the session has just gotten its first remote ICE
6337 // candidates, so go to Checking.
6338 // If state is Disconnected, the session is re-using old candidates or
6339 // receiving additional ones, so go to Checking.
6340 // If state is Connected, stay Connected.
6341 // TODO(bemasc): If state is Connected, and the new candidates are for a
6342 // newly added transport, then the state actually _should_ move to
6343 // checking. Add a way to distinguish that case.
6344 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6345 }
6346 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006347 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006348 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006349 }
6350 return true;
6351}
6352
Guido Urdaneta41633172019-05-23 20:12:29 +02006353RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6354 const SessionDescriptionInterface* description,
6355 const IceCandidateInterface* candidate) {
6356 if (candidate->sdp_mline_index() >= 0) {
6357 size_t mediacontent_index =
6358 static_cast<size_t>(candidate->sdp_mline_index());
6359 size_t content_size = description->description()->contents().size();
6360 if (mediacontent_index < content_size) {
6361 return &description->description()->contents()[mediacontent_index];
6362 } else {
6363 return RTCError(RTCErrorType::INVALID_RANGE,
6364 "Media line index (" +
6365 rtc::ToString(candidate->sdp_mline_index()) +
6366 ") out of range (number of mlines: " +
6367 rtc::ToString(content_size) + ").");
6368 }
6369 } else if (!candidate->sdp_mid().empty()) {
6370 auto& contents = description->description()->contents();
6371 auto it = absl::c_find_if(
6372 contents, [candidate](const cricket::ContentInfo& content_info) {
6373 return content_info.mid() == candidate->sdp_mid();
6374 });
6375 if (it == contents.end()) {
6376 return RTCError(
6377 RTCErrorType::INVALID_PARAMETER,
6378 "Mid " + candidate->sdp_mid() +
6379 " specified but no media section with that mid found.");
6380 } else {
6381 return &*it;
6382 }
6383 }
6384
6385 return RTCError(RTCErrorType::INVALID_PARAMETER,
6386 "Neither sdp_mline_index nor sdp_mid specified.");
6387}
6388
Steve Anton75737c02017-11-06 10:37:17 -08006389void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006390 // Destroy video channel first since it may have a pointer to the
6391 // voice channel.
6392 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006393 if (!video_info || video_info->rejected) {
6394 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006395 }
6396
Steve Anton6fec8802017-12-04 10:37:29 -08006397 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6398 if (!audio_info || audio_info->rejected) {
6399 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006400 }
6401
6402 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6403 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006404 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006405 }
6406}
6407
Steve Antondcc3c022017-12-22 16:02:54 -08006408RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6409 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006410 const cricket::ContentGroup* bundle_group = nullptr;
6411 if (configuration_.bundle_policy ==
6412 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006413 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006414 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6416 "max-bundle configured but session description "
6417 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006418 }
6419 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006420 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006421}
6422
6423RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006424 // Creating the media channels. Transports should already have been created
6425 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006426 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006427 if (voice && !voice->rejected &&
6428 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006429 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006430 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006431 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6432 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006433 }
6434 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6435 }
6436
Steve Antondcc3c022017-12-22 16:02:54 -08006437 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006438 if (video && !video->rejected &&
6439 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006440 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006441 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006442 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6443 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006444 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006445 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006446 }
6447
Steve Antondcc3c022017-12-22 16:02:54 -08006448 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006449 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006450 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006451 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006452 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6453 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006454 }
6455 }
6456
Steve Anton8a006912017-12-04 15:25:56 -08006457 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006458}
6459
Steve Anton4171afb2017-11-20 10:20:22 -08006460// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006461cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006462 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006463 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006464 MediaTransportConfig media_transport_config =
6465 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006466
Steve Anton75737c02017-11-06 10:37:17 -08006467 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006468 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006469 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6470 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006471 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006472 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006473 }
Steve Anton75737c02017-11-06 10:37:17 -08006474 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6475 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006476 voice_channel->SignalSentPacket.connect(this,
6477 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006478 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006479
Steve Antoneda6ccd2017-12-04 10:21:55 -08006480 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006481}
6482
Steve Anton4171afb2017-11-20 10:20:22 -08006483// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006484cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006485 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006486 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006487 MediaTransportConfig media_transport_config =
6488 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006489
Steve Anton75737c02017-11-06 10:37:17 -08006490 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006491 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006492 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6493 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006494 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006495 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006496 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006497 }
Steve Anton75737c02017-11-06 10:37:17 -08006498 video_channel->SignalDtlsSrtpSetupFailure.connect(
6499 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006500 video_channel->SignalSentPacket.connect(this,
6501 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006502 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006503
Steve Antoneda6ccd2017-12-04 10:21:55 -08006504 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006505}
6506
Zhi Huange830e682018-03-30 10:48:35 -07006507bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006508 switch (data_channel_type_) {
6509 case cricket::DCT_MEDIA_TRANSPORT:
6510 if (network_thread()->Invoke<bool>(
6511 RTC_FROM_HERE,
6512 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6513 this, mid))) {
6514 for (const auto& channel : sctp_data_channels_) {
6515 channel->OnTransportChannelCreated();
6516 }
6517 return true;
6518 }
Steve Anton75737c02017-11-06 10:37:17 -08006519 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006520 case cricket::DCT_SCTP:
6521 if (!sctp_factory_) {
6522 RTC_LOG(LS_ERROR)
6523 << "Trying to create SCTP transport, but didn't compile with "
6524 "SCTP support (HAVE_SCTP)";
6525 return false;
6526 }
6527 if (!network_thread()->Invoke<bool>(
6528 RTC_FROM_HERE,
6529 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6530 return false;
6531 }
6532 for (const auto& channel : sctp_data_channels_) {
6533 channel->OnTransportChannelCreated();
6534 }
6535 return true;
6536 case cricket::DCT_RTP:
6537 default:
6538 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6539 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6540 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006541 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006542 if (!rtp_data_channel_) {
6543 return false;
6544 }
6545 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6546 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6547 rtp_data_channel_->SignalSentPacket.connect(
6548 this, &PeerConnection::OnSentPacket_w);
6549 rtp_data_channel_->SetRtpTransport(rtp_transport);
6550 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006551 }
6552
Steve Anton75737c02017-11-06 10:37:17 -08006553 return true;
6554}
6555
6556Call::Stats PeerConnection::GetCallStats() {
6557 if (!worker_thread()->IsCurrent()) {
6558 return worker_thread()->Invoke<Call::Stats>(
6559 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6560 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006561 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006562 if (call_) {
6563 return call_->GetStats();
6564 } else {
6565 return Call::Stats();
6566 }
6567}
6568
Zhi Huange830e682018-03-30 10:48:35 -07006569bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006570 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006571 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006572 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6573 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006574 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006575 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006576 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006577 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6578 sctp_factory_->CreateSctpTransport(dtls_transport);
6579 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006580 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006581 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006582 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006583 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006584 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006585 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6586 // another thread. Would be nice if there was a helper class similar to
6587 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6588 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006589 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006590 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006591 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006592 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006593 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006594 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6595 std::move(cricket_sctp_transport));
6596 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006597 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006598}
6599
6600void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006601 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006602 sctp_transport_->Clear();
6603 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006604 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006605 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006606}
6607
6608void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006609 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006610 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006611 // Note: Cannot use rtc::Bind here because it will grab a reference to
6612 // PeerConnection and potentially cause PeerConnection to live longer than
6613 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6614 // be destroyed before PeerConnection is destroyed, and at that point all
6615 // pending tasks will be cleared.
6616 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6617 OnSctpTransportReadyToSendData_s(true);
6618 });
6619}
6620
6621void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006622 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006623 sctp_ready_to_send_data_ = ready;
6624 SignalSctpReadyToSendData(ready);
6625}
6626
6627void PeerConnection::OnSctpTransportDataReceived_n(
6628 const cricket::ReceiveDataParams& params,
6629 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006630 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006631 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006632 // Note: Cannot use rtc::Bind here because it will grab a reference to
6633 // PeerConnection and potentially cause PeerConnection to live longer than
6634 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6635 // be destroyed before PeerConnection is destroyed, and at that point all
6636 // pending tasks will be cleared.
6637 sctp_invoker_->AsyncInvoke<void>(
6638 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6639 OnSctpTransportDataReceived_s(params, payload);
6640 });
6641}
6642
6643void PeerConnection::OnSctpTransportDataReceived_s(
6644 const cricket::ReceiveDataParams& params,
6645 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006646 RTC_DCHECK_RUN_ON(signaling_thread());
6647 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006648 SignalSctpDataReceived(params, payload);
6649 }
6650}
6651
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006652void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006653 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006654 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006655 sctp_invoker_->AsyncInvoke<void>(
6656 RTC_FROM_HERE, signaling_thread(),
6657 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006658 &SignalSctpClosingProcedureStartedRemotely, sid));
6659}
6660
6661void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006662 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006663 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006664 sctp_invoker_->AsyncInvoke<void>(
6665 RTC_FROM_HERE, signaling_thread(),
6666 rtc::Bind(&sigslot::signal1<int>::operator(),
6667 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006668}
6669
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006670bool PeerConnection::SetupMediaTransportForDataChannels_n(
6671 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006672 media_transport_ =
6673 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006674 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006675 RTC_LOG(LS_ERROR)
6676 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006677 return false;
6678 }
6679
6680 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6681 media_transport_->SetDataSink(this);
6682 media_transport_data_mid_ = mid;
6683 transport_controller_->SignalMediaTransportStateChanged.connect(
6684 this, &PeerConnection::OnMediaTransportStateChanged_n);
6685 // Check the initial state right away, in case transport is already writable.
6686 OnMediaTransportStateChanged_n();
6687 return true;
6688}
6689
6690void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6691 if (!media_transport_) {
6692 return;
6693 }
6694 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6695 media_transport_data_mid_.reset();
6696 media_transport_->SetDataSink(nullptr);
6697 media_transport_invoker_ = nullptr;
6698 media_transport_ = nullptr;
6699}
6700
6701void PeerConnection::OnMediaTransportStateChanged_n() {
6702 if (!media_transport_data_mid_ ||
6703 transport_controller_->GetMediaTransportState(
6704 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6705 return;
6706 }
6707 media_transport_invoker_->AsyncInvoke<void>(
6708 RTC_FROM_HERE, signaling_thread(), [this] {
6709 RTC_DCHECK_RUN_ON(signaling_thread());
6710 media_transport_ready_to_send_data_ = true;
6711 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6712 });
6713}
6714
Steve Anton75737c02017-11-06 10:37:17 -08006715// Returns false if bundle is enabled and rtcp_mux is disabled.
6716bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6717 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6718 if (!bundle_enabled)
6719 return true;
6720
6721 const cricket::ContentGroup* bundle_group =
6722 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6723 RTC_DCHECK(bundle_group != NULL);
6724
6725 const cricket::ContentInfos& contents = desc->contents();
6726 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6727 citer != contents.end(); ++citer) {
6728 const cricket::ContentInfo* content = (&*citer);
6729 RTC_DCHECK(content != NULL);
6730 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006731 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006732 if (!HasRtcpMuxEnabled(content))
6733 return false;
6734 }
6735 }
6736 // RTCP-MUX is enabled in all the contents.
6737 return true;
6738}
6739
6740bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006741 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006742}
6743
Steve Anton06817cd2018-12-18 15:55:30 -08006744static RTCError ValidateMids(const cricket::SessionDescription& description) {
6745 std::set<std::string> mids;
6746 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006747 if (content.name.empty()) {
6748 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6749 "A media section is missing a MID attribute.");
6750 }
Steve Anton06817cd2018-12-18 15:55:30 -08006751 if (!mids.insert(content.name).second) {
6752 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6753 "Duplicate a=mid value '" + content.name + "'.");
6754 }
6755 }
6756 return RTCError::OK();
6757}
6758
Steve Anton8a006912017-12-04 15:25:56 -08006759RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006760 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006761 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006762 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006763 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006764 }
6765
6766 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006767 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006768 }
6769
Steve Anton3828c062017-12-06 10:34:51 -08006770 SdpType type = sdesc->GetType();
6771 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6772 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006773 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006774 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006775 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006776 }
6777
Steve Anton06817cd2018-12-18 15:55:30 -08006778 RTCError error = ValidateMids(*sdesc->description());
6779 if (!error.ok()) {
6780 return error;
6781 }
6782
Steve Anton75737c02017-11-06 10:37:17 -08006783 // Verify crypto settings.
6784 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006785 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6786 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006787 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006788 if (!crypto_error.ok()) {
6789 return crypto_error;
6790 }
Steve Anton75737c02017-11-06 10:37:17 -08006791 }
6792
6793 // Verify ice-ufrag and ice-pwd.
6794 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006795 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6796 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006797 }
6798
6799 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006800 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6801 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006802 }
6803
6804 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6805 // m-lines that do not rtcp-mux enabled.
6806
6807 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006808 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006809 // With an answer we want to compare the new answer session description with
6810 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006811 const cricket::SessionDescription* offer_desc =
6812 (source == cricket::CS_LOCAL) ? remote_description()->description()
6813 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006814 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6815 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6816 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006817 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6818 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006819 }
6820 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006821 // The re-offers should respect the order of m= sections in current
6822 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006823 // With a re-offer, either the current local or current remote descriptions
6824 // could be the most up to date, so we would like to check against both of
6825 // them if they exist. It could be the case that one of them has a 0 port
6826 // for a media section, but the other does not. This is important to check
6827 // against in the case that we are recycling an m= section.
6828 const cricket::SessionDescription* current_desc = nullptr;
6829 const cricket::SessionDescription* secondary_current_desc = nullptr;
6830 if (local_description()) {
6831 current_desc = local_description()->description();
6832 if (remote_description()) {
6833 secondary_current_desc = remote_description()->description();
6834 }
6835 } else if (remote_description()) {
6836 current_desc = remote_description()->description();
6837 }
Steve Anton75737c02017-11-06 10:37:17 -08006838 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006839 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6840 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006841 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6842 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006843 }
6844 }
6845
Steve Antonba42e992018-04-09 14:10:01 -07006846 if (IsUnifiedPlan()) {
6847 // Ensure that each audio and video media section has at most one
6848 // "StreamParams". This will return an error if receiving a session
6849 // description from a "Plan B" endpoint which adds multiple tracks of the
6850 // same type. With Unified Plan, there can only be at most one track per
6851 // media section.
6852 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006853 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006854 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6855 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6856 desc.streams().size() > 1u) {
6857 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6858 "Media section has more than one track specified "
6859 "with a=ssrc lines which is not supported with "
6860 "Unified Plan.");
6861 }
6862 }
6863 }
6864
Steve Anton8a006912017-12-04 15:25:56 -08006865 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006866}
6867
Steve Anton3828c062017-12-06 10:34:51 -08006868bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006869 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006870 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006871 return (state == PeerConnectionInterface::kStable) ||
6872 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006873 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006874 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006875 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6876 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6877 }
6878}
6879
Steve Anton3828c062017-12-06 10:34:51 -08006880bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006881 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006882 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006883 return (state == PeerConnectionInterface::kStable) ||
6884 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006885 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006886 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006887 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6888 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6889 }
6890}
6891
Steve Antonf8470812017-12-04 10:46:21 -08006892const char* PeerConnection::SessionErrorToString(SessionError error) const {
6893 switch (error) {
6894 case SessionError::kNone:
6895 return "ERROR_NONE";
6896 case SessionError::kContent:
6897 return "ERROR_CONTENT";
6898 case SessionError::kTransport:
6899 return "ERROR_TRANSPORT";
6900 }
6901 RTC_NOTREACHED();
6902 return "";
6903}
6904
Steve Anton75737c02017-11-06 10:37:17 -08006905std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006906 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006907 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6908 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006909 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006910}
6911
Steve Anton8e20f172018-03-06 10:55:04 -08006912void PeerConnection::ReportSdpFormatReceived(
6913 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006914 int num_audio_mlines = 0;
6915 int num_video_mlines = 0;
6916 int num_audio_tracks = 0;
6917 int num_video_tracks = 0;
6918 for (const ContentInfo& content : remote_offer.description()->contents()) {
6919 cricket::MediaType media_type = content.media_description()->type();
6920 int num_tracks = std::max(
6921 1, static_cast<int>(content.media_description()->streams().size()));
6922 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6923 num_audio_mlines += 1;
6924 num_audio_tracks += num_tracks;
6925 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6926 num_video_mlines += 1;
6927 num_video_tracks += num_tracks;
6928 }
6929 }
6930 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6931 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6932 format = kSdpFormatReceivedComplexUnifiedPlan;
6933 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6934 format = kSdpFormatReceivedComplexPlanB;
6935 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6936 format = kSdpFormatReceivedSimple;
6937 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006938 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6939 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006940}
6941
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006942void PeerConnection::NoteUsageEvent(UsageEvent event) {
6943 RTC_DCHECK_RUN_ON(signaling_thread());
6944 usage_event_accumulator_ |= static_cast<int>(event);
6945}
6946
6947void PeerConnection::ReportUsagePattern() const {
6948 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006949 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6950 usage_event_accumulator_,
6951 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006952 const int bad_bits =
6953 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6954 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6955 const int good_bits =
6956 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6957 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6958 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6959 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6960 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006961 // If called after close(), we can't report, because observer may have
6962 // been deallocated, and therefore pointer is null. Write to log instead.
6963 if (observer_) {
6964 Observer()->OnInterestingUsage(usage_event_accumulator_);
6965 } else {
6966 RTC_LOG(LS_INFO) << "Interesting usage signature "
6967 << usage_event_accumulator_
6968 << " observed after observer shutdown";
6969 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006970 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006971}
6972
Steve Anton0ffaaa22018-02-23 10:31:30 -08006973void PeerConnection::ReportNegotiatedSdpSemantics(
6974 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006975 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006976 switch (answer.description()->msid_signaling()) {
6977 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006978 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006979 break;
6980 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006981 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006982 break;
6983 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006984 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006985 break;
6986 case cricket::kMsidSignalingMediaSection |
6987 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006988 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006989 break;
6990 default:
6991 RTC_NOTREACHED();
6992 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006993 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6994 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006995}
6996
Steve Anton75737c02017-11-06 10:37:17 -08006997// We need to check the local/remote description for the Transport instead of
6998// the session, because a new Transport added during renegotiation may have
6999// them unset while the session has them set from the previous negotiation.
7000// Not doing so may trigger the auto generation of transport description and
7001// mess up DTLS identity information, ICE credential, etc.
7002bool PeerConnection::ReadyToUseRemoteCandidate(
7003 const IceCandidateInterface* candidate,
7004 const SessionDescriptionInterface* remote_desc,
7005 bool* valid) {
7006 *valid = true;
7007
7008 const SessionDescriptionInterface* current_remote_desc =
7009 remote_desc ? remote_desc : remote_description();
7010
7011 if (!current_remote_desc) {
7012 return false;
7013 }
7014
Guido Urdaneta41633172019-05-23 20:12:29 +02007015 RTCErrorOr<const cricket::ContentInfo*> result =
7016 FindContentInfo(current_remote_desc, candidate);
7017 if (!result.ok()) {
7018 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7019 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007020
7021 *valid = false;
7022 return false;
7023 }
7024
Guido Urdaneta41633172019-05-23 20:12:29 +02007025 std::string transport_name = GetTransportName(result.value()->name);
7026 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007027}
7028
7029bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007030 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007031 (dtls_enabled_ ||
7032 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007033}
7034
7035void PeerConnection::OnTransportControllerGatheringState(
7036 cricket::IceGatheringState state) {
7037 RTC_DCHECK(signaling_thread()->IsCurrent());
7038 if (state == cricket::kIceGatheringGathering) {
7039 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7040 } else if (state == cricket::kIceGatheringComplete) {
7041 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7042 }
7043}
7044
7045void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007046 std::map<std::string, std::set<cricket::MediaType>>
7047 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007048 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007049 if (transceiver->internal()->channel()) {
7050 const std::string& transport_name =
7051 transceiver->internal()->channel()->transport_name();
7052 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007053 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007054 }
Steve Anton75737c02017-11-06 10:37:17 -08007055 }
7056 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007057 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7058 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007059 }
Zhi Huange830e682018-03-30 10:48:35 -07007060
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007061 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007062 if (transport_name) {
7063 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007064 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007065 }
Zhi Huange830e682018-03-30 10:48:35 -07007066
Steve Antonc7b964c2018-02-01 14:39:45 -08007067 for (const auto& entry : media_types_by_transport_name) {
7068 const std::string& transport_name = entry.first;
7069 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007070 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007071 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007072 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007073 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007074 }
7075 }
7076}
7077// Walk through the ConnectionInfos to gather best connection usage
7078// for IPv4 and IPv6.
7079void PeerConnection::ReportBestConnectionState(
7080 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007081 for (const cricket::TransportChannelStats& channel_stats :
7082 stats.channel_stats) {
7083 for (const cricket::ConnectionInfo& connection_info :
7084 channel_stats.connection_infos) {
7085 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007086 continue;
7087 }
7088
Steve Antonc7b964c2018-02-01 14:39:45 -08007089 const cricket::Candidate& local = connection_info.local_candidate;
7090 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007091
7092 // Increment the counter for IceCandidatePairType.
7093 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7094 (local.type() == RELAY_PORT_TYPE &&
7095 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007096 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7097 GetIceCandidatePairCounter(local, remote),
7098 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007099 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007100 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7101 GetIceCandidatePairCounter(local, remote),
7102 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007103 } else {
7104 RTC_CHECK(0);
7105 }
Steve Anton75737c02017-11-06 10:37:17 -08007106
7107 // Increment the counter for IP type.
7108 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007109 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7110 kBestConnections_IPv4,
7111 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007112 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007113 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7114 kBestConnections_IPv6,
7115 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007116 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007117 RTC_CHECK(!local.address().hostname().empty() &&
7118 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007119 }
7120
7121 return;
7122 }
7123 }
7124}
7125
7126void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007127 const cricket::TransportStats& stats,
7128 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007129 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7130 return;
7131 }
7132
7133 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7134 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7135 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7136 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7137 return;
7138 }
7139
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007140 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7141 for (cricket::MediaType media_type : media_types) {
7142 switch (media_type) {
7143 case cricket::MEDIA_TYPE_AUDIO:
7144 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7145 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7146 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7147 break;
7148 case cricket::MEDIA_TYPE_VIDEO:
7149 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7150 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7151 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7152 break;
7153 case cricket::MEDIA_TYPE_DATA:
7154 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7155 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7156 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7157 break;
7158 default:
7159 RTC_NOTREACHED();
7160 continue;
7161 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007162 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007163 }
7164
7165 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7166 for (cricket::MediaType media_type : media_types) {
7167 switch (media_type) {
7168 case cricket::MEDIA_TYPE_AUDIO:
7169 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7170 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7171 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7172 break;
7173 case cricket::MEDIA_TYPE_VIDEO:
7174 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7175 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7176 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7177 break;
7178 case cricket::MEDIA_TYPE_DATA:
7179 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7180 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7181 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7182 break;
7183 default:
7184 RTC_NOTREACHED();
7185 continue;
7186 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007187 }
Steve Anton75737c02017-11-06 10:37:17 -08007188 }
7189}
7190
7191void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007192 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007193 RTC_DCHECK(call_);
7194 call_->OnSentPacket(sent_packet);
7195}
7196
7197const std::string PeerConnection::GetTransportName(
7198 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007199 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007200 if (channel) {
7201 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007202 }
Steve Anton6fec8802017-12-04 10:37:29 -08007203 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007204 RTC_DCHECK(sctp_mid_);
7205 if (content_name == *sctp_mid_) {
7206 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007207 }
7208 }
7209 // Return an empty string if failed to retrieve the transport name.
7210 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007211}
7212
Steve Anton6fec8802017-12-04 10:37:29 -08007213void PeerConnection::DestroyTransceiverChannel(
7214 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7215 transceiver) {
7216 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007217
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007218 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007219 if (channel) {
7220 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007221 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007222 }
7223}
7224
7225void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007226 if (rtp_data_channel_) {
7227 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007228 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007229 rtp_data_channel_ = nullptr;
7230 }
7231
7232 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7233 // grab a reference to this PeerConnection. If this is called from the
7234 // PeerConnection destructor, the RefCountedObject vtable will have already
7235 // been destroyed (since it is a subclass of PeerConnection) and using
7236 // rtc::Bind will cause "Pure virtual function called" error to appear.
7237
7238 if (sctp_transport_) {
7239 OnDataChannelDestroyed();
7240 network_thread()->Invoke<void>(RTC_FROM_HERE,
7241 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007242 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007243 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007244
7245 if (media_transport_) {
7246 OnDataChannelDestroyed();
7247 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7248 RTC_DCHECK_RUN_ON(network_thread());
7249 TeardownMediaTransportForDataChannels_n();
7250 });
7251 }
Steve Anton6fec8802017-12-04 10:37:29 -08007252}
7253
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007254void PeerConnection::DestroyChannelInterface(
7255 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007256 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007257 switch (channel->media_type()) {
7258 case cricket::MEDIA_TYPE_AUDIO:
7259 channel_manager()->DestroyVoiceChannel(
7260 static_cast<cricket::VoiceChannel*>(channel));
7261 break;
7262 case cricket::MEDIA_TYPE_VIDEO:
7263 channel_manager()->DestroyVideoChannel(
7264 static_cast<cricket::VideoChannel*>(channel));
7265 break;
7266 case cricket::MEDIA_TYPE_DATA:
7267 channel_manager()->DestroyRtpDataChannel(
7268 static_cast<cricket::RtpDataChannel*>(channel));
7269 break;
7270 default:
7271 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7272 break;
7273 }
Zhi Huange830e682018-03-30 10:48:35 -07007274}
Steve Anton6fec8802017-12-04 10:37:29 -08007275
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007276bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007277 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007278 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007279 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007280 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007281 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007282 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007283 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007284 auto base_channel = GetChannel(mid);
7285 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007286 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007287 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007288 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007289 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007290 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007291
Karl Wiberg5966c502019-02-21 23:55:09 +01007292 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007293 // Only pass media transport to call object if media transport is used
7294 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007295 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007296 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007297
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007298 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007299}
7300
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007301void PeerConnection::OnSetStreams() {
7302 RTC_DCHECK_RUN_ON(signaling_thread());
7303 if (IsUnifiedPlan())
7304 UpdateNegotiationNeeded();
7305}
7306
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007307PeerConnectionObserver* PeerConnection::Observer() const {
7308 // In earlier production code, the pointer was not cleared on close,
7309 // which might have led to undefined behavior if the observer was not
7310 // deallocated, or strange crashes if it was.
7311 // We use CHECK in order to catch such behavior if it exists.
7312 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7313 RTC_CHECK(observer_);
7314 return observer_;
7315}
7316
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007317CryptoOptions PeerConnection::GetCryptoOptions() {
7318 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7319 // after it has been removed.
7320 return configuration_.crypto_options.has_value()
7321 ? *configuration_.crypto_options
7322 : factory_->options().crypto_options;
7323}
7324
Harald Alvestrand89061872018-01-02 14:08:34 +01007325void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007326 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007327 if (stats_collector_) {
7328 stats_collector_->ClearCachedStatsReport();
7329 }
7330}
7331
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007332void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007333 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7334 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007335}
7336
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007337void PeerConnection::UpdateNegotiationNeeded() {
7338 RTC_DCHECK_RUN_ON(signaling_thread());
7339 if (!IsUnifiedPlan()) {
7340 Observer()->OnRenegotiationNeeded();
7341 return;
7342 }
7343
7344 // If connection's [[IsClosed]] slot is true, abort these steps.
7345 if (IsClosed())
7346 return;
7347
7348 // If connection's signaling state is not "stable", abort these steps.
7349 if (signaling_state() != kStable)
7350 return;
7351
7352 // NOTE
7353 // The negotiation-needed flag will be updated once the state transitions to
7354 // "stable", as part of the steps for setting an RTCSessionDescription.
7355
7356 // If the result of checking if negotiation is needed is false, clear the
7357 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7358 // to false, and abort these steps.
7359 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7360 if (!is_negotiation_needed) {
7361 is_negotiation_needed_ = false;
7362 return;
7363 }
7364
7365 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7366 // steps.
7367 if (is_negotiation_needed_)
7368 return;
7369
7370 // Set connection's [[NegotiationNeeded]] slot to true.
7371 is_negotiation_needed_ = true;
7372
7373 // Queue a task that runs the following steps:
7374 // If connection's [[IsClosed]] slot is true, abort these steps.
7375 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7376 // Fire an event named negotiationneeded at connection.
7377 Observer()->OnRenegotiationNeeded();
7378}
7379
7380bool PeerConnection::CheckIfNegotiationIsNeeded() {
7381 RTC_DCHECK_RUN_ON(signaling_thread());
7382 // 1. If any implementation-specific negotiation is required, as described at
7383 // the start of this section, return true.
7384
Henrik Boström79b69802019-07-18 11:16:56 +02007385 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7386 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7387 return true;
7388 }
7389
7390 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007391 const SessionDescriptionInterface* description = current_local_description();
7392 if (!description)
7393 return true;
7394
Henrik Boström79b69802019-07-18 11:16:56 +02007395 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007396 // description has been negotiated yet for data, return true.
7397 if (!sctp_data_channels_.empty()) {
7398 if (!cricket::GetFirstDataContent(description->description()->contents()))
7399 return true;
7400 }
7401
Henrik Boström79b69802019-07-18 11:16:56 +02007402 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007403 // following checks:
7404 for (const auto& transceiver : transceivers_) {
7405 const ContentInfo* current_local_msection =
7406 FindTransceiverMSection(transceiver.get(), description);
7407
7408 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7409 transceiver.get(), current_remote_description());
7410
Henrik Boström79b69802019-07-18 11:16:56 +02007411 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007412 // but the associated m= section is not yet rejected in
7413 // connection.[[CurrentLocalDescription]] or
7414 // connection.[[CurrentRemoteDescription]], return true.
7415 if (transceiver->stopped()) {
7416 if (current_local_msection && !current_local_msection->rejected &&
7417 ((current_remote_msection && !current_remote_msection->rejected) ||
7418 !current_remote_msection)) {
7419 return true;
7420 }
7421 continue;
7422 }
7423
Henrik Boström79b69802019-07-18 11:16:56 +02007424 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007425 // section in description, return true.
7426 if (!current_local_msection)
7427 return true;
7428
7429 const MediaContentDescription* current_local_media_description =
7430 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007431 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007432 // in description then perform the following checks:
7433
Henrik Boström79b69802019-07-18 11:16:56 +02007434 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007435 // associated m= section in description either doesn't contain a single
7436 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7437 // m= section, or the MSID values themselves, differ from what is in
7438 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7439 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7440 if (current_local_media_description->streams().size() == 0)
7441 return true;
7442
7443 std::vector<std::string> msection_msids;
7444 for (const auto& stream : current_local_media_description->streams()) {
7445 for (const std::string& msid : stream.stream_ids())
7446 msection_msids.push_back(msid);
7447 }
7448
7449 std::vector<std::string> transceiver_msids =
7450 transceiver->sender()->stream_ids();
7451 if (msection_msids.size() != transceiver_msids.size())
7452 return true;
7453
7454 absl::c_sort(transceiver_msids);
7455 absl::c_sort(msection_msids);
7456 if (transceiver_msids != msection_msids)
7457 return true;
7458 }
7459
Henrik Boström79b69802019-07-18 11:16:56 +02007460 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007461 // associated m= section in neither connection.[[CurrentLocalDescription]]
7462 // nor connection.[[CurrentRemoteDescription]] matches
7463 // transceiver.[[Direction]], return true.
7464 if (description->GetType() == SdpType::kOffer) {
7465 if (!current_remote_description())
7466 return true;
7467
7468 if (!current_remote_msection)
7469 return true;
7470
7471 RtpTransceiverDirection current_local_direction =
7472 current_local_media_description->direction();
7473 RtpTransceiverDirection current_remote_direction =
7474 current_remote_msection->media_description()->direction();
7475 if (transceiver->direction() != current_local_direction &&
7476 transceiver->direction() !=
7477 RtpTransceiverDirectionReversed(current_remote_direction)) {
7478 return true;
7479 }
7480 }
7481
Henrik Boström79b69802019-07-18 11:16:56 +02007482 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007483 // associated m= section in the description does not match
7484 // transceiver.[[Direction]] intersected with the offered direction (as
7485 // described in [JSEP] (section 5.3.1.)), return true.
7486 if (description->GetType() == SdpType::kAnswer) {
7487 if (!remote_description())
7488 return true;
7489
7490 const ContentInfo* offered_remote_msection =
7491 FindTransceiverMSection(transceiver.get(), remote_description());
7492
7493 RtpTransceiverDirection offered_direction =
7494 offered_remote_msection
7495 ? offered_remote_msection->media_description()->direction()
7496 : RtpTransceiverDirection::kInactive;
7497
7498 if (current_local_media_description->direction() !=
7499 (RtpTransceiverDirectionIntersection(
7500 transceiver->direction(),
7501 RtpTransceiverDirectionReversed(offered_direction)))) {
7502 return true;
7503 }
7504 }
7505 }
7506
7507 // If all the preceding checks were performed and true was not returned,
7508 // nothing remains to be negotiated; return false.
7509 return false;
7510}
7511
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007512} // namespace webrtc