blob: fd2b81fd0929a519211fba977dadf2f44b2f543d [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>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
Steve Antondcc3c022017-12-22 16:02:54 -080016#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080017#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080018#include <utility>
19#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000020
Steve Anton64b626b2019-01-28 17:25:26 -080021#include "absl/algorithm/container.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"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020028#include "api/rtc_event_log/rtc_event_log.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020029#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070030#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "logging/rtc_event_log/ice_logger.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";
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700113// Controls datagram transport data channel support.
114const char kDatagramTransportDataChannelFieldTrial[] =
115 "WebRTC-DatagramTransportDataChannels";
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700116
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800117// UMA metric names.
118const char kSimulcastVersionApplyLocalDescription[] =
119 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
120const char kSimulcastVersionApplyRemoteDescription[] =
121 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
122const char kSimulcastNumberOfEncodings[] =
123 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
124const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
125
Seth Hampson845e8782018-03-02 11:34:10 -0800126static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800127static const char kDefaultAudioSenderId[] = "defaulta0";
128static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700129
zhihuang8f65cdf2016-05-06 18:40:30 -0700130// The length of RTCP CNAMEs.
131static const int kRtcpCnameLength = 16;
132
Steve Antonad182762018-09-05 20:22:40 +0000133enum {
134 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
135 MSG_SET_SESSIONDESCRIPTION_FAILED,
136 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
137 MSG_GETSTATS,
Steve Antonad182762018-09-05 20:22:40 +0000138 MSG_REPORT_USAGE_PATTERN,
139};
140
Harald Alvestrand19793842018-06-25 12:03:50 +0200141static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
142
Steve Antonad182762018-09-05 20:22:40 +0000143struct SetSessionDescriptionMsg : public rtc::MessageData {
144 explicit SetSessionDescriptionMsg(
145 webrtc::SetSessionDescriptionObserver* observer)
146 : observer(observer) {}
147
148 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
149 RTCError error;
150};
151
152struct CreateSessionDescriptionMsg : public rtc::MessageData {
153 explicit CreateSessionDescriptionMsg(
154 webrtc::CreateSessionDescriptionObserver* observer)
155 : observer(observer) {}
156
157 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
158 RTCError error;
159};
160
161struct GetStatsMsg : public rtc::MessageData {
162 GetStatsMsg(webrtc::StatsObserver* observer,
163 webrtc::MediaStreamTrackInterface* track)
164 : observer(observer), track(track) {}
165 rtc::scoped_refptr<webrtc::StatsObserver> observer;
166 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
167};
168
deadbeefab9b2d12015-10-14 11:33:11 -0700169// Check if we can send |new_stream| on a PeerConnection.
170bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
171 webrtc::MediaStreamInterface* new_stream) {
172 if (!new_stream || !current_streams) {
173 return false;
174 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700175 if (current_streams->find(new_stream->id()) != nullptr) {
176 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100177 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700178 return false;
179 }
180 return true;
181}
182
deadbeef5e97fb52015-10-15 12:49:08 -0700183// If the direction is "recvonly" or "inactive", treat the description
184// as containing no streams.
185// See: https://code.google.com/p/webrtc/issues/detail?id=5054
186std::vector<cricket::StreamParams> GetActiveStreams(
187 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800188 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700189 ? desc->streams()
190 : std::vector<cricket::StreamParams>();
191}
192
deadbeefab9b2d12015-10-14 11:33:11 -0700193bool IsValidOfferToReceiveMedia(int value) {
194 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
195 return (value >= Options::kUndefined) &&
196 (value <= Options::kMaxOfferToReceiveMedia);
197}
198
zhihuang1c378ed2017-08-17 14:10:50 -0700199// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800200void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700201 const std::vector<rtc::scoped_refptr<
202 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700203 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200204 cricket::MediaDescriptionOptions* video_media_description_options,
205 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700206 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700207 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
208 if (audio_media_description_options) {
209 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700210 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700211 }
212 } else {
213 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
214 if (video_media_description_options) {
215 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800216 sender->id(), sender->internal()->stream_ids(), {},
217 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700218 }
219 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700220 }
zhihuang1c378ed2017-08-17 14:10:50 -0700221}
olka3c747662017-08-17 06:50:32 -0700222
zhihuang1c378ed2017-08-17 14:10:50 -0700223// Add options to |session_options| from |rtp_data_channels|.
224void AddRtpDataChannelOptions(
225 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
226 rtp_data_channels,
227 cricket::MediaDescriptionOptions* data_media_description_options) {
228 if (!data_media_description_options) {
229 return;
230 }
deadbeefab9b2d12015-10-14 11:33:11 -0700231 // Check for data channels.
232 for (const auto& kv : rtp_data_channels) {
233 const DataChannel* channel = kv.second;
234 if (channel->state() == DataChannel::kConnecting ||
235 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700236 // Legacy RTP data channels are signaled with the track/stream ID set to
237 // the data channel's label.
238 data_media_description_options->AddRtpDataChannel(channel->label(),
239 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700240 }
241 }
242}
243
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700244uint32_t ConvertIceTransportTypeToCandidateFilter(
245 PeerConnectionInterface::IceTransportsType type) {
246 switch (type) {
247 case PeerConnectionInterface::kNone:
248 return cricket::CF_NONE;
249 case PeerConnectionInterface::kRelay:
250 return cricket::CF_RELAY;
251 case PeerConnectionInterface::kNoHost:
252 return (cricket::CF_ALL & ~cricket::CF_HOST);
253 case PeerConnectionInterface::kAll:
254 return cricket::CF_ALL;
255 default:
nissec80e7412017-01-11 05:56:46 -0800256 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700257 }
258 return cricket::CF_NONE;
259}
260
Steve Antonba818672017-11-06 10:21:57 -0800261std::string GetSignalingStateString(
262 PeerConnectionInterface::SignalingState state) {
263 switch (state) {
264 case PeerConnectionInterface::kStable:
265 return "kStable";
266 case PeerConnectionInterface::kHaveLocalOffer:
267 return "kHaveLocalOffer";
268 case PeerConnectionInterface::kHaveLocalPrAnswer:
269 return "kHavePrAnswer";
270 case PeerConnectionInterface::kHaveRemoteOffer:
271 return "kHaveRemoteOffer";
272 case PeerConnectionInterface::kHaveRemotePrAnswer:
273 return "kHaveRemotePrAnswer";
274 case PeerConnectionInterface::kClosed:
275 return "kClosed";
276 }
277 RTC_NOTREACHED();
278 return "";
279}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700280
Steve Anton75737c02017-11-06 10:37:17 -0800281IceCandidatePairType GetIceCandidatePairCounter(
282 const cricket::Candidate& local,
283 const cricket::Candidate& remote) {
284 const auto& l = local.type();
285 const auto& r = remote.type();
286 const auto& host = LOCAL_PORT_TYPE;
287 const auto& srflx = STUN_PORT_TYPE;
288 const auto& relay = RELAY_PORT_TYPE;
289 const auto& prflx = PRFLX_PORT_TYPE;
290 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800291 bool local_hostname =
292 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
293 bool remote_hostname = !remote.address().hostname().empty() &&
294 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800295 bool local_private = IPIsPrivate(local.address().ipaddr());
296 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800297 if (local_hostname) {
298 if (remote_hostname) {
299 return kIceCandidatePairHostNameHostName;
300 } else if (remote_private) {
301 return kIceCandidatePairHostNameHostPrivate;
302 } else {
303 return kIceCandidatePairHostNameHostPublic;
304 }
305 } else if (local_private) {
306 if (remote_hostname) {
307 return kIceCandidatePairHostPrivateHostName;
308 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800309 return kIceCandidatePairHostPrivateHostPrivate;
310 } else {
311 return kIceCandidatePairHostPrivateHostPublic;
312 }
313 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800314 if (remote_hostname) {
315 return kIceCandidatePairHostPublicHostName;
316 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800317 return kIceCandidatePairHostPublicHostPrivate;
318 } else {
319 return kIceCandidatePairHostPublicHostPublic;
320 }
321 }
322 }
323 if (l == host && r == srflx)
324 return kIceCandidatePairHostSrflx;
325 if (l == host && r == relay)
326 return kIceCandidatePairHostRelay;
327 if (l == host && r == prflx)
328 return kIceCandidatePairHostPrflx;
329 if (l == srflx && r == host)
330 return kIceCandidatePairSrflxHost;
331 if (l == srflx && r == srflx)
332 return kIceCandidatePairSrflxSrflx;
333 if (l == srflx && r == relay)
334 return kIceCandidatePairSrflxRelay;
335 if (l == srflx && r == prflx)
336 return kIceCandidatePairSrflxPrflx;
337 if (l == relay && r == host)
338 return kIceCandidatePairRelayHost;
339 if (l == relay && r == srflx)
340 return kIceCandidatePairRelaySrflx;
341 if (l == relay && r == relay)
342 return kIceCandidatePairRelayRelay;
343 if (l == relay && r == prflx)
344 return kIceCandidatePairRelayPrflx;
345 if (l == prflx && r == host)
346 return kIceCandidatePairPrflxHost;
347 if (l == prflx && r == srflx)
348 return kIceCandidatePairPrflxSrflx;
349 if (l == prflx && r == relay)
350 return kIceCandidatePairPrflxRelay;
351 return kIceCandidatePairMax;
352}
353
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800354// Logic to decide if an m= section can be recycled. This means that the new
355// m= section is not rejected, but the old local or remote m= section is
356// rejected. |old_content_one| and |old_content_two| refer to the m= section
357// of the old remote and old local descriptions in no particular order.
358// We need to check both the old local and remote because either
359// could be the most current from the latest negotation.
360bool IsMediaSectionBeingRecycled(SdpType type,
361 const ContentInfo& content,
362 const ContentInfo* old_content_one,
363 const ContentInfo* old_content_two) {
364 return type == SdpType::kOffer && !content.rejected &&
365 ((old_content_one && old_content_one->rejected) ||
366 (old_content_two && old_content_two->rejected));
367}
368
Steve Anton75737c02017-11-06 10:37:17 -0800369// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370// |current_desc|. The number of m= sections in |new_desc| should be no
371// less than |current_desc|. In the case of checking an answer's
372// |new_desc|, the |current_desc| is the last offer that was set as the
373// local or remote. In the case of checking an offer's |new_desc| we
374// check against the local and remote descriptions stored from the last
375// negotiation, because either of these could be the most up to date for
376// possible rejected m sections. These are the |current_desc| and
377// |secondary_current_desc|.
378bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
379 const SessionDescription* secondary_current_desc,
380 const SessionDescription& new_desc,
381 const SdpType type) {
382 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800383 return false;
384 }
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
387 const cricket::ContentInfo* secondary_content_info = nullptr;
388 if (secondary_current_desc &&
389 i < secondary_current_desc->contents().size()) {
390 secondary_content_info = &secondary_current_desc->contents()[i];
391 }
392 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
393 &current_desc.contents()[i],
394 secondary_content_info)) {
395 // For new offer descriptions, if the media section can be recycled, it's
396 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800397 continue;
398 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800399 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800400 return false;
401 }
402 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800403 new_desc.contents()[i].media_description();
404 const MediaContentDescription* current_desc_mdesc =
405 current_desc.contents()[i].media_description();
406 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800407 return false;
408 }
409 }
410 return true;
411}
412
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
414 const SessionDescription& desc2) {
415 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800416}
417
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700418void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
419 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200420 // Array of structs needed to map {KeyExchangeProtocolType,
421 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
422 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
423 static constexpr struct {
424 KeyExchangeProtocolType protocol_type;
425 cricket::MediaType media_type;
426 KeyExchangeProtocolMedia protocol_media;
427 } kEnumCounterKeyProtocolMediaMap[] = {
428 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
429 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
430 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
431 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
432 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
433 kEnumCounterKeyProtocolMediaTypeDtlsData},
434 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
435 kEnumCounterKeyProtocolMediaTypeSdesAudio},
436 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
437 kEnumCounterKeyProtocolMediaTypeSdesVideo},
438 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
439 kEnumCounterKeyProtocolMediaTypeSdesData},
440 };
441
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700442 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
443 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100444
Mirko Bonadeiab499822018-09-11 10:43:20 +0200445 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
446 if (i.protocol_type == protocol_type && i.media_type == media_type) {
447 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
448 i.protocol_media,
449 kEnumCounterKeyProtocolMediaTypeMax);
450 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100451 }
452}
453
Harald Alvestrand76829d72018-07-18 23:24:36 +0200454void NoteAddIceCandidateResult(int result) {
455 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
456 kAddIceCandidateMax);
457}
458
Steve Anton75737c02017-11-06 10:37:17 -0800459// Checks that each non-rejected content has SDES crypto keys or a DTLS
460// fingerprint, unless it's in a BUNDLE group, in which case only the
461// BUNDLE-tag section (first media section/description in the BUNDLE group)
462// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
463// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
464// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700465RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800466 const cricket::ContentGroup* bundle =
467 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800468 for (const cricket::ContentInfo& content_info : desc->contents()) {
469 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800470 continue;
471 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100472 // Note what media is used with each crypto protocol, for all sections.
473 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
474 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700475 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800476 const std::string& mid = content_info.name;
477 if (bundle && bundle->HasContentName(mid) &&
478 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800479 // This isn't the first media section in the BUNDLE group, so it's not
480 // required to have crypto attributes, since only the crypto attributes
481 // from the first section actually get used.
482 continue;
483 }
484
485 // If the content isn't rejected or bundled into another m= section, crypto
486 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800487 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800488 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800489 if (!media || !tinfo) {
490 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800491 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800492 }
493 if (dtls_enabled) {
494 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100495 RTC_LOG(LS_WARNING)
496 << "Session description must have DTLS fingerprint if "
497 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800498 return RTCError(RTCErrorType::INVALID_PARAMETER,
499 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800500 }
501 } else {
502 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800504 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800505 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800506 }
507 }
508 }
Steve Anton8a006912017-12-04 15:25:56 -0800509 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800510}
511
512// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
513// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
514// media section/description in the BUNDLE group) needs a ufrag and pwd.
515bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
516 const cricket::ContentGroup* bundle =
517 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800518 for (const cricket::ContentInfo& content_info : desc->contents()) {
519 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800520 continue;
521 }
Steve Anton8a006912017-12-04 15:25:56 -0800522 const std::string& mid = content_info.name;
523 if (bundle && bundle->HasContentName(mid) &&
524 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800525 // This isn't the first media section in the BUNDLE group, so it's not
526 // required to have ufrag/password, since only the ufrag/password from
527 // the first section actually get used.
528 continue;
529 }
530
531 // If the content isn't rejected or bundled into another m= section,
532 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800533 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800534 if (!tinfo) {
535 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100536 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800537 return false;
538 }
539 if (tinfo->description.ice_ufrag.empty() ||
540 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100541 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800542 return false;
543 }
544 }
545 return true;
546}
547
Steve Anton75737c02017-11-06 10:37:17 -0800548// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
549bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
550 const SessionDescriptionInterface* new_desc,
551 const std::string& content_name) {
552 if (!old_desc) {
553 return false;
554 }
555 const SessionDescription* new_sd = new_desc->description();
556 const SessionDescription* old_sd = old_desc->description();
557 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
558 if (!cinfo || cinfo->rejected) {
559 return false;
560 }
561 // If the content isn't rejected, check if ufrag and password has changed.
562 const cricket::TransportDescription* new_transport_desc =
563 new_sd->GetTransportDescriptionByName(content_name);
564 const cricket::TransportDescription* old_transport_desc =
565 old_sd->GetTransportDescriptionByName(content_name);
566 if (!new_transport_desc || !old_transport_desc) {
567 // No transport description exists. This is not an ICE restart.
568 return false;
569 }
570 if (cricket::IceCredentialsChanged(
571 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
572 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100573 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
574 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800575 return true;
576 }
577 return false;
578}
579
Steve Anton80dd7b52018-02-16 17:08:42 -0800580// Generates a string error message for SetLocalDescription/SetRemoteDescription
581// from an RTCError.
582std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
583 SdpType type,
584 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200585 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800586 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
587 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200588 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800589}
590
Seth Hampson5b4f0752018-04-02 16:31:36 -0700591std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
592 std::string output = "streams=[";
593 const char* separator = "";
594 for (const auto& stream_id : stream_ids) {
595 output.append(separator).append(stream_id);
596 separator = ", ";
597 }
598 output.append("]");
599 return output;
600}
601
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200602absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700603 int rtc_configuration_parameter) {
604 if (rtc_configuration_parameter ==
605 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200606 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700607 }
608 return rtc_configuration_parameter;
609}
610
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800611void ReportSimulcastApiVersion(const char* name,
612 const SessionDescription& session) {
613 bool has_legacy = false;
614 bool has_spec_compliant = false;
615 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200616 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800617 continue;
618 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200619 has_spec_compliant |= content.media_description()->HasSimulcast();
620 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800621 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
622 }
623 }
624
625 if (has_legacy) {
626 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
627 kSimulcastApiVersionMax);
628 }
629 if (has_spec_compliant) {
630 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
631 kSimulcastApiVersionMax);
632 }
633 if (!has_legacy && !has_spec_compliant) {
634 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
635 kSimulcastApiVersionMax);
636 }
637}
638
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200639const ContentInfo* FindTransceiverMSection(
640 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
641 const SessionDescriptionInterface* session_description) {
642 return transceiver->mid()
643 ? session_description->description()->GetContentByName(
644 *transceiver->mid())
645 : nullptr;
646}
647
Henrik Boströma3728d32019-10-28 12:09:49 +0100648// Wraps a CreateSessionDescriptionObserver and an OperationsChain operation
649// complete callback. When the observer is invoked, the wrapped observer is
650// invoked followed by invoking the completion callback.
651class CreateSessionDescriptionObserverOperationWrapper
652 : public CreateSessionDescriptionObserver {
653 public:
654 CreateSessionDescriptionObserverOperationWrapper(
655 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer,
656 std::function<void()> operation_complete_callback)
657 : observer_(std::move(observer)),
658 operation_complete_callback_(std::move(operation_complete_callback)) {
659 RTC_DCHECK(observer_);
660 }
661 ~CreateSessionDescriptionObserverOperationWrapper() override {
662 RTC_DCHECK(was_called_);
663 }
664
665 void OnSuccess(SessionDescriptionInterface* desc) override {
666 RTC_DCHECK(!was_called_);
667#ifdef RTC_DCHECK_IS_ON
668 was_called_ = true;
669#endif // RTC_DCHECK_IS_ON
670 // Completing the operation before invoking the observer allows the observer
671 // to execute SetLocalDescription() without delay.
672 operation_complete_callback_();
673 observer_->OnSuccess(desc);
674 }
675
676 void OnFailure(RTCError error) override {
677 RTC_DCHECK(!was_called_);
678#ifdef RTC_DCHECK_IS_ON
679 was_called_ = true;
680#endif // RTC_DCHECK_IS_ON
681 operation_complete_callback_();
682 observer_->OnFailure(std::move(error));
683 }
684
685 private:
686#ifdef RTC_DCHECK_IS_ON
687 bool was_called_ = false;
688#endif // RTC_DCHECK_IS_ON
689 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer_;
690 std::function<void()> operation_complete_callback_;
691};
692
Steve Anton75737c02017-11-06 10:37:17 -0800693} // namespace
694
Henrik Boström4e196702019-10-30 10:35:50 +0100695// Used by parameterless SetLocalDescription() to create an offer or answer.
696// Upon completion of creating the session description, SetLocalDescription() is
697// invoked with the result.
698// For consistency with DoSetLocalDescription(), if the PeerConnection is
699// destroyed midst operation, we DO NOT inform the
700// |set_local_description_observer| that the operation failed.
701// TODO(hbos): If/when we process SLD messages in ~PeerConnection, the
702// consistent thing would be to inform the observer here.
703class PeerConnection::ImplicitCreateSessionDescriptionObserver
704 : public CreateSessionDescriptionObserver {
705 public:
706 ImplicitCreateSessionDescriptionObserver(
707 rtc::WeakPtr<PeerConnection> pc,
708 rtc::scoped_refptr<SetSessionDescriptionObserver>
709 set_local_description_observer)
710 : pc_(std::move(pc)),
711 set_local_description_observer_(
712 std::move(set_local_description_observer)) {}
713 ~ImplicitCreateSessionDescriptionObserver() override {
714 RTC_DCHECK(was_called_);
715 }
716
717 void SetOperationCompleteCallback(
718 std::function<void()> operation_complete_callback) {
719 operation_complete_callback_ = std::move(operation_complete_callback);
720 }
721
722 bool was_called() const { return was_called_; }
723
724 void OnSuccess(SessionDescriptionInterface* desc_ptr) override {
725 RTC_DCHECK(!was_called_);
726 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
727 was_called_ = true;
728
729 // Abort early if |pc_| is no longer valid.
730 if (!pc_) {
731 operation_complete_callback_();
732 return;
733 }
734 // DoSetLocalDescription() is currently implemented as a synchronous
735 // operation but where the |set_local_description_observer_|'s callbacks are
736 // invoked asynchronously in a post to PeerConnection::OnMessage().
737 pc_->DoSetLocalDescription(std::move(desc),
738 std::move(set_local_description_observer_));
739 // For backwards-compatability reasons, we declare the operation as
740 // completed here (rather than in PeerConnection::OnMessage()). This ensures
741 // that subsequent offer/answer operations can start immediately (without
742 // waiting for OnMessage()).
743 operation_complete_callback_();
744 }
745
746 void OnFailure(RTCError error) override {
747 RTC_DCHECK(!was_called_);
748 was_called_ = true;
749
750 // Abort early if |pc_| is no longer valid.
751 if (!pc_) {
752 operation_complete_callback_();
753 return;
754 }
755 // DoSetLocalDescription() reports its failures in a post. We do the
756 // same thing here for consistency.
757 pc_->PostSetSessionDescriptionFailure(
758 set_local_description_observer_,
759 RTCError(error.type(),
760 std::string("SetLocalDescription failed to create "
761 "session description - ") +
762 error.message()));
763 operation_complete_callback_();
764 }
765
766 private:
767 bool was_called_ = false;
768 rtc::WeakPtr<PeerConnection> pc_;
769 rtc::scoped_refptr<SetSessionDescriptionObserver>
770 set_local_description_observer_;
771 std::function<void()> operation_complete_callback_;
772};
773
Henrik Boström79b69802019-07-18 11:16:56 +0200774class PeerConnection::LocalIceCredentialsToReplace {
775 public:
776 // Sets the ICE credentials that need restarting to the ICE credentials of
777 // the current and pending descriptions.
778 void SetIceCredentialsFromLocalDescriptions(
779 const SessionDescriptionInterface* current_local_description,
780 const SessionDescriptionInterface* pending_local_description) {
781 ice_credentials_.clear();
782 if (current_local_description) {
783 AppendIceCredentialsFromSessionDescription(*current_local_description);
784 }
785 if (pending_local_description) {
786 AppendIceCredentialsFromSessionDescription(*pending_local_description);
787 }
788 }
789
790 void ClearIceCredentials() { ice_credentials_.clear(); }
791
792 // Returns true if we have ICE credentials that need restarting.
793 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
794
795 // Returns true if |local_description| shares no ICE credentials with the
796 // ICE credentials that need restarting.
797 bool SatisfiesIceRestart(
798 const SessionDescriptionInterface& local_description) const {
799 for (const auto& transport_info :
800 local_description.description()->transport_infos()) {
801 if (ice_credentials_.find(std::make_pair(
802 transport_info.description.ice_ufrag,
803 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
804 return false;
805 }
806 }
807 return true;
808 }
809
810 private:
811 void AppendIceCredentialsFromSessionDescription(
812 const SessionDescriptionInterface& desc) {
813 for (const auto& transport_info : desc.description()->transport_infos()) {
814 ice_credentials_.insert(
815 std::make_pair(transport_info.description.ice_ufrag,
816 transport_info.description.ice_pwd));
817 }
818 }
819
820 std::set<std::pair<std::string, std::string>> ice_credentials_;
821};
822
Henrik Boström31638672017-11-23 17:48:32 +0100823// Upon completion, posts a task to execute the callback of the
824// SetSessionDescriptionObserver asynchronously on the same thread. At this
825// point, the state of the peer connection might no longer reflect the effects
826// of the SetRemoteDescription operation, as the peer connection could have been
827// modified during the post.
828// TODO(hbos): Remove this class once we remove the version of
829// PeerConnectionInterface::SetRemoteDescription() that takes a
830// SetSessionDescriptionObserver as an argument.
831class PeerConnection::SetRemoteDescriptionObserverAdapter
832 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
833 public:
834 SetRemoteDescriptionObserverAdapter(
835 rtc::scoped_refptr<PeerConnection> pc,
836 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
837 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
838
839 // SetRemoteDescriptionObserverInterface implementation.
840 void OnSetRemoteDescriptionComplete(RTCError error) override {
841 if (error.ok())
842 pc_->PostSetSessionDescriptionSuccess(wrapper_);
843 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100844 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100845 }
846
847 private:
848 rtc::scoped_refptr<PeerConnection> pc_;
849 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
850};
851
deadbeef293e9262017-01-11 12:28:30 -0800852bool PeerConnectionInterface::RTCConfiguration::operator==(
853 const PeerConnectionInterface::RTCConfiguration& o) const {
854 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700855 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800856 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000857 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700858 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800859 BundlePolicy bundle_policy;
860 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700861 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
862 int ice_candidate_pool_size;
863 bool disable_ipv6;
864 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700865 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100866 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700867 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200868 absl::optional<int> screencast_min_bitrate;
869 absl::optional<bool> combined_audio_video_bwe;
870 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800871 TcpCandidatePolicy tcp_candidate_policy;
872 CandidateNetworkPolicy candidate_network_policy;
873 int audio_jitter_buffer_max_packets;
874 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100875 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100876 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800877 int ice_connection_receiving_timeout;
878 int ice_backup_candidate_pair_ping_interval;
879 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800880 bool prioritize_most_likely_ice_candidate_pairs;
881 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800882 bool prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700883 PortPrunePolicy turn_port_prune_policy;
deadbeef293e9262017-01-11 12:28:30 -0800884 bool presume_writable_when_fully_relayed;
885 bool enable_ice_renomination;
886 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700887 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200888 absl::optional<int> ice_check_interval_strong_connectivity;
889 absl::optional<int> ice_check_interval_weak_connectivity;
890 absl::optional<int> ice_check_min_interval;
891 absl::optional<int> ice_unwritable_timeout;
892 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800893 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200894 absl::optional<int> stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200895 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800896 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200897 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700898 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700899 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700900 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700901 absl::optional<bool> use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700902 absl::optional<bool> use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700903 absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700904 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100905 bool offer_extmap_allow_mixed;
Jonas Oreland3c028422019-08-22 16:16:35 +0200906 std::string turn_logging_id;
Eldar Rello5ab79e62019-10-09 18:29:44 +0300907 bool enable_implicit_rollback;
philipel16cec3b2019-10-25 12:23:02 +0200908 absl::optional<bool> allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800909 };
910 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
911 "Did you add something to RTCConfiguration and forget to "
912 "update operator==?");
913 return type == o.type && servers == o.servers &&
914 bundle_policy == o.bundle_policy &&
915 rtcp_mux_policy == o.rtcp_mux_policy &&
916 tcp_candidate_policy == o.tcp_candidate_policy &&
917 candidate_network_policy == o.candidate_network_policy &&
918 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
919 audio_jitter_buffer_fast_accelerate ==
920 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100921 audio_jitter_buffer_min_delay_ms ==
922 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100923 audio_jitter_buffer_enable_rtx_handling ==
924 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800925 ice_connection_receiving_timeout ==
926 o.ice_connection_receiving_timeout &&
927 ice_backup_candidate_pair_ping_interval ==
928 o.ice_backup_candidate_pair_ping_interval &&
929 continual_gathering_policy == o.continual_gathering_policy &&
930 certificates == o.certificates &&
931 prioritize_most_likely_ice_candidate_pairs ==
932 o.prioritize_most_likely_ice_candidate_pairs &&
933 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800934 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700935 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100936 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800937 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800938 screencast_min_bitrate == o.screencast_min_bitrate &&
939 combined_audio_video_bwe == o.combined_audio_video_bwe &&
940 enable_dtls_srtp == o.enable_dtls_srtp &&
941 ice_candidate_pool_size == o.ice_candidate_pool_size &&
942 prune_turn_ports == o.prune_turn_ports &&
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700943 turn_port_prune_policy == o.turn_port_prune_policy &&
deadbeef293e9262017-01-11 12:28:30 -0800944 presume_writable_when_fully_relayed ==
945 o.presume_writable_when_fully_relayed &&
946 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800947 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700948 surface_ice_candidates_on_ice_transport_type_changed ==
949 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800950 ice_check_interval_strong_connectivity ==
951 o.ice_check_interval_strong_connectivity &&
952 ice_check_interval_weak_connectivity ==
953 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700954 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700955 ice_unwritable_timeout == o.ice_unwritable_timeout &&
956 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800957 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800958 stun_candidate_keepalive_interval ==
959 o.stun_candidate_keepalive_interval &&
Steve Anton79e79602017-11-20 10:25:56 -0800960 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800961 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700962 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700963 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700964 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700965 use_media_transport_for_data_channels ==
966 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700967 use_datagram_transport == o.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700968 use_datagram_transport_for_data_channels ==
969 o.use_datagram_transport_for_data_channels &&
Bjorn A Mellem7da4e562019-09-26 11:02:11 -0700970 use_datagram_transport_for_data_channels_receive_only ==
971 o.use_datagram_transport_for_data_channels_receive_only &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100972 crypto_options == o.crypto_options &&
Jonas Oreland3c028422019-08-22 16:16:35 +0200973 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
Eldar Rello5ab79e62019-10-09 18:29:44 +0300974 turn_logging_id == o.turn_logging_id &&
philipel16cec3b2019-10-25 12:23:02 +0200975 enable_implicit_rollback == o.enable_implicit_rollback &&
976 allow_codec_switching == o.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -0800977}
978
979bool PeerConnectionInterface::RTCConfiguration::operator!=(
980 const PeerConnectionInterface::RTCConfiguration& o) const {
981 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800982}
983
Eldar Rello353a7182019-11-25 18:49:44 +0200984void PeerConnection::TransceiverStableState::set_newly_created() {
985 RTC_DCHECK(!has_m_section_);
986 newly_created_ = true;
987}
988
989void PeerConnection::TransceiverStableState::SetMSectionIfUnset(
990 absl::optional<std::string> mid,
991 absl::optional<size_t> mline_index) {
992 if (!has_m_section_) {
993 mid_ = mid;
994 mline_index_ = mline_index;
995 has_m_section_ = true;
996 }
997}
998
999void PeerConnection::TransceiverStableState::SetRemoteStreamIdsIfUnset(
1000 const std::vector<std::string>& ids) {
1001 if (!remote_stream_ids_.has_value()) {
1002 remote_stream_ids_ = ids;
1003 }
1004}
1005
zhihuang8f65cdf2016-05-06 18:40:30 -07001006// Generate a RTCP CNAME when a PeerConnection is created.
1007std::string GenerateRtcpCname() {
1008 std::string cname;
1009 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001010 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -08001011 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -07001012 }
1013 return cname;
1014}
1015
zhihuang1c378ed2017-08-17 14:10:50 -07001016bool ValidateOfferAnswerOptions(
1017 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
1018 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
1019 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -07001020}
1021
zhihuang1c378ed2017-08-17 14:10:50 -07001022// From |rtc_options|, fill parts of |session_options| shared by all generated
1023// m= sections (in other words, nothing that involves a map/array).
1024void ExtractSharedMediaSessionOptions(
1025 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1026 cricket::MediaSessionOptions* session_options) {
1027 session_options->vad_enabled = rtc_options.voice_activity_detection;
1028 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +02001029 session_options->raw_packetization_for_video =
1030 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -07001031}
zhihuanga77e6bb2017-08-14 18:17:48 -07001032
zhihuang38ede132017-06-15 12:52:32 -07001033PeerConnection::PeerConnection(PeerConnectionFactory* factory,
1034 std::unique_ptr<RtcEventLog> event_log,
1035 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -07001037 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +01001038 event_log_ptr_(event_log_.get()),
Henrik Boströma3728d32019-10-28 12:09:49 +01001039 operations_chain_(rtc::OperationsChain::Create()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001040 datagram_transport_config_(
1041 field_trial::FindFullName(kDatagramTransportFieldTrial)),
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001042 datagram_transport_data_channel_config_(
1043 field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -07001044 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -07001045 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -07001046 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001047 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +02001048 call_ptr_(call_.get()),
Henrik Boströma3728d32019-10-28 12:09:49 +01001049 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()),
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01001050 data_channel_controller_(this),
Henrik Boströma3728d32019-10-28 12:09:49 +01001051 weak_ptr_factory_(this) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052
1053PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001054 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -08001055 RTC_DCHECK_RUN_ON(signaling_thread());
1056
Henrik Boströma3728d32019-10-28 12:09:49 +01001057 weak_ptr_factory_.InvalidateWeakPtrs();
1058
Steve Anton8af21862017-12-15 11:20:13 -08001059 // Need to stop transceivers before destroying the stats collector because
1060 // AudioRtpSender has a reference to the StatsCollector it will update when
1061 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +01001062 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08001063 transceiver->Stop();
1064 }
Steve Anton4171afb2017-11-20 10:20:22 -08001065
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001066 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -08001067 if (stats_collector_) {
1068 stats_collector_->WaitForPendingRequest();
1069 stats_collector_ = nullptr;
1070 }
Steve Anton75737c02017-11-06 10:37:17 -08001071
Steve Anton8af21862017-12-15 11:20:13 -08001072 // Don't destroy BaseChannels until after stats has been cleaned up so that
1073 // the last stats request can still read from the channels.
1074 DestroyAllChannels();
1075
Mirko Bonadei675513b2017-11-09 11:09:25 +01001076 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -08001077
1078 webrtc_session_desc_factory_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001079 sctp_factory_.reset();
1080 transport_controller_.reset();
1081
deadbeef91dd5672016-05-18 16:55:30 -07001082 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001083 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1084 RTC_DCHECK_RUN_ON(network_thread());
1085 port_allocator_.reset();
1086 });
eladalon248fd4f2017-09-06 05:18:15 -07001087 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -07001088 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01001089 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07001090 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -08001091 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -07001092 event_log_.reset();
1093 });
Henrik Boströma3728d32019-10-28 12:09:49 +01001094
1095 // Process all pending notifications in the message queue. If we don't do
1096 // this, requests will linger and not know they succeeded or failed.
1097 rtc::MessageList list;
1098 signaling_thread()->Clear(this, rtc::MQID_ANY, &list);
1099 for (auto& msg : list) {
1100 if (msg.message_id == MSG_CREATE_SESSIONDESCRIPTION_FAILED) {
1101 // Processing CreateOffer() and CreateAnswer() messages ensures their
1102 // observers are invoked even if the PeerConnection is destroyed early.
1103 OnMessage(&msg);
1104 } else {
1105 // TODO(hbos): Consider processing all pending messages. This would mean
1106 // that SetLocalDescription() and SetRemoteDescription() observers are
1107 // informed of successes and failures; this is currently NOT the case.
1108 delete msg.pdata;
1109 }
1110 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001111}
1112
Steve Anton8af21862017-12-15 11:20:13 -08001113void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -08001114 // Destroy video channels first since they may have a pointer to a voice
1115 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +01001116 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001117 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001118 DestroyTransceiverChannel(transceiver);
1119 }
1120 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01001121 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001122 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -08001123 DestroyTransceiverChannel(transceiver);
1124 }
1125 }
Harald Alvestrand408cb4b2019-11-16 12:09:08 +01001126 DestroyDataChannelTransport();
Steve Anton3fe1b152017-12-12 10:20:08 -08001127}
1128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001130 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -07001131 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001132 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001133 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -07001134
1135 RTCError config_error = ValidateConfiguration(configuration);
1136 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001137 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -07001138 return false;
1139 }
1140
Benjamin Wrightcab58882018-05-02 15:12:47 -07001141 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001142 RTC_LOG(LS_ERROR)
1143 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001144 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001145 return false;
1146 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001147
Benjamin Wrightcab58882018-05-02 15:12:47 -07001148 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001149 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001150 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001151 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001152 return false;
1153 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001154
Benjamin Wrightcab58882018-05-02 15:12:47 -07001155 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001156 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001157 port_allocator_ = std::move(dependencies.allocator);
Qingsi Wang25ec8882019-11-15 12:33:05 -08001158 ice_transport_factory_ = std::move(dependencies.ice_transport_factory);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001159 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001160
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001161 cricket::ServerAddresses stun_servers;
1162 std::vector<cricket::RelayServerConfig> turn_servers;
1163
1164 RTCErrorType parse_error =
1165 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1166 if (parse_error != RTCErrorType::NONE) {
1167 return false;
1168 }
1169
Jonas Oreland3c028422019-08-22 16:16:35 +02001170 // Add the turn logging id to all turn servers
1171 for (cricket::RelayServerConfig& turn_server : turn_servers) {
1172 turn_server.turn_logging_id = configuration.turn_logging_id;
1173 }
1174
deadbeef91dd5672016-05-18 16:55:30 -07001175 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001176 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001177 const auto pa_result =
1178 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001179 RTC_FROM_HERE,
1180 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001181 stun_servers, turn_servers, configuration));
1182
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001183 // If initialization was successful, note if STUN or TURN servers
1184 // were supplied.
1185 if (!stun_servers.empty()) {
1186 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1187 }
1188 if (!turn_servers.empty()) {
1189 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1190 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001192 // Send information about IPv4/IPv6 status.
1193 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001194 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001195 address_family = kPeerConnection_IPv6;
1196 } else {
1197 address_family = kPeerConnection_IPv4;
1198 }
1199 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1200 kPeerConnectionAddressFamilyCounter_Max);
1201
Zhi Huange830e682018-03-30 10:48:35 -07001202 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1203
Steve Anton75737c02017-11-06 10:37:17 -08001204 // RFC 3264: The numeric value of the session id and version in the
1205 // o line MUST be representable with a "64 bit signed integer".
1206 // Due to this constraint session id |session_id_| is max limited to
1207 // LLONG_MAX.
1208 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001209 JsepTransportController::Config config;
1210 config.redetermine_role_on_ice_restart =
1211 configuration.redetermine_role_on_ice_restart;
1212 config.ssl_max_version = factory_->options().ssl_max_version;
1213 config.disable_encryption = options.disable_encryption;
1214 config.bundle_policy = configuration.bundle_policy;
1215 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001216 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1217 // stub.
1218 config.crypto_options = configuration.crypto_options.has_value()
1219 ? *configuration.crypto_options
1220 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001221 config.transport_observer = this;
Sebastian Jansson1b83a9e2019-09-18 18:22:12 +02001222 // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
1223 // since the JsepTransportController instance is owned by this PeerConnection
1224 // instance and is destroyed before both |rtcp_invoker_| and the |call_|
1225 // pointer.
1226 config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
1227 int64_t packet_time_us) {
1228 RTC_DCHECK_RUN_ON(network_thread());
1229 rtcp_invoker_.AsyncInvoke<void>(
1230 RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
1231 RTC_DCHECK_RUN_ON(worker_thread());
1232 // |call_| is reset on the worker thread in the PeerConnection
1233 // destructor, so we check that it's still valid before propagating
1234 // the packet.
1235 if (call_) {
1236 call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
1237 packet_time_us);
1238 }
1239 });
1240 };
Karl Wibergb03ab712019-02-14 11:59:57 +01001241 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001242#if defined(ENABLE_EXTERNAL_AUTH)
1243 config.enable_external_auth = true;
1244#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001245 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001246
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001247 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001248 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001249 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001250 use_datagram_transport_for_data_channels_ =
1251 datagram_transport_data_channel_config_.enabled &&
1252 configuration.use_datagram_transport_for_data_channels.value_or(
1253 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001254 use_datagram_transport_for_data_channels_receive_only_ =
1255 configuration.use_datagram_transport_for_data_channels_receive_only
1256 .value_or(datagram_transport_data_channel_config_.receive_only);
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -08001257 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001258 if (!factory_->media_transport_factory()) {
1259 RTC_DCHECK(false)
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -08001260 << "PeerConnecton is initialized with use_datagram_transport = true "
1261 "or use_datagram_transport_for_data_channels = true "
Jonas Olssonb2b20312020-01-14 12:11:31 +01001262 "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001263 return false;
1264 }
1265
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001266 config.use_datagram_transport = use_datagram_transport_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07001267 config.use_datagram_transport_for_data_channels =
1268 use_datagram_transport_for_data_channels_;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07001269 config.use_datagram_transport_for_data_channels_receive_only =
1270 use_datagram_transport_for_data_channels_receive_only_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001271 config.media_transport_factory = factory_->media_transport_factory();
1272 }
1273
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001274 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1275 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1276 if (!configuration.certificates.empty()) {
1277 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1278 // just picking the first one. The decision should be made based on the DTLS
1279 // handshake. The DTLS negotiations need to know about all certificates.
1280 certificate = configuration.certificates[0];
1281 }
1282
1283 if (options.disable_encryption) {
1284 dtls_enabled_ = false;
1285 } else {
1286 // Enable DTLS by default if we have an identity store or a certificate.
1287 dtls_enabled_ = (dependencies.cert_generator || certificate);
1288 // |configuration| can override the default |dtls_enabled_| value.
1289 if (configuration.enable_dtls_srtp) {
1290 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1291 }
1292 }
1293
1294 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
1295
1296 if (use_datagram_transport_for_data_channels_) {
1297 if (configuration.enable_rtp_data_channel) {
1298 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1299 "use_datagram_transport_for_data_channels are "
1300 "incompatible and cannot both be set to true";
1301 return false;
1302 }
1303 if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
1304 RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
Harald Alvestrand05e4d082019-12-03 14:04:21 +01001305 data_channel_controller_.set_data_channel_type(
1306 cricket::DCT_DATA_CHANNEL_TRANSPORT);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001307 } else {
1308 RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
Harald Alvestrand05e4d082019-12-03 14:04:21 +01001309 data_channel_controller_.set_data_channel_type(
1310 cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001311 config.sctp_factory = sctp_factory_.get();
1312 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001313 } else if (configuration.enable_rtp_data_channel) {
1314 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1315 // set. It takes precendence over the disable_sctp_data_channels
1316 // PeerConnectionFactoryInterface::Options.
Harald Alvestrand05e4d082019-12-03 14:04:21 +01001317 data_channel_controller_.set_data_channel_type(cricket::DCT_RTP);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001318 } else {
1319 // DTLS has to be enabled to use SCTP.
1320 if (!options.disable_sctp_data_channels && dtls_enabled_) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01001321 data_channel_controller_.set_data_channel_type(cricket::DCT_SCTP);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07001322 config.sctp_factory = sctp_factory_.get();
1323 }
1324 }
1325
Qingsi Wang25ec8882019-11-15 12:33:05 -08001326 config.ice_transport_factory = ice_transport_factory_.get();
1327
Zhi Huange830e682018-03-30 10:48:35 -07001328 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001329 signaling_thread(), network_thread(), port_allocator_.get(),
1330 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001331 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001332 this, &PeerConnection::OnTransportControllerConnectionState);
1333 transport_controller_->SignalStandardizedIceConnectionState.connect(
1334 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001335 transport_controller_->SignalConnectionState.connect(
1336 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001337 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001338 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001339 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001340 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001341 transport_controller_->SignalIceCandidateError.connect(
1342 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001343 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001344 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1345 transport_controller_->SignalDtlsHandshakeError.connect(
1346 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001347 transport_controller_->SignalIceCandidatePairChanged.connect(
1348 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001349
deadbeefab9b2d12015-10-14 11:33:11 -07001350 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001351 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352
Steve Antonba818672017-11-06 10:21:57 -08001353 configuration_ = configuration;
1354
Steve Antond25da372017-11-06 14:50:29 -08001355 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001356
Steve Anton75737c02017-11-06 10:37:17 -08001357 video_options_.screencast_min_bitrate_kbps =
1358 configuration.screencast_min_bitrate;
1359 audio_options_.combined_audio_video_bwe =
1360 configuration.combined_audio_video_bwe;
1361
1362 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001363 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001364
1365 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001366 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001367
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001368 audio_options_.audio_jitter_buffer_min_delay_ms =
1369 configuration.audio_jitter_buffer_min_delay_ms;
1370
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001371 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1372 configuration.audio_jitter_buffer_enable_rtx_handling;
1373
Steve Anton75737c02017-11-06 10:37:17 -08001374 // Whether the certificate generator/certificate is null or not determines
1375 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1376 // the right instructions by clearing the variables if needed.
1377 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001378 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001379 certificate = nullptr;
1380 } else if (certificate) {
1381 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001382 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001383 }
1384
1385 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1386 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001387 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001388 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1389 this, &PeerConnection::OnCertificateReady);
1390
1391 if (options.disable_encryption) {
1392 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1393 }
1394
1395 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001396 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001397 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398
Steve Anton4171afb2017-11-20 10:20:22 -08001399 // Add default audio/video transceivers for Plan B SDP.
1400 if (!IsUnifiedPlan()) {
1401 transceivers_.push_back(
1402 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1403 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1404 transceivers_.push_back(
1405 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1406 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1407 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001408 int delay_ms =
1409 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001410 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1411 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001412
1413 if (dependencies.video_bitrate_allocator_factory) {
1414 video_bitrate_allocator_factory_ =
1415 std::move(dependencies.video_bitrate_allocator_factory);
1416 } else {
1417 video_bitrate_allocator_factory_ =
1418 CreateBuiltinVideoBitrateAllocatorFactory();
1419 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001420 return true;
1421}
1422
Steve Anton038834f2017-07-14 15:59:59 -07001423RTCError PeerConnection::ValidateConfiguration(
1424 const RTCConfiguration& config) const {
Steve Antonf4172382020-01-27 15:45:02 -08001425 return cricket::P2PTransportChannel::ValidateIceConfig(
1426 ParseIceConfig(config));
Steve Anton038834f2017-07-14 15:59:59 -07001427}
1428
Yves Gerey665174f2018-06-19 15:03:05 +02001429rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001430 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001431 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1432 "Plan SdpSemantics. Please use GetSenders "
1433 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001434 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435}
1436
Yves Gerey665174f2018-06-19 15:03:05 +02001437rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001438 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001439 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1440 "Plan SdpSemantics. Please use GetReceivers "
1441 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001442 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443}
1444
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001445bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001446 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001447 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1448 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001449 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 if (IsClosed()) {
1451 return false;
1452 }
deadbeefab9b2d12015-10-14 11:33:11 -07001453 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454 return false;
1455 }
deadbeefab9b2d12015-10-14 11:33:11 -07001456
1457 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001458 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1459 observer->SignalAudioTrackAdded.connect(this,
1460 &PeerConnection::OnAudioTrackAdded);
1461 observer->SignalAudioTrackRemoved.connect(
1462 this, &PeerConnection::OnAudioTrackRemoved);
1463 observer->SignalVideoTrackAdded.connect(this,
1464 &PeerConnection::OnVideoTrackAdded);
1465 observer->SignalVideoTrackRemoved.connect(
1466 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001467 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001468
deadbeefab9b2d12015-10-14 11:33:11 -07001469 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001470 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001471 }
1472 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001473 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001474 }
1475
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001476 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001477 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 return true;
1479}
1480
1481void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001482 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001483 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1484 "Plan SdpSemantics. Please use RemoveTrack "
1485 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001486 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001487 if (!IsClosed()) {
1488 for (const auto& track : local_stream->GetAudioTracks()) {
1489 RemoveAudioTrack(track.get(), local_stream);
1490 }
1491 for (const auto& track : local_stream->GetVideoTracks()) {
1492 RemoveVideoTrack(track.get(), local_stream);
1493 }
deadbeefab9b2d12015-10-14 11:33:11 -07001494 }
deadbeefab9b2d12015-10-14 11:33:11 -07001495 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001496 stream_observers_.erase(
1497 std::remove_if(
1498 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001499 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001500 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001501 }),
1502 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001503
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001504 if (IsClosed()) {
1505 return;
1506 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001507 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001508}
1509
Steve Anton2d6c76a2018-01-05 17:10:52 -08001510RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001511 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001512 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001513 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001514 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001515 if (!track) {
1516 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1517 }
1518 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1519 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1520 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1521 "Track has invalid kind: " + track->kind());
1522 }
Steve Antonf9381f02017-12-14 10:23:57 -08001523 if (IsClosed()) {
1524 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1525 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001526 }
Steve Anton4171afb2017-11-20 10:20:22 -08001527 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001528 LOG_AND_RETURN_ERROR(
1529 RTCErrorType::INVALID_PARAMETER,
1530 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001531 }
Steve Antonf9381f02017-12-14 10:23:57 -08001532 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001533 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1534 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001535 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001536 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001537 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001538 }
1539 return sender_or_error;
1540}
deadbeefe1f9d832016-01-14 15:35:42 -08001541
Steve Antonf9381f02017-12-14 10:23:57 -08001542RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1543PeerConnection::AddTrackPlanB(
1544 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001545 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001546 if (stream_ids.size() > 1u) {
1547 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1548 "AddTrack with more than one stream is not "
1549 "supported with Plan B semantics.");
1550 }
1551 std::vector<std::string> adjusted_stream_ids = stream_ids;
1552 if (adjusted_stream_ids.empty()) {
1553 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1554 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001555 cricket::MediaType media_type =
1556 (track->kind() == MediaStreamTrackInterface::kAudioKind
1557 ? cricket::MEDIA_TYPE_AUDIO
1558 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001559 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001560 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001561 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001562 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001563 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001564 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001565 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001566 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001567 if (sender_info) {
1568 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001569 }
Steve Antonf9381f02017-12-14 10:23:57 -08001570 } else {
1571 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001572 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001573 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001574 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001575 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001576 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001577 if (sender_info) {
1578 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001579 }
deadbeefe1f9d832016-01-14 15:35:42 -08001580 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001581 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001582}
deadbeefe1f9d832016-01-14 15:35:42 -08001583
Steve Antonf9381f02017-12-14 10:23:57 -08001584RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1585PeerConnection::AddTrackUnifiedPlan(
1586 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001587 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001588 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1589 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001590 RTC_LOG(LS_INFO) << "Reusing an existing "
1591 << cricket::MediaTypeToString(transceiver->media_type())
1592 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001593 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001594 transceiver->internal()->set_direction(
1595 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001596 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001597 transceiver->internal()->set_direction(
1598 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001599 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001600 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001601 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Eldar Rello353a7182019-11-25 18:49:44 +02001602 transceiver->internal()->set_reused_for_addtrack(true);
Steve Antonf9381f02017-12-14 10:23:57 -08001603 } else {
1604 cricket::MediaType media_type =
1605 (track->kind() == MediaStreamTrackInterface::kAudioKind
1606 ? cricket::MEDIA_TYPE_AUDIO
1607 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001608 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1609 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001610 std::string sender_id = track->id();
1611 // Avoid creating a sender with an existing ID by generating a random ID.
1612 // This can happen if this is the second time AddTrack has created a sender
1613 // for this track.
1614 if (FindSenderById(sender_id)) {
1615 sender_id = rtc::CreateRandomUuid();
1616 }
Florent Castelli892acf02018-10-01 22:47:20 +02001617 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001618 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1619 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001620 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001621 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001622 }
Steve Antonf9381f02017-12-14 10:23:57 -08001623 return transceiver->sender();
1624}
1625
1626rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1627PeerConnection::FindFirstTransceiverForAddedTrack(
1628 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1629 RTC_DCHECK(track);
1630 for (auto transceiver : transceivers_) {
1631 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001632 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001633 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001634 !transceiver->internal()->has_ever_been_used_to_send() &&
1635 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001636 return transceiver;
1637 }
1638 }
1639 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001640}
1641
1642bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1643 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001644 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001645}
1646
Steve Anton24db5732018-07-23 10:27:33 -07001647RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001648 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001649 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001650 if (!sender) {
1651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1652 }
deadbeefe1f9d832016-01-14 15:35:42 -08001653 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001654 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1655 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001656 }
Steve Antonf9381f02017-12-14 10:23:57 -08001657 if (IsUnifiedPlan()) {
1658 auto transceiver = FindTransceiverBySender(sender);
1659 if (!transceiver || !sender->track()) {
1660 return RTCError::OK();
1661 }
1662 sender->SetTrack(nullptr);
1663 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001664 transceiver->internal()->set_direction(
1665 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001666 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001667 transceiver->internal()->set_direction(
1668 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001669 }
Steve Anton4171afb2017-11-20 10:20:22 -08001670 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001671 bool removed;
1672 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1673 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1674 } else {
1675 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1676 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1677 }
1678 if (!removed) {
1679 LOG_AND_RETURN_ERROR(
1680 RTCErrorType::INVALID_PARAMETER,
1681 "Couldn't find sender " + sender->id() + " to remove.");
1682 }
Steve Anton4171afb2017-11-20 10:20:22 -08001683 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001684 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001685 return RTCError::OK();
1686}
1687
1688rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1689PeerConnection::FindTransceiverBySender(
1690 rtc::scoped_refptr<RtpSenderInterface> sender) {
1691 for (auto transceiver : transceivers_) {
1692 if (transceiver->sender() == sender) {
1693 return transceiver;
1694 }
1695 }
1696 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001697}
1698
Steve Anton9158ef62017-11-27 13:01:52 -08001699RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1700PeerConnection::AddTransceiver(
1701 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1702 return AddTransceiver(track, RtpTransceiverInit());
1703}
1704
1705RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1706PeerConnection::AddTransceiver(
1707 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1708 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001709 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001710 RTC_CHECK(IsUnifiedPlan())
1711 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001712 if (!track) {
1713 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1714 }
1715 cricket::MediaType media_type;
1716 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1717 media_type = cricket::MEDIA_TYPE_AUDIO;
1718 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1719 media_type = cricket::MEDIA_TYPE_VIDEO;
1720 } else {
1721 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1722 "Track kind is not audio or video");
1723 }
1724 return AddTransceiver(media_type, track, init);
1725}
1726
1727RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1728PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1729 return AddTransceiver(media_type, RtpTransceiverInit());
1730}
1731
1732RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1733PeerConnection::AddTransceiver(cricket::MediaType media_type,
1734 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001735 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001736 RTC_CHECK(IsUnifiedPlan())
1737 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001738 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1739 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1741 "media type is not audio or video");
1742 }
1743 return AddTransceiver(media_type, nullptr, init);
1744}
1745
1746RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1747PeerConnection::AddTransceiver(
1748 cricket::MediaType media_type,
1749 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001750 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001751 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001752 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1753 media_type == cricket::MEDIA_TYPE_VIDEO));
1754 if (track) {
1755 RTC_DCHECK_EQ(media_type,
1756 (track->kind() == MediaStreamTrackInterface::kAudioKind
1757 ? cricket::MEDIA_TYPE_AUDIO
1758 : cricket::MEDIA_TYPE_VIDEO));
1759 }
1760
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001761 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1762 init.send_encodings.size(), 0, 7, 8);
1763
Amit Hilbuchaa584152019-02-06 17:09:52 -08001764 size_t num_rids = absl::c_count_if(init.send_encodings,
1765 [](const RtpEncodingParameters& encoding) {
1766 return !encoding.rid.empty();
1767 });
1768 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001769 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001770 RTCErrorType::INVALID_PARAMETER,
1771 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001772 }
1773
Amit Hilbuchf4770402019-04-08 14:11:57 -07001774 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1775 [](const RtpEncodingParameters& encoding) {
1776 return !IsLegalRsidName(encoding.rid);
1777 })) {
1778 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1779 "Invalid RID value provided.");
1780 }
1781
Amit Hilbuchaa584152019-02-06 17:09:52 -08001782 if (absl::c_any_of(init.send_encodings,
1783 [](const RtpEncodingParameters& encoding) {
1784 return encoding.ssrc.has_value();
1785 })) {
1786 LOG_AND_RETURN_ERROR(
1787 RTCErrorType::UNSUPPORTED_PARAMETER,
1788 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001789 }
1790
1791 RtpParameters parameters;
1792 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001793
1794 // Encodings are dropped from the tail if too many are provided.
1795 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1796 parameters.encodings.erase(
1797 parameters.encodings.begin() + kMaxSimulcastStreams,
1798 parameters.encodings.end());
1799 }
1800
1801 // Single RID should be removed.
1802 if (parameters.encodings.size() == 1 &&
1803 !parameters.encodings[0].rid.empty()) {
1804 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1805 parameters.encodings[0].rid.clear();
1806 }
1807
1808 // If RIDs were not provided, they are generated for simulcast scenario.
1809 if (parameters.encodings.size() > 1 && num_rids == 0) {
1810 rtc::UniqueStringGenerator rid_generator;
1811 for (RtpEncodingParameters& encoding : parameters.encodings) {
1812 encoding.rid = rid_generator();
1813 }
1814 }
1815
Florent Castelli892acf02018-10-01 22:47:20 +02001816 if (UnimplementedRtpParameterHasValue(parameters)) {
1817 LOG_AND_RETURN_ERROR(
1818 RTCErrorType::UNSUPPORTED_PARAMETER,
1819 "Attempted to set an unimplemented parameter of RtpParameters.");
1820 }
Steve Anton9158ef62017-11-27 13:01:52 -08001821
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001822 auto result = cricket::CheckRtpParametersValues(parameters);
1823 if (!result.ok()) {
1824 LOG_AND_RETURN_ERROR(result.type(), result.message());
1825 }
1826
Steve Anton3d954a62018-04-02 11:27:23 -07001827 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1828 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001829 // Set the sender ID equal to the track ID if the track is specified unless
1830 // that sender ID is already in use.
1831 std::string sender_id =
1832 (track && !FindSenderById(track->id()) ? track->id()
1833 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001834 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001835 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001836 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1837 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1838 transceiver->internal()->set_direction(init.direction);
1839
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001840 if (update_negotiation_needed) {
1841 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001842 }
Steve Antonf9381f02017-12-14 10:23:57 -08001843
1844 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1845}
1846
Steve Anton02ee47c2018-01-10 16:26:06 -08001847rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1848PeerConnection::CreateSender(
1849 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001850 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001851 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001852 const std::vector<std::string>& stream_ids,
1853 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001854 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001855 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001856 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1857 RTC_DCHECK(!track ||
1858 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1859 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1860 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001861 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001862 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001863 } else {
1864 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1865 RTC_DCHECK(!track ||
1866 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1867 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001868 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001869 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001870 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001871 bool set_track_succeeded = sender->SetTrack(track);
1872 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001873 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001874 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001875 return sender;
1876}
1877
1878rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1879PeerConnection::CreateReceiver(cricket::MediaType media_type,
1880 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001881 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1882 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001883 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001884 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001885 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1886 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001887 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001888 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001889 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001890 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001891 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1892 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001893 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001894 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001895 return receiver;
1896}
1897
1898rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1899PeerConnection::CreateAndAddTransceiver(
1900 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1901 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1902 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001903 // Ensure that the new sender does not have an ID that is already in use by
1904 // another sender.
1905 // Allow receiver IDs to conflict since those come from remote SDP (which
1906 // could be invalid, but should not cause a crash).
1907 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001908 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001909 signaling_thread(),
Markus Handell0357b3e2020-03-16 13:40:51 +01001910 new RtpTransceiver(
1911 sender, receiver, channel_manager(),
1912 sender->media_type() == cricket::MEDIA_TYPE_AUDIO
1913 ? channel_manager()->GetSupportedAudioRtpHeaderExtensions()
1914 : channel_manager()->GetSupportedVideoRtpHeaderExtensions()));
Steve Anton9158ef62017-11-27 13:01:52 -08001915 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001916 transceiver->internal()->SignalNegotiationNeeded.connect(
1917 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001918 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001919}
1920
Steve Anton52d86772018-02-20 15:48:12 -08001921void PeerConnection::OnNegotiationNeeded() {
1922 RTC_DCHECK_RUN_ON(signaling_thread());
1923 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001924 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001925}
1926
deadbeeffac06552015-11-25 11:26:01 -08001927rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001928 const std::string& kind,
1929 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001930 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001931 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1932 "Plan SdpSemantics. Please use AddTransceiver "
1933 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001934 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001935 if (IsClosed()) {
1936 return nullptr;
1937 }
Steve Anton4171afb2017-11-20 10:20:22 -08001938
Seth Hampson5b4f0752018-04-02 16:31:36 -07001939 // Internally we need to have one stream with Plan B semantics, so we
1940 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001941 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001942 if (stream_id.empty()) {
1943 stream_ids.push_back(rtc::CreateRandomUuid());
1944 RTC_LOG(LS_INFO)
1945 << "No stream_id specified for sender. Generated stream ID: "
1946 << stream_ids[0];
1947 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001948 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001949 }
1950
Steve Anton4171afb2017-11-20 10:20:22 -08001951 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001952 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001953 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001954 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001955 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001956 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001957 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001958 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001959 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001960 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001961 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001962 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001963 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001964 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001965 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001966 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001967 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001968 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001969 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001970 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001971 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001972
deadbeefe1f9d832016-01-14 15:35:42 -08001973 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001974}
1975
deadbeef70ab1a12015-09-28 16:53:55 -07001976std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1977 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001978 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001979 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001980 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001981 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001982 }
1983 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001984}
1985
Steve Anton4171afb2017-11-20 10:20:22 -08001986std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1987PeerConnection::GetSendersInternal() const {
1988 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1989 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001990 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001991 auto senders = transceiver->internal()->senders();
1992 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1993 }
1994 return all_senders;
1995}
1996
deadbeef70ab1a12015-09-28 16:53:55 -07001997std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1998PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001999 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07002000 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08002001 for (const auto& receiver : GetReceiversInternal()) {
2002 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07002003 }
2004 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07002005}
2006
Steve Anton4171afb2017-11-20 10:20:22 -08002007std::vector<
2008 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2009PeerConnection::GetReceiversInternal() const {
2010 std::vector<
2011 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
2012 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002013 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08002014 auto receivers = transceiver->internal()->receivers();
2015 all_receivers.insert(all_receivers.end(), receivers.begin(),
2016 receivers.end());
2017 }
2018 return all_receivers;
2019}
2020
Steve Anton9158ef62017-11-27 13:01:52 -08002021std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2022PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01002023 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08002024 RTC_CHECK(IsUnifiedPlan())
2025 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08002026 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002027 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08002028 all_transceivers.push_back(transceiver);
2029 }
2030 return all_transceivers;
2031}
2032
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002034 MediaStreamTrackInterface* track,
2035 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002036 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002037 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08002038 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002039 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040 return false;
2041 }
2042
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002043 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07002044 // The StatsCollector is used to tell if a track is valid because it may
2045 // remember tracks that the PeerConnection previously removed.
2046 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002047 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
2048 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07002049 return false;
2050 }
Steve Antonad182762018-09-05 20:22:40 +00002051 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
2052 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002053 return true;
2054}
2055
hbos74e1a4f2016-09-15 23:33:01 -07002056void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01002057 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002058 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07002059 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01002060 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07002061 stats_collector_->GetStatsReport(callback);
2062}
2063
Henrik Boström1df1bf82018-03-20 13:24:20 +01002064void PeerConnection::GetStats(
2065 rtc::scoped_refptr<RtpSenderInterface> selector,
2066 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2067 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002068 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002069 RTC_DCHECK(callback);
2070 RTC_DCHECK(stats_collector_);
2071 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
2072 if (selector) {
2073 for (const auto& proxy_transceiver : transceivers_) {
2074 for (const auto& proxy_sender :
2075 proxy_transceiver->internal()->senders()) {
2076 if (proxy_sender == selector) {
2077 internal_sender = proxy_sender->internal();
2078 break;
2079 }
2080 }
2081 if (internal_sender)
2082 break;
2083 }
2084 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002085 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01002086 // belong to the PeerConnection (in Plan B, senders can be removed from the
2087 // PeerConnection). This means that "all the stats objects representing the
2088 // selector" is an empty set. Invoking GetStatsReport() with a null selector
2089 // produces an empty stats report.
2090 stats_collector_->GetStatsReport(internal_sender, callback);
2091}
2092
2093void PeerConnection::GetStats(
2094 rtc::scoped_refptr<RtpReceiverInterface> selector,
2095 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
2096 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01002097 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01002098 RTC_DCHECK(callback);
2099 RTC_DCHECK(stats_collector_);
2100 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
2101 if (selector) {
2102 for (const auto& proxy_transceiver : transceivers_) {
2103 for (const auto& proxy_receiver :
2104 proxy_transceiver->internal()->receivers()) {
2105 if (proxy_receiver == selector) {
2106 internal_receiver = proxy_receiver->internal();
2107 break;
2108 }
2109 }
2110 if (internal_receiver)
2111 break;
2112 }
2113 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01002114 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01002115 // not belong to the PeerConnection (in Plan B, receivers can be removed from
2116 // the PeerConnection). This means that "all the stats objects representing
2117 // the selector" is an empty set. Invoking GetStatsReport() with a null
2118 // selector produces an empty stats report.
2119 stats_collector_->GetStatsReport(internal_receiver, callback);
2120}
2121
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002123 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002124 return signaling_state_;
2125}
2126
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002127PeerConnectionInterface::IceConnectionState
2128PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002129 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 return ice_connection_state_;
2131}
2132
Alex Loiko9289eda2018-11-23 16:18:59 +00002133PeerConnectionInterface::IceConnectionState
2134PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002135 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00002136 return standardized_ice_connection_state_;
2137}
2138
Jonas Olsson635474e2018-10-18 15:58:17 +02002139PeerConnectionInterface::PeerConnectionState
2140PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002141 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02002142 return connection_state_;
2143}
2144
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145PeerConnectionInterface::IceGatheringState
2146PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002147 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148 return ice_gathering_state_;
2149}
2150
Harald Alvestrand61f74d92020-03-02 11:20:00 +01002151absl::optional<bool> PeerConnection::can_trickle_ice_candidates() {
2152 RTC_DCHECK_RUN_ON(signaling_thread());
2153 SessionDescriptionInterface* description = current_remote_description_.get();
2154 if (!description) {
2155 description = pending_remote_description_.get();
2156 }
2157 if (!description) {
2158 return absl::nullopt;
2159 }
2160 // TODO(bugs.webrtc.org/7443): Change to retrieve from session-level option.
2161 if (description->description()->transport_infos().size() < 1) {
2162 return absl::nullopt;
2163 }
2164 return description->description()->transport_infos()[0].description.HasOption(
2165 "trickle");
2166}
2167
Yves Gerey665174f2018-06-19 15:03:05 +02002168rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169 const std::string& label,
2170 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01002171 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002172 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07002173
Harald Alvestrand05e4d082019-12-03 14:04:21 +01002174 bool first_datachannel = !data_channel_controller_.HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002175
kwibergd1fe2812016-04-27 06:47:29 -07002176 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002177 if (config) {
2178 internal_config.reset(new InternalDataChannelInit(*config));
2179 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002180 rtc::scoped_refptr<DataChannelInterface> channel(
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01002181 data_channel_controller_.InternalCreateDataChannel(
2182 label, internal_config.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07002183 if (!channel.get()) {
2184 return nullptr;
2185 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002186
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002187 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2188 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002189 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002190 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002191 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002192 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193 return DataChannelProxy::Create(signaling_thread(), channel.get());
2194}
2195
Henrik Boström79b69802019-07-18 11:16:56 +02002196void PeerConnection::RestartIce() {
2197 RTC_DCHECK_RUN_ON(signaling_thread());
2198 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2199 current_local_description_.get(), pending_local_description_.get());
2200 UpdateNegotiationNeeded();
2201}
2202
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002204 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002205 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002206 // Chain this operation. If asynchronous operations are pending on the chain,
2207 // this operation will be queued to be invoked, otherwise the contents of the
2208 // lambda will execute immediately.
2209 operations_chain_->ChainOperation(
2210 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2211 observer_refptr =
2212 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2213 options](std::function<void()> operations_chain_callback) {
2214 // Abort early if |this_weak_ptr| is no longer valid.
2215 if (!this_weak_ptr) {
2216 observer_refptr->OnFailure(
2217 RTCError(RTCErrorType::INTERNAL_ERROR,
2218 "CreateOffer failed because the session was shut down"));
2219 operations_chain_callback();
2220 return;
2221 }
2222 // The operation completes asynchronously when the wrapper is invoked.
2223 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2224 observer_wrapper(new rtc::RefCountedObject<
2225 CreateSessionDescriptionObserverOperationWrapper>(
2226 std::move(observer_refptr),
2227 std::move(operations_chain_callback)));
2228 this_weak_ptr->DoCreateOffer(options, observer_wrapper);
2229 });
2230}
2231
2232void PeerConnection::DoCreateOffer(
2233 const RTCOfferAnswerOptions& options,
2234 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2235 RTC_DCHECK_RUN_ON(signaling_thread());
2236 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002237
nisse7ce109a2017-01-31 00:57:56 -08002238 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002239 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002240 return;
2241 }
deadbeefab9b2d12015-10-14 11:33:11 -07002242
Steve Anton8d3444d2017-10-20 15:30:51 -07002243 if (IsClosed()) {
2244 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002245 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002246 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002247 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002248 return;
2249 }
2250
Steve Anton25ca0ac2019-06-25 10:40:48 -07002251 // If a session error has occurred the PeerConnection is in a possibly
2252 // inconsistent state so fail right away.
2253 if (session_error() != SessionError::kNone) {
2254 std::string error_message = GetSessionErrorMsg();
2255 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2256 PostCreateSessionDescriptionFailure(
2257 observer,
2258 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2259 return;
2260 }
2261
zhihuang1c378ed2017-08-17 14:10:50 -07002262 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002263 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002264 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002265 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002266 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002267 return;
2268 }
2269
Steve Anton22da89f2018-01-25 13:58:07 -08002270 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2271 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2272 if (IsUnifiedPlan()) {
2273 RTCError error = HandleLegacyOfferOptions(options);
2274 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002275 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002276 return;
2277 }
2278 }
2279
zhihuang1c378ed2017-08-17 14:10:50 -07002280 cricket::MediaSessionOptions session_options;
2281 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002282 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002283}
2284
Steve Anton22da89f2018-01-25 13:58:07 -08002285RTCError PeerConnection::HandleLegacyOfferOptions(
2286 const RTCOfferAnswerOptions& options) {
2287 RTC_DCHECK(IsUnifiedPlan());
2288
2289 if (options.offer_to_receive_audio == 0) {
2290 RemoveRecvDirectionFromReceivingTransceiversOfType(
2291 cricket::MEDIA_TYPE_AUDIO);
2292 } else if (options.offer_to_receive_audio == 1) {
2293 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2294 } else if (options.offer_to_receive_audio > 1) {
2295 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2296 "offer_to_receive_audio > 1 is not supported.");
2297 }
2298
2299 if (options.offer_to_receive_video == 0) {
2300 RemoveRecvDirectionFromReceivingTransceiversOfType(
2301 cricket::MEDIA_TYPE_VIDEO);
2302 } else if (options.offer_to_receive_video == 1) {
2303 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2304 } else if (options.offer_to_receive_video > 1) {
2305 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2306 "offer_to_receive_video > 1 is not supported.");
2307 }
2308
2309 return RTCError::OK();
2310}
2311
2312void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2313 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002314 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002315 RtpTransceiverDirection new_direction =
2316 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2317 if (new_direction != transceiver->direction()) {
2318 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2319 << " transceiver (MID="
2320 << transceiver->mid().value_or("<not set>") << ") from "
2321 << RtpTransceiverDirectionToString(
2322 transceiver->direction())
2323 << " to "
2324 << RtpTransceiverDirectionToString(new_direction)
2325 << " since CreateOffer specified offer_to_receive=0";
2326 transceiver->internal()->set_direction(new_direction);
2327 }
Steve Anton22da89f2018-01-25 13:58:07 -08002328 }
2329}
2330
2331void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2332 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002333 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002334 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002335 RTC_LOG(LS_INFO)
2336 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2337 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002338 RtpTransceiverInit init;
2339 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002340 AddTransceiver(media_type, nullptr, init,
2341 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002342 }
2343}
2344
2345std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2346PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2347 std::vector<
2348 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2349 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002350 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002351 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002352 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2353 receiving_transceivers.push_back(transceiver);
2354 }
2355 }
2356 return receiving_transceivers;
2357}
2358
htaa2a49d92016-03-04 02:51:39 -08002359void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2360 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002361 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002362 // Chain this operation. If asynchronous operations are pending on the chain,
2363 // this operation will be queued to be invoked, otherwise the contents of the
2364 // lambda will execute immediately.
2365 operations_chain_->ChainOperation(
2366 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2367 observer_refptr =
2368 rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer),
2369 options](std::function<void()> operations_chain_callback) {
2370 // Abort early if |this_weak_ptr| is no longer valid.
2371 if (!this_weak_ptr) {
2372 observer_refptr->OnFailure(RTCError(
2373 RTCErrorType::INTERNAL_ERROR,
2374 "CreateAnswer failed because the session was shut down"));
2375 operations_chain_callback();
2376 return;
2377 }
2378 // The operation completes asynchronously when the wrapper is invoked.
2379 rtc::scoped_refptr<CreateSessionDescriptionObserverOperationWrapper>
2380 observer_wrapper(new rtc::RefCountedObject<
2381 CreateSessionDescriptionObserverOperationWrapper>(
2382 std::move(observer_refptr),
2383 std::move(operations_chain_callback)));
2384 this_weak_ptr->DoCreateAnswer(options, observer_wrapper);
2385 });
2386}
2387
2388void PeerConnection::DoCreateAnswer(
2389 const RTCOfferAnswerOptions& options,
2390 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) {
2391 RTC_DCHECK_RUN_ON(signaling_thread());
2392 TRACE_EVENT0("webrtc", "PeerConnection::DoCreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002393 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002394 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002395 return;
2396 }
2397
Steve Anton25ca0ac2019-06-25 10:40:48 -07002398 // If a session error has occurred the PeerConnection is in a possibly
2399 // inconsistent state so fail right away.
2400 if (session_error() != SessionError::kNone) {
2401 std::string error_message = GetSessionErrorMsg();
2402 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2403 PostCreateSessionDescriptionFailure(
2404 observer,
2405 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2406 return;
2407 }
2408
Steve Antondffead82018-02-06 10:31:29 -08002409 if (!(signaling_state_ == kHaveRemoteOffer ||
2410 signaling_state_ == kHaveLocalPrAnswer)) {
2411 std::string error =
2412 "PeerConnection cannot create an answer in a state other than "
2413 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002414 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002415 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002416 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002417 return;
2418 }
2419
Steve Antondffead82018-02-06 10:31:29 -08002420 // The remote description should be set if we're in the right state.
2421 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002422
Steve Anton22da89f2018-01-25 13:58:07 -08002423 if (IsUnifiedPlan()) {
2424 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2425 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2426 "supported with Unified Plan semantics. Use the "
2427 "RtpTransceiver API instead.";
2428 }
2429 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2430 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2431 "supported with Unified Plan semantics. Use the "
2432 "RtpTransceiver API instead.";
2433 }
2434 }
2435
htaa2a49d92016-03-04 02:51:39 -08002436 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002437 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002438
Steve Antond25da372017-11-06 14:50:29 -08002439 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440}
2441
2442void PeerConnection::SetLocalDescription(
2443 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002444 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002445 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002446 // Chain this operation. If asynchronous operations are pending on the chain,
2447 // this operation will be queued to be invoked, otherwise the contents of the
2448 // lambda will execute immediately.
2449 operations_chain_->ChainOperation(
2450 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2451 observer_refptr =
2452 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2453 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2454 std::function<void()> operations_chain_callback) mutable {
2455 // Abort early if |this_weak_ptr| is no longer valid.
2456 if (!this_weak_ptr) {
2457 // For consistency with DoSetLocalDescription(), we DO NOT inform the
2458 // |observer_refptr| that the operation failed in this case.
2459 // TODO(hbos): If/when we process SLD messages in ~PeerConnection,
2460 // the consistent thing would be to inform the observer here.
2461 operations_chain_callback();
2462 return;
2463 }
2464 this_weak_ptr->DoSetLocalDescription(std::move(desc),
2465 std::move(observer_refptr));
2466 // DoSetLocalDescription() is currently implemented as a synchronous
2467 // operation but where the |observer|'s callbacks are invoked
2468 // asynchronously in a post to OnMessage().
2469 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 10:35:50 +01002470 // completed here (rather than in OnMessage()). This ensures that
2471 // subsequent offer/answer operations can start immediately (without
2472 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 12:09:49 +01002473 operations_chain_callback();
2474 });
2475}
Steve Anton8a006912017-12-04 15:25:56 -08002476
Henrik Boström4e196702019-10-30 10:35:50 +01002477void PeerConnection::SetLocalDescription(
2478 SetSessionDescriptionObserver* observer) {
2479 RTC_DCHECK_RUN_ON(signaling_thread());
2480 // The |create_sdp_observer| handles performing DoSetLocalDescription() with
2481 // the resulting description as well as completing the operation.
2482 rtc::scoped_refptr<ImplicitCreateSessionDescriptionObserver>
2483 create_sdp_observer(
2484 new rtc::RefCountedObject<ImplicitCreateSessionDescriptionObserver>(
2485 weak_ptr_factory_.GetWeakPtr(),
2486 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer)));
2487 // Chain this operation. If asynchronous operations are pending on the chain,
2488 // this operation will be queued to be invoked, otherwise the contents of the
2489 // lambda will execute immediately.
2490 operations_chain_->ChainOperation(
2491 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2492 create_sdp_observer](std::function<void()> operations_chain_callback) {
2493 // The |create_sdp_observer| is responsible for completing the
2494 // operation.
2495 create_sdp_observer->SetOperationCompleteCallback(
2496 std::move(operations_chain_callback));
2497 // Abort early if |this_weak_ptr| is no longer valid. This triggers the
2498 // same code path as if DoCreateOffer() or DoCreateAnswer() failed.
2499 if (!this_weak_ptr) {
2500 create_sdp_observer->OnFailure(RTCError(
2501 RTCErrorType::INTERNAL_ERROR,
2502 "SetLocalDescription failed because the session was shut down"));
2503 return;
2504 }
2505 switch (this_weak_ptr->signaling_state()) {
2506 case PeerConnectionInterface::kStable:
2507 case PeerConnectionInterface::kHaveLocalOffer:
2508 case PeerConnectionInterface::kHaveRemotePrAnswer:
2509 // TODO(hbos): If [LastCreatedOffer] exists and still represents the
2510 // current state of the system, use that instead of creating another
2511 // offer.
2512 this_weak_ptr->DoCreateOffer(RTCOfferAnswerOptions(),
2513 create_sdp_observer);
2514 break;
2515 case PeerConnectionInterface::kHaveLocalPrAnswer:
2516 case PeerConnectionInterface::kHaveRemoteOffer:
2517 // TODO(hbos): If [LastCreatedAnswer] exists and still represents
2518 // the current state of the system, use that instead of creating
2519 // another answer.
2520 this_weak_ptr->DoCreateAnswer(RTCOfferAnswerOptions(),
2521 create_sdp_observer);
2522 break;
2523 case PeerConnectionInterface::kClosed:
2524 create_sdp_observer->OnFailure(RTCError(
2525 RTCErrorType::INVALID_STATE,
2526 "SetLocalDescription called when PeerConnection is closed."));
2527 break;
2528 }
2529 });
2530}
2531
Henrik Boströma3728d32019-10-28 12:09:49 +01002532void PeerConnection::DoSetLocalDescription(
2533 std::unique_ptr<SessionDescriptionInterface> desc,
2534 rtc::scoped_refptr<SetSessionDescriptionObserver> observer) {
2535 RTC_DCHECK_RUN_ON(signaling_thread());
2536 TRACE_EVENT0("webrtc", "PeerConnection::DoSetLocalDescription");
Steve Anton80dd7b52018-02-16 17:08:42 -08002537
nisse7ce109a2017-01-31 00:57:56 -08002538 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002539 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002540 return;
2541 }
Steve Anton8a006912017-12-04 15:25:56 -08002542
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002543 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002544 PostSetSessionDescriptionFailure(
2545 observer,
2546 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002547 return;
2548 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002549
Steve Anton80dd7b52018-02-16 17:08:42 -08002550 // If a session error has occurred the PeerConnection is in a possibly
2551 // inconsistent state so fail right away.
2552 if (session_error() != SessionError::kNone) {
2553 std::string error_message = GetSessionErrorMsg();
2554 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002555 PostSetSessionDescriptionFailure(
2556 observer,
2557 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002558 return;
2559 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002560
Eldar Rello5ab79e62019-10-09 18:29:44 +03002561 // For SLD we support only explicit rollback.
2562 if (desc->GetType() == SdpType::kRollback) {
2563 if (IsUnifiedPlan()) {
Eldar Relloead0ec92019-10-21 23:01:31 +03002564 RTCError error = Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03002565 if (error.ok()) {
2566 PostSetSessionDescriptionSuccess(observer);
2567 } else {
2568 PostSetSessionDescriptionFailure(observer, std::move(error));
2569 }
2570 } else {
2571 PostSetSessionDescriptionFailure(
2572 observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
2573 "Rollback not supported in Plan B"));
2574 }
2575 return;
2576 }
2577
Steve Anton80dd7b52018-02-16 17:08:42 -08002578 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2579 if (!error.ok()) {
2580 std::string error_message = GetSetDescriptionErrorMessage(
2581 cricket::CS_LOCAL, desc->GetType(), error);
2582 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002583 PostSetSessionDescriptionFailure(
2584 observer,
2585 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002586 return;
2587 }
2588
2589 // Grab the description type before moving ownership to ApplyLocalDescription,
2590 // which may destroy it before returning.
2591 const SdpType type = desc->GetType();
2592
2593 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002594 // |desc| may be destroyed at this point.
2595
2596 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002597 // If ApplyLocalDescription fails, the PeerConnection could be in an
2598 // inconsistent state, so act conservatively here and set the session error
2599 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2600 SetSessionError(SessionError::kContent, error.message());
2601 std::string error_message =
2602 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2603 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002604 PostSetSessionDescriptionFailure(
2605 observer,
2606 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002607 return;
2608 }
Steve Anton8a006912017-12-04 15:25:56 -08002609 RTC_DCHECK(local_description());
2610
2611 PostSetSessionDescriptionSuccess(observer);
2612
Steve Antonad182762018-09-05 20:22:40 +00002613 // MaybeStartGathering needs to be called after posting
2614 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2615 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002616 transport_controller_->MaybeStartGathering();
2617
Steve Antona3a92c22017-12-07 10:27:41 -08002618 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002619 // TODO(deadbeef): We already had to hop to the network thread for
2620 // MaybeStartGathering...
2621 network_thread()->Invoke<void>(
2622 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2623 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002624 // Make UMA notes about what was agreed to.
2625 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002626 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002627
2628 if (IsUnifiedPlan()) {
2629 bool was_negotiation_needed = is_negotiation_needed_;
2630 UpdateNegotiationNeeded();
2631 if (signaling_state() == kStable && was_negotiation_needed &&
2632 is_negotiation_needed_) {
2633 Observer()->OnRenegotiationNeeded();
2634 }
2635 }
2636
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002637 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002638}
2639
2640RTCError PeerConnection::ApplyLocalDescription(
2641 std::unique_ptr<SessionDescriptionInterface> desc) {
2642 RTC_DCHECK_RUN_ON(signaling_thread());
2643 RTC_DCHECK(desc);
2644
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645 // Update stats here so that we have the most recent stats for tracks and
2646 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002647 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002648
Steve Antondcc3c022017-12-22 16:02:54 -08002649 // Take a reference to the old local description since it's used below to
2650 // compare against the new local description. When setting the new local
2651 // description, grab ownership of the replaced session description in case it
2652 // is the same as |old_local_description|, to keep it alive for the duration
2653 // of the method.
2654 const SessionDescriptionInterface* old_local_description =
2655 local_description();
2656 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002657 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002658 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002659 replaced_local_description = pending_local_description_
2660 ? std::move(pending_local_description_)
2661 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002662 current_local_description_ = std::move(desc);
2663 pending_local_description_ = nullptr;
2664 current_remote_description_ = std::move(pending_remote_description_);
2665 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002666 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002667 pending_local_description_ = std::move(desc);
2668 }
2669 // The session description to apply now must be accessed by
2670 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002671 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002672
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002673 // Report statistics about any use of simulcast.
2674 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2675 *local_description()->description());
2676
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002677 if (!is_caller_) {
2678 if (remote_description()) {
2679 // Remote description was applied first, so this PC is the callee.
2680 is_caller_ = false;
2681 } else {
2682 // Local description is applied first, so this PC is the caller.
2683 is_caller_ = true;
2684 }
2685 }
2686
Zhi Huange830e682018-03-30 10:48:35 -07002687 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2688 if (!error.ok()) {
2689 return error;
2690 }
2691
Steve Antondcc3c022017-12-22 16:02:54 -08002692 if (IsUnifiedPlan()) {
2693 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002694 cricket::CS_LOCAL, *local_description(), old_local_description,
2695 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002696 if (!error.ok()) {
2697 return error;
2698 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002699 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2700 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002701 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002702 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2703 // Note that code paths that don't set MID won't be able to use
2704 // information about DTLS transports.
2705 if (transceiver->mid()) {
2706 auto dtls_transport =
2707 LookupDtlsTransportByMidInternal(*transceiver->mid());
2708 transceiver->internal()->sender_internal()->set_transport(
2709 dtls_transport);
2710 transceiver->internal()->receiver_internal()->set_transport(
2711 dtls_transport);
2712 }
2713
Steve Antondcc3c022017-12-22 16:02:54 -08002714 const ContentInfo* content =
2715 FindMediaSectionForTransceiver(transceiver, local_description());
2716 if (!content) {
2717 continue;
2718 }
2719 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002720 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2721 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002722 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002723 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2724 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2725 // "recvonly", process the removal of a remote track for the media
2726 // description, given transceiver, removeList, and muteTracks.
2727 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2728 (transceiver->internal()->fired_direction() &&
2729 RtpTransceiverDirectionHasRecv(
2730 *transceiver->internal()->fired_direction()))) {
2731 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2732 &removed_streams);
2733 }
2734 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2735 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002736 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002737 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002738 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002739 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002740 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002741 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002742 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002743 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002744 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002745 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002746 }
2747 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002748 // Media channels will be created only when offer is set. These may use new
2749 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002750 if (type == SdpType::kOffer) {
2751 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2752 // description is applied. Restore back to old description.
2753 RTCError error = CreateChannels(*local_description()->description());
2754 if (!error.ok()) {
2755 return error;
2756 }
2757 }
Steve Antondcc3c022017-12-22 16:02:54 -08002758 // Remove unused channels if MediaContentDescription is rejected.
2759 RemoveUnusedChannels(local_description()->description());
2760 }
Steve Anton8a006912017-12-04 15:25:56 -08002761
Zhi Huange830e682018-03-30 10:48:35 -07002762 error = UpdateSessionState(type, cricket::CS_LOCAL,
2763 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002764 if (!error.ok()) {
2765 return error;
2766 }
Steve Antondcc3c022017-12-22 16:02:54 -08002767
Steve Anton8a006912017-12-04 15:25:56 -08002768 if (remote_description()) {
2769 // Now that we have a local description, we can push down remote candidates.
2770 UseCandidatesInSessionDescription(remote_description());
2771 }
2772
2773 pending_ice_restarts_.clear();
2774 if (session_error() != SessionError::kNone) {
2775 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2776 }
2777
deadbeefab9b2d12015-10-14 11:33:11 -07002778 // If setting the description decided our SSL role, allocate any necessary
2779 // SCTP sids.
2780 rtc::SSLRole role;
Harald Alvestrand05e4d082019-12-03 14:04:21 +01002781 if (DataChannel::IsSctpLike(data_channel_type()) && GetSctpSslRole(&role)) {
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01002782 data_channel_controller_.AllocateSctpSids(role);
deadbeefab9b2d12015-10-14 11:33:11 -07002783 }
2784
Steve Antond3679212018-01-17 17:41:02 -08002785 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002786 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002787 const ContentInfo* content =
2788 FindMediaSectionForTransceiver(transceiver, local_description());
2789 if (!content) {
2790 continue;
2791 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002792 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2793 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002794 // 0 is a special value meaning "this sender has no associated send
2795 // stream". Need to call this so the sender won't attempt to configure
2796 // a no longer existing stream and run into DCHECKs in the lower
2797 // layers.
2798 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002799 } else {
2800 // Get the StreamParams from the channel which could generate SSRCs.
2801 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002802 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002803 streams[0].stream_ids());
2804 transceiver->internal()->sender_internal()->SetSsrc(
2805 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002806 }
2807 }
2808 } else {
2809 // Plan B semantics.
2810
Steve Antondcc3c022017-12-22 16:02:54 -08002811 // Update state and SSRC of local MediaStreams and DataChannels based on the
2812 // local session description.
2813 const cricket::ContentInfo* audio_content =
2814 GetFirstAudioContent(local_description()->description());
2815 if (audio_content) {
2816 if (audio_content->rejected) {
2817 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2818 } else {
2819 const cricket::AudioContentDescription* audio_desc =
2820 audio_content->media_description()->as_audio();
2821 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2822 }
deadbeeffaac4972015-11-12 15:33:07 -08002823 }
deadbeefab9b2d12015-10-14 11:33:11 -07002824
Steve Antondcc3c022017-12-22 16:02:54 -08002825 const cricket::ContentInfo* video_content =
2826 GetFirstVideoContent(local_description()->description());
2827 if (video_content) {
2828 if (video_content->rejected) {
2829 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2830 } else {
2831 const cricket::VideoContentDescription* video_desc =
2832 video_content->media_description()->as_video();
2833 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2834 }
deadbeeffaac4972015-11-12 15:33:07 -08002835 }
deadbeefab9b2d12015-10-14 11:33:11 -07002836 }
2837
2838 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002839 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002840 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002841 const cricket::RtpDataContentDescription* rtp_data_desc =
2842 data_content->media_description()->as_rtp_data();
2843 // rtp_data_desc will be null if this is an SCTP description.
2844 if (rtp_data_desc) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01002845 data_channel_controller_.UpdateLocalRtpDataChannels(
2846 rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002847 }
2848 }
2849
Henrik Boström79b69802019-07-18 11:16:56 +02002850 if (type == SdpType::kAnswer &&
2851 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2852 *current_local_description_)) {
2853 local_ice_credentials_to_replace_->ClearIceCredentials();
2854 }
2855
Steve Anton8a006912017-12-04 15:25:56 -08002856 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002857}
2858
Steve Anton06817cd2018-12-18 15:55:30 -08002859// The SDP parser used to populate these values by default for the 'content
2860// name' if an a=mid line was absent.
2861static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2862 switch (media_type) {
2863 case cricket::MEDIA_TYPE_AUDIO:
2864 return cricket::CN_AUDIO;
2865 case cricket::MEDIA_TYPE_VIDEO:
2866 return cricket::CN_VIDEO;
2867 case cricket::MEDIA_TYPE_DATA:
2868 return cricket::CN_DATA;
2869 }
2870 RTC_NOTREACHED();
2871 return "";
2872}
2873
2874void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002875 cricket::SessionDescription* new_remote_description) {
2876 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002877 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002878 const cricket::ContentInfos& local_contents =
2879 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002880 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002881 const cricket::ContentInfos& remote_contents =
2882 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002883 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002884 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2885 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002886 if (!content.name.empty()) {
2887 continue;
2888 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002889 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002890 absl::string_view source_explanation;
2891 if (IsUnifiedPlan()) {
2892 if (i < local_contents.size()) {
2893 new_mid = local_contents[i].name;
2894 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002895 } else if (i < remote_contents.size()) {
2896 new_mid = remote_contents[i].name;
2897 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002898 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002899 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002900 source_explanation = "generated just now";
2901 }
2902 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002903 new_mid = std::string(
2904 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002905 source_explanation = "to match pre-existing behavior";
2906 }
Steve Antond7180cc2019-02-07 10:44:53 -08002907 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002908 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002909 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002910 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2911 << " is missing an a=mid line. Filling in the value '"
2912 << new_mid << "' " << source_explanation << ".";
2913 }
2914}
2915
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002916void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002917 SetSessionDescriptionObserver* observer,
Henrik Boströma3728d32019-10-28 12:09:49 +01002918 SessionDescriptionInterface* desc_ptr) {
2919 RTC_DCHECK_RUN_ON(signaling_thread());
2920 // Chain this operation. If asynchronous operations are pending on the chain,
2921 // this operation will be queued to be invoked, otherwise the contents of the
2922 // lambda will execute immediately.
2923 operations_chain_->ChainOperation(
2924 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
2925 observer_refptr =
2926 rtc::scoped_refptr<SetSessionDescriptionObserver>(observer),
2927 desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)](
2928 std::function<void()> operations_chain_callback) mutable {
2929 // Abort early if |this_weak_ptr| is no longer valid.
2930 if (!this_weak_ptr) {
2931 // For consistency with SetRemoteDescriptionObserverAdapter, we DO NOT
2932 // inform the |observer_refptr| that the operation failed in this
2933 // case.
2934 // TODO(hbos): If/when we process SRD messages in ~PeerConnection,
2935 // the consistent thing would be to inform the observer here.
2936 operations_chain_callback();
2937 return;
2938 }
2939 this_weak_ptr->DoSetRemoteDescription(
2940 std::move(desc),
2941 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2942 new SetRemoteDescriptionObserverAdapter(
2943 this_weak_ptr.get(), std::move(observer_refptr))));
2944 // DoSetRemoteDescription() is currently implemented as a synchronous
2945 // operation but where SetRemoteDescriptionObserverAdapter ensures that
2946 // the |observer|'s callbacks are invoked asynchronously in a post to
2947 // OnMessage().
2948 // For backwards-compatability reasons, we declare the operation as
Henrik Boström4e196702019-10-30 10:35:50 +01002949 // completed here (rather than in OnMessage()). This ensures that
2950 // subsequent offer/answer operations can start immediately (without
2951 // waiting for OnMessage()).
Henrik Boströma3728d32019-10-28 12:09:49 +01002952 operations_chain_callback();
2953 });
Henrik Boström31638672017-11-23 17:48:32 +01002954}
2955
2956void PeerConnection::SetRemoteDescription(
2957 std::unique_ptr<SessionDescriptionInterface> desc,
2958 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002959 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boströma3728d32019-10-28 12:09:49 +01002960 // Chain this operation. If asynchronous operations are pending on the chain,
2961 // this operation will be queued to be invoked, otherwise the contents of the
2962 // lambda will execute immediately.
2963 operations_chain_->ChainOperation(
2964 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer,
2965 desc = std::move(desc)](
2966 std::function<void()> operations_chain_callback) mutable {
2967 // Abort early if |this_weak_ptr| is no longer valid.
2968 if (!this_weak_ptr) {
2969 // For consistency with DoSetRemoteDescription(), we DO inform the
2970 // |observer| that the operation failed in this case.
2971 observer->OnSetRemoteDescriptionComplete(RTCError(
2972 RTCErrorType::INVALID_STATE,
2973 "Failed to set remote offer sdp: failed because the session was "
2974 "shut down"));
2975 operations_chain_callback();
2976 return;
2977 }
2978 this_weak_ptr->DoSetRemoteDescription(std::move(desc),
2979 std::move(observer));
2980 // DoSetRemoteDescription() is currently implemented as a synchronous
2981 // operation. The |observer| will already have been informed that it
2982 // completed, and we can mark this operation as complete without any
2983 // loose ends.
2984 operations_chain_callback();
2985 });
2986}
2987
2988void PeerConnection::DoSetRemoteDescription(
2989 std::unique_ptr<SessionDescriptionInterface> desc,
2990 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
2991 RTC_DCHECK_RUN_ON(signaling_thread());
2992 TRACE_EVENT0("webrtc", "PeerConnection::DoSetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002993
nisse7ce109a2017-01-31 00:57:56 -08002994 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002995 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002996 return;
2997 }
Steve Anton8a006912017-12-04 15:25:56 -08002998
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002999 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01003000 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08003001 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003002 return;
3003 }
Steve Anton8d3444d2017-10-20 15:30:51 -07003004
Steve Anton80dd7b52018-02-16 17:08:42 -08003005 // If a session error has occurred the PeerConnection is in a possibly
3006 // inconsistent state so fail right away.
3007 if (session_error() != SessionError::kNone) {
3008 std::string error_message = GetSessionErrorMsg();
3009 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
3010 observer->OnSetRemoteDescriptionComplete(
3011 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
3012 return;
3013 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003014 if (IsUnifiedPlan()) {
3015 if (configuration_.enable_implicit_rollback) {
3016 if (desc->GetType() == SdpType::kOffer &&
3017 signaling_state() == kHaveLocalOffer) {
Eldar Relloead0ec92019-10-21 23:01:31 +03003018 Rollback(desc->GetType());
Eldar Rello5ab79e62019-10-09 18:29:44 +03003019 }
3020 }
3021 // Explicit rollback.
3022 if (desc->GetType() == SdpType::kRollback) {
Eldar Relloead0ec92019-10-21 23:01:31 +03003023 observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
Eldar Rello5ab79e62019-10-09 18:29:44 +03003024 return;
3025 }
3026 } else if (desc->GetType() == SdpType::kRollback) {
3027 observer->OnSetRemoteDescriptionComplete(
3028 RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
3029 "Rollback not supported in Plan B"));
3030 return;
3031 }
Steve Antonba42e992018-04-09 14:10:01 -07003032 if (desc->GetType() == SdpType::kOffer) {
3033 // Report to UMA the format of the received offer.
3034 ReportSdpFormatReceived(*desc);
3035 }
3036
Steve Anton06817cd2018-12-18 15:55:30 -08003037 // Handle remote descriptions missing a=mid lines for interop with legacy end
3038 // points.
3039 FillInMissingRemoteMids(desc->description());
3040
Steve Anton80dd7b52018-02-16 17:08:42 -08003041 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08003042 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08003043 std::string error_message = GetSetDescriptionErrorMessage(
3044 cricket::CS_REMOTE, desc->GetType(), error);
3045 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08003046 observer->OnSetRemoteDescriptionComplete(
3047 RTCError(error.type(), std::move(error_message)));
3048 return;
3049 }
Steve Anton71439a62018-02-15 11:53:06 -08003050
Steve Anton80dd7b52018-02-16 17:08:42 -08003051 // Grab the description type before moving ownership to
3052 // ApplyRemoteDescription, which may destroy it before returning.
3053 const SdpType type = desc->GetType();
3054
3055 error = ApplyRemoteDescription(std::move(desc));
3056 // |desc| may be destroyed at this point.
3057
3058 if (!error.ok()) {
3059 // If ApplyRemoteDescription fails, the PeerConnection could be in an
3060 // inconsistent state, so act conservatively here and set the session error
3061 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
3062 SetSessionError(SessionError::kContent, error.message());
3063 std::string error_message =
3064 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
3065 RTC_LOG(LS_ERROR) << error_message;
3066 observer->OnSetRemoteDescriptionComplete(
3067 RTCError(error.type(), std::move(error_message)));
3068 return;
3069 }
3070 RTC_DCHECK(remote_description());
3071
3072 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08003073 // TODO(deadbeef): We already had to hop to the network thread for
3074 // MaybeStartGathering...
3075 network_thread()->Invoke<void>(
3076 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3077 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01003078 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08003079 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08003080 }
3081
Guido Urdaneta70c2db12019-04-16 12:24:14 +02003082 if (IsUnifiedPlan()) {
3083 bool was_negotiation_needed = is_negotiation_needed_;
3084 UpdateNegotiationNeeded();
3085 if (signaling_state() == kStable && was_negotiation_needed &&
3086 is_negotiation_needed_) {
3087 Observer()->OnRenegotiationNeeded();
3088 }
3089 }
3090
Steve Anton8a006912017-12-04 15:25:56 -08003091 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003092 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08003093}
3094
3095RTCError PeerConnection::ApplyRemoteDescription(
3096 std::unique_ptr<SessionDescriptionInterface> desc) {
3097 RTC_DCHECK_RUN_ON(signaling_thread());
3098 RTC_DCHECK(desc);
3099
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100 // Update stats here so that we have the most recent stats for tracks and
3101 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003102 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08003103
Steve Antondcc3c022017-12-22 16:02:54 -08003104 // Take a reference to the old remote description since it's used below to
3105 // compare against the new remote description. When setting the new remote
3106 // description, grab ownership of the replaced session description in case it
3107 // is the same as |old_remote_description|, to keep it alive for the duration
3108 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08003109 const SessionDescriptionInterface* old_remote_description =
3110 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08003111 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08003112 SdpType type = desc->GetType();
3113 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08003114 replaced_remote_description = pending_remote_description_
3115 ? std::move(pending_remote_description_)
3116 : std::move(current_remote_description_);
3117 current_remote_description_ = std::move(desc);
3118 pending_remote_description_ = nullptr;
3119 current_local_description_ = std::move(pending_local_description_);
3120 } else {
3121 replaced_remote_description = std::move(pending_remote_description_);
3122 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003123 }
Steve Anton8a006912017-12-04 15:25:56 -08003124 // The session description to apply now must be accessed by
3125 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01003126 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003127
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003128 // Report statistics about any use of simulcast.
3129 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
3130 *remote_description()->description());
3131
Zhi Huange830e682018-03-30 10:48:35 -07003132 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
3133 if (!error.ok()) {
3134 return error;
3135 }
Steve Anton8a006912017-12-04 15:25:56 -08003136 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08003137 if (IsUnifiedPlan()) {
3138 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003139 cricket::CS_REMOTE, *remote_description(), local_description(),
3140 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08003141 if (!error.ok()) {
3142 return error;
3143 }
Steve Antondcc3c022017-12-22 16:02:54 -08003144 } else {
Zhi Huange830e682018-03-30 10:48:35 -07003145 // Media channels will be created only when offer is set. These may use new
3146 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08003147 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07003148 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08003149 // description is applied. Restore back to old description.
3150 RTCError error = CreateChannels(*remote_description()->description());
3151 if (!error.ok()) {
3152 return error;
3153 }
3154 }
Steve Antondcc3c022017-12-22 16:02:54 -08003155 // Remove unused channels if MediaContentDescription is rejected.
3156 RemoveUnusedChannels(remote_description()->description());
3157 }
Steve Anton8a006912017-12-04 15:25:56 -08003158
Zhi Huange830e682018-03-30 10:48:35 -07003159 // NOTE: Candidates allocation will be initiated only when
3160 // SetLocalDescription is called.
3161 error = UpdateSessionState(type, cricket::CS_REMOTE,
3162 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08003163 if (!error.ok()) {
3164 return error;
3165 }
3166
3167 if (local_description() &&
3168 !UseCandidatesInSessionDescription(remote_description())) {
3169 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
3170 }
3171
3172 if (old_remote_description) {
3173 for (const cricket::ContentInfo& content :
3174 old_remote_description->description()->contents()) {
3175 // Check if this new SessionDescription contains new ICE ufrag and
3176 // password that indicates the remote peer requests an ICE restart.
3177 // TODO(deadbeef): When we start storing both the current and pending
3178 // remote description, this should reset pending_ice_restarts and compare
3179 // against the current description.
3180 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3181 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08003182 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08003183 pending_ice_restarts_.insert(content.name);
3184 }
3185 } else {
3186 // We retain all received candidates only if ICE is not restarted.
3187 // When ICE is restarted, all previous candidates belong to an old
3188 // generation and should not be kept.
3189 // TODO(deadbeef): This goes against the W3C spec which says the remote
3190 // description should only contain candidates from the last set remote
3191 // description plus any candidates added since then. We should remove
3192 // this once we're sure it won't break anything.
3193 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3194 old_remote_description, content.name, mutable_remote_description());
3195 }
3196 }
3197 }
3198
3199 if (session_error() != SessionError::kNone) {
3200 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3201 }
3202
3203 // Set the the ICE connection state to connecting since the connection may
3204 // become writable with peer reflexive candidates before any remote candidate
3205 // is signaled.
3206 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3207 // is to have a new signal the indicates a change in checking state from the
3208 // transport and expose a new checking() member from transport that can be
3209 // read to determine the current checking state. The existing SignalConnecting
3210 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08003211 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07003212 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08003213 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3214 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3215 }
3216
deadbeefab9b2d12015-10-14 11:33:11 -07003217 // If setting the description decided our SSL role, allocate any necessary
3218 // SCTP sids.
3219 rtc::SSLRole role;
Harald Alvestrand05e4d082019-12-03 14:04:21 +01003220 if (DataChannel::IsSctpLike(data_channel_type()) && GetSctpSslRole(&role)) {
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01003221 data_channel_controller_.AllocateSctpSids(role);
deadbeefab9b2d12015-10-14 11:33:11 -07003222 }
3223
Steve Antondcc3c022017-12-22 16:02:54 -08003224 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08003225 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07003226 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07003227 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08003228 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07003229 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01003230 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08003231 const ContentInfo* content =
3232 FindMediaSectionForTransceiver(transceiver, remote_description());
3233 if (!content) {
3234 continue;
3235 }
3236 const MediaContentDescription* media_desc = content->media_description();
3237 RtpTransceiverDirection local_direction =
3238 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003239 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
3240 // RTCSessionDescription: Set the associated remote streams given
3241 // transceiver.[[Receiver]], msids, addList, and removeList".
3242 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
3243 if (RtpTransceiverDirectionHasRecv(local_direction)) {
3244 std::vector<std::string> stream_ids;
3245 if (!media_desc->streams().empty()) {
3246 // The remote description has signaled the stream IDs.
3247 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08003248 }
Eldar Rello353a7182019-11-25 18:49:44 +02003249 transceiver_stable_states_by_transceivers_[transceiver]
3250 .SetRemoteStreamIdsIfUnset(transceiver->receiver()->stream_ids());
3251
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003252 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
3253 << " (" << GetStreamIdsString(stream_ids) << ").";
3254 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
3255 stream_ids, &added_streams,
3256 &removed_streams);
3257 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
3258 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
3259 // and transceiver's current direction is neither sendrecv nor recvonly,
3260 // process the addition of a remote track for the media description.
3261 if (!transceiver->fired_direction() ||
3262 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
3263 RTC_LOG(LS_INFO)
3264 << "Processing the addition of a remote track for MID="
3265 << content->name << ".";
3266 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01003267 }
Steve Antondcc3c022017-12-22 16:02:54 -08003268 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003269 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07003270 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
3271 // removal of a remote track for the media description, given transceiver,
3272 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08003273 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07003274 (transceiver->fired_direction() &&
3275 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
3276 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
3277 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08003278 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003279 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07003280 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003281 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07003282 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08003283 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003284 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07003285 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08003286 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003287 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
3288 if (transceiver->mid()) {
3289 auto dtls_transport =
3290 LookupDtlsTransportByMidInternal(*transceiver->mid());
3291 transceiver->internal()->sender_internal()->set_transport(
3292 dtls_transport);
3293 transceiver->internal()->receiver_internal()->set_transport(
3294 dtls_transport);
3295 }
Steve Antondcc3c022017-12-22 16:02:54 -08003296 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003297 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07003298 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08003299 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07003300 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
3301 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08003302 transceiver->Stop();
3303 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003304 if (!content->rejected &&
3305 RtpTransceiverDirectionHasRecv(local_direction)) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07003306 if (!media_desc->streams().empty() &&
3307 media_desc->streams()[0].has_ssrcs()) {
Saurav Das7262fc22019-09-11 16:23:05 -07003308 uint32_t ssrc = media_desc->streams()[0].first_ssrc();
3309 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
3310 } else {
3311 transceiver->internal()
3312 ->receiver_internal()
3313 ->SetupUnsignaledMediaChannel();
Seth Hampson2f0d7022018-02-20 11:54:42 -08003314 }
Steve Antond3679212018-01-17 17:41:02 -08003315 }
Steve Antondcc3c022017-12-22 16:02:54 -08003316 }
Steve Antonc49bcd92018-02-14 14:28:13 -08003317 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003318 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01003319 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08003320 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003321 observer->OnTrack(transceiver);
3322 observer->OnAddTrack(transceiver->receiver(),
3323 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08003324 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003325 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003326 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08003327 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003328 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003329 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07003330 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01003331 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003332 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07003333 }
Steve Antondcc3c022017-12-22 16:02:54 -08003334 }
3335
Henrik Boströmfdb92012017-11-09 19:55:44 +01003336 const cricket::ContentInfo* audio_content =
3337 GetFirstAudioContent(remote_description()->description());
3338 const cricket::ContentInfo* video_content =
3339 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003340 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003341 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003342 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01003343 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003344 const cricket::RtpDataContentDescription* rtp_data_desc =
3345 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08003346
3347 // Check if the descriptions include streams, just in case the peer supports
3348 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01003349 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08003350 (audio_desc && !audio_desc->streams().empty()) ||
3351 (video_desc && !video_desc->streams().empty())) {
3352 remote_peer_supports_msid_ = true;
3353 }
deadbeefab9b2d12015-10-14 11:33:11 -07003354
3355 // We wait to signal new streams until we finish processing the description,
3356 // since only at that point will new streams have all their tracks.
3357 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
3358
Steve Antondcc3c022017-12-22 16:02:54 -08003359 if (!IsUnifiedPlan()) {
3360 // TODO(steveanton): When removing RTP senders/receivers in response to a
3361 // rejected media section, there is some cleanup logic that expects the
3362 // voice/ video channel to still be set. But in this method the voice/video
3363 // channel would have been destroyed by the SetRemoteDescription caller
3364 // above so the cleanup that relies on them fails to run. The RemoveSenders
3365 // calls should be moved to right before the DestroyChannel calls to fix
3366 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07003367
Steve Antondcc3c022017-12-22 16:02:54 -08003368 // Find all audio rtp streams and create corresponding remote AudioTracks
3369 // and MediaStreams.
3370 if (audio_content) {
3371 if (audio_content->rejected) {
3372 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
3373 } else {
3374 bool default_audio_track_needed =
3375 !remote_peer_supports_msid_ &&
3376 RtpTransceiverDirectionHasSend(audio_desc->direction());
3377 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
3378 default_audio_track_needed, audio_desc->type(),
3379 new_streams);
3380 }
deadbeeffaac4972015-11-12 15:33:07 -08003381 }
deadbeefab9b2d12015-10-14 11:33:11 -07003382
Steve Antondcc3c022017-12-22 16:02:54 -08003383 // Find all video rtp streams and create corresponding remote VideoTracks
3384 // and MediaStreams.
3385 if (video_content) {
3386 if (video_content->rejected) {
3387 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
3388 } else {
3389 bool default_video_track_needed =
3390 !remote_peer_supports_msid_ &&
3391 RtpTransceiverDirectionHasSend(video_desc->direction());
3392 UpdateRemoteSendersList(GetActiveStreams(video_desc),
3393 default_video_track_needed, video_desc->type(),
3394 new_streams);
3395 }
deadbeeffaac4972015-11-12 15:33:07 -08003396 }
deadbeefab9b2d12015-10-14 11:33:11 -07003397
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003398 // If this is an RTP data transport, update the DataChannels with the
3399 // information from the remote peer.
3400 if (rtp_data_desc) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01003401 data_channel_controller_.UpdateRemoteRtpDataChannels(
3402 GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07003403 }
deadbeefab9b2d12015-10-14 11:33:11 -07003404
Steve Antondcc3c022017-12-22 16:02:54 -08003405 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003406 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08003407 for (size_t i = 0; i < new_streams->count(); ++i) {
3408 MediaStreamInterface* new_stream = new_streams->at(i);
3409 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003410 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08003411 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
3412 }
deadbeefab9b2d12015-10-14 11:33:11 -07003413
Steve Antondcc3c022017-12-22 16:02:54 -08003414 UpdateEndedRemoteMediaStreams();
3415 }
deadbeefab9b2d12015-10-14 11:33:11 -07003416
Henrik Boström79b69802019-07-18 11:16:56 +02003417 if (type == SdpType::kAnswer &&
3418 local_ice_credentials_to_replace_->SatisfiesIceRestart(
3419 *current_local_description_)) {
3420 local_ice_credentials_to_replace_->ClearIceCredentials();
3421 }
3422
Steve Anton8a006912017-12-04 15:25:56 -08003423 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07003424}
3425
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003426void PeerConnection::SetAssociatedRemoteStreams(
3427 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3428 const std::vector<std::string>& stream_ids,
3429 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3430 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3431 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3432 for (const std::string& stream_id : stream_ids) {
3433 rtc::scoped_refptr<MediaStreamInterface> stream =
3434 remote_streams_->find(stream_id);
3435 if (!stream) {
3436 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3437 MediaStream::Create(stream_id));
3438 remote_streams_->AddStream(stream);
3439 added_streams->push_back(stream);
3440 }
3441 media_streams.push_back(stream);
3442 }
3443 // Special case: "a=msid" missing, use random stream ID.
3444 if (media_streams.empty() &&
3445 !(remote_description()->description()->msid_signaling() &
3446 cricket::kMsidSignalingMediaSection)) {
3447 if (!missing_msid_default_stream_) {
3448 missing_msid_default_stream_ = MediaStreamProxy::Create(
3449 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3450 added_streams->push_back(missing_msid_default_stream_);
3451 }
3452 media_streams.push_back(missing_msid_default_stream_);
3453 }
3454 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3455 receiver->streams();
3456 // SetStreams() will add/remove the receiver's track to/from the streams. This
3457 // differs from the spec - the spec uses an "addList" and "removeList" to
3458 // update the stream-track relationships in a later step. We do this earlier,
3459 // changing the order of things, but the end-result is the same.
3460 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3461 // instead. https://crbug.com/webrtc/9480
3462 receiver->SetStreams(media_streams);
3463 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3464}
3465
Steve Anton0f5400a2018-07-17 14:25:36 -07003466void PeerConnection::ProcessRemovalOfRemoteTrack(
3467 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3468 transceiver,
3469 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3470 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3471 RTC_DCHECK(transceiver->mid());
3472 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3473 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003474 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003475 transceiver->internal()->receiver_internal()->streams();
3476 // This will remove the remote track from the streams.
3477 transceiver->internal()->receiver_internal()->set_stream_ids({});
3478 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003479 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3480}
3481
3482void PeerConnection::RemoveRemoteStreamsIfEmpty(
3483 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3484 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3485 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3486 // streams, see if the stream was removed by checking if this was the last
3487 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003488 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003489 if (remote_stream->GetAudioTracks().empty() &&
3490 remote_stream->GetVideoTracks().empty()) {
3491 remote_streams_->RemoveStream(remote_stream);
3492 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003493 }
3494 }
3495}
3496
Steve Antondcc3c022017-12-22 16:02:54 -08003497RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3498 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003499 const SessionDescriptionInterface& new_session,
3500 const SessionDescriptionInterface* old_local_description,
3501 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003502 RTC_DCHECK(IsUnifiedPlan());
3503
Steve Anton7464fca2018-01-19 11:10:37 -08003504 const cricket::ContentGroup* bundle_group = nullptr;
3505 if (new_session.GetType() == SdpType::kOffer) {
3506 auto bundle_group_or_error =
3507 GetEarlyBundleGroup(*new_session.description());
3508 if (!bundle_group_or_error.ok()) {
3509 return bundle_group_or_error.MoveError();
3510 }
3511 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003512 }
Steve Antondcc3c022017-12-22 16:02:54 -08003513
Steve Antondcc3c022017-12-22 16:02:54 -08003514 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003515 for (size_t i = 0; i < new_contents.size(); ++i) {
3516 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003517 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003518 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003519 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3520 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003521 const cricket::ContentInfo* old_local_content = nullptr;
3522 if (old_local_description &&
3523 i < old_local_description->description()->contents().size()) {
3524 old_local_content =
3525 &old_local_description->description()->contents()[i];
3526 }
3527 const cricket::ContentInfo* old_remote_content = nullptr;
3528 if (old_remote_description &&
3529 i < old_remote_description->description()->contents().size()) {
3530 old_remote_content =
3531 &old_remote_description->description()->contents()[i];
3532 }
Steve Antondcc3c022017-12-22 16:02:54 -08003533 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003534 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3535 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003536 if (!transceiver_or_error.ok()) {
3537 return transceiver_or_error.MoveError();
3538 }
3539 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003540 RTCError error =
3541 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3542 if (!error.ok()) {
3543 return error;
3544 }
3545 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003546 if (GetDataMid() && new_content.name != *GetDataMid()) {
3547 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003548 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3549 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003550 continue;
3551 }
3552 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3553 if (!error.ok()) {
3554 return error;
3555 }
Steve Antondcc3c022017-12-22 16:02:54 -08003556 } else {
3557 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3558 "Unknown section type.");
3559 }
3560 }
3561
3562 return RTCError::OK();
3563}
3564
3565RTCError PeerConnection::UpdateTransceiverChannel(
3566 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3567 transceiver,
3568 const cricket::ContentInfo& content,
3569 const cricket::ContentGroup* bundle_group) {
3570 RTC_DCHECK(IsUnifiedPlan());
3571 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003572 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003573 if (content.rejected) {
3574 if (channel) {
3575 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003576 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003577 }
3578 } else {
3579 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003580 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003581 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003582 } else {
Steve Anton69470252018-02-09 11:43:08 -08003583 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003584 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003585 }
3586 if (!channel) {
3587 LOG_AND_RETURN_ERROR(
3588 RTCErrorType::INTERNAL_ERROR,
3589 "Failed to create channel for mid=" + content.name);
3590 }
3591 transceiver->internal()->SetChannel(channel);
3592 }
3593 }
3594 return RTCError::OK();
3595}
3596
Steve Antonfa2260d2017-12-28 16:38:23 -08003597RTCError PeerConnection::UpdateDataChannel(
3598 cricket::ContentSource source,
3599 const cricket::ContentInfo& content,
3600 const cricket::ContentGroup* bundle_group) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01003601 if (data_channel_type() == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003602 // If data channels are disabled, ignore this media section. CreateAnswer
3603 // will take care of rejecting it.
3604 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003605 }
3606 if (content.rejected) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003607 RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
Harald Alvestrand408cb4b2019-11-16 12:09:08 +01003608 DestroyDataChannelTransport();
Steve Antonfa2260d2017-12-28 16:38:23 -08003609 } else {
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01003610 if (!data_channel_controller_.rtp_data_channel() &&
3611 !data_channel_controller_.data_channel_transport()) {
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003612 RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
Zhi Huange830e682018-03-30 10:48:35 -07003613 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003614 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3615 "Failed to create data channel.");
3616 }
3617 }
3618 if (source == cricket::CS_REMOTE) {
3619 const MediaContentDescription* data_desc = content.media_description();
3620 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01003621 data_channel_controller_.UpdateRemoteRtpDataChannels(
3622 GetActiveStreams(data_desc));
Steve Antonfa2260d2017-12-28 16:38:23 -08003623 }
3624 }
3625 }
3626 return RTCError::OK();
3627}
3628
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003629// This method will extract any send encodings that were sent by the remote
3630// connection. This is currently only relevant for Simulcast scenario (where
3631// the number of layers may be communicated by the server).
3632static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3633 const MediaContentDescription& desc) {
3634 if (!desc.HasSimulcast()) {
3635 return {};
3636 }
3637 std::vector<RtpEncodingParameters> result;
3638 const SimulcastDescription& simulcast = desc.simulcast_description();
3639
3640 // This is a remote description, the parameters we are after should appear
3641 // as receive streams.
3642 for (const auto& alternatives : simulcast.receive_layers()) {
3643 RTC_DCHECK(!alternatives.empty());
3644 // There is currently no way to specify or choose from alternatives.
3645 // We will always use the first alternative, which is the most preferred.
3646 const SimulcastLayer& layer = alternatives[0];
3647 RtpEncodingParameters parameters;
3648 parameters.rid = layer.rid;
3649 parameters.active = !layer.is_paused;
3650 result.push_back(parameters);
3651 }
3652
3653 return result;
3654}
3655
3656static RTCError UpdateSimulcastLayerStatusInSender(
3657 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003658 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003659 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003660 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003661 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003662
3663 // The simulcast envelope cannot be changed, only the status of the streams.
3664 // So we will iterate over the send encodings rather than the layers.
3665 for (RtpEncodingParameters& encoding : parameters.encodings) {
3666 auto iter = std::find_if(layers.begin(), layers.end(),
3667 [&encoding](const SimulcastLayer& layer) {
3668 return layer.rid == encoding.rid;
3669 });
3670 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003671 if (iter == layers.end()) {
3672 disabled_layers.push_back(encoding.rid);
3673 continue;
3674 }
3675
3676 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003677 }
3678
Amit Hilbuch619b2942019-02-26 15:55:19 -08003679 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003680 if (result.ok()) {
3681 result = sender->DisableEncodingLayers(disabled_layers);
3682 }
3683
3684 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003685}
3686
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003687static bool SimulcastIsRejected(
3688 const ContentInfo* local_content,
3689 const MediaContentDescription& answer_media_desc) {
3690 bool simulcast_offered = local_content &&
3691 local_content->media_description() &&
3692 local_content->media_description()->HasSimulcast();
3693 bool simulcast_answered = answer_media_desc.HasSimulcast();
3694 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3695 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3696 return simulcast_offered && (!simulcast_answered || !rids_supported);
3697}
3698
Amit Hilbuch2297d332019-02-19 12:49:22 -08003699static RTCError DisableSimulcastInSender(
3700 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003701 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003702 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003703 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003704 return RTCError::OK();
3705 }
3706
Amit Hilbuch2297d332019-02-19 12:49:22 -08003707 std::vector<std::string> disabled_layers;
3708 std::transform(
3709 parameters.encodings.begin() + 1, parameters.encodings.end(),
3710 std::back_inserter(disabled_layers),
3711 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3712 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003713}
3714
Steve Antondcc3c022017-12-22 16:02:54 -08003715RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3716PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003717 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003718 size_t mline_index,
3719 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003720 const ContentInfo* old_local_content,
3721 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003722 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003723 // If this is an offer then the m= section might be recycled. If the m=
3724 // section is being recycled (defined as: rejected in the current local or
3725 // remote description and not rejected in new description), dissociate the
3726 // currently associated RtpTransceiver by setting its mid property to null,
3727 // and discard the mapping between the transceiver and its m= section index.
3728 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3729 old_remote_content)) {
3730 // We want to dissociate the transceiver that has the rejected mid.
3731 const std::string& old_mid =
3732 (old_local_content && old_local_content->rejected)
3733 ? old_local_content->name
3734 : old_remote_content->name;
3735 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003736 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003737 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3738 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003739 old_transceiver->internal()->set_mid(absl::nullopt);
3740 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003741 }
3742 }
3743 const MediaContentDescription* media_desc = content.media_description();
3744 auto transceiver = GetAssociatedTransceiver(content.name);
3745 if (source == cricket::CS_LOCAL) {
3746 // Find the RtpTransceiver that corresponds to this m= section, using the
3747 // mapping between transceivers and m= section indices established when
3748 // creating the offer.
3749 if (!transceiver) {
3750 transceiver = GetTransceiverByMLineIndex(mline_index);
3751 }
3752 if (!transceiver) {
3753 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3754 "Unknown transceiver");
3755 }
3756 } else {
3757 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3758 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3759 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003760 // When simulcast is requested, a transceiver cannot be associated because
3761 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003762 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003763 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3764 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003765 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3766 }
3767 // If no RtpTransceiver was found in the previous step, create one with a
3768 // recvonly direction.
3769 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003770 RTC_LOG(LS_INFO) << "Adding "
3771 << cricket::MediaTypeToString(media_desc->type())
3772 << " transceiver for MID=" << content.name
3773 << " at i=" << mline_index
3774 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003775 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003776 std::vector<RtpEncodingParameters> send_encodings =
3777 GetSendEncodingsFromRemoteDescription(*media_desc);
3778 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3779 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003780 std::string receiver_id;
3781 if (!media_desc->streams().empty()) {
3782 receiver_id = media_desc->streams()[0].id;
3783 } else {
3784 receiver_id = rtc::CreateRandomUuid();
3785 }
3786 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003787 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003788 transceiver->internal()->set_direction(
3789 RtpTransceiverDirection::kRecvOnly);
Eldar Rello5ab79e62019-10-09 18:29:44 +03003790 if (type == SdpType::kOffer) {
Eldar Rello353a7182019-11-25 18:49:44 +02003791 transceiver_stable_states_by_transceivers_[transceiver]
3792 .set_newly_created();
Eldar Rello5ab79e62019-10-09 18:29:44 +03003793 }
Steve Antondcc3c022017-12-22 16:02:54 -08003794 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003795 // Check if the offer indicated simulcast but the answer rejected it.
3796 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003797 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003798 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003799 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003800 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003801 if (!error.ok()) {
3802 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3803 return std::move(error);
3804 }
3805 }
Steve Antondcc3c022017-12-22 16:02:54 -08003806 }
3807 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003808 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003809 LOG_AND_RETURN_ERROR(
3810 RTCErrorType::INVALID_PARAMETER,
3811 "Transceiver type does not match media description type.");
3812 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003813 if (media_desc->HasSimulcast()) {
3814 std::vector<SimulcastLayer> layers =
3815 source == cricket::CS_LOCAL
3816 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3817 : media_desc->simulcast_description()
3818 .receive_layers()
3819 .GetAllLayers();
3820 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003821 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003822 if (!error.ok()) {
3823 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3824 return std::move(error);
3825 }
3826 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03003827 if (type == SdpType::kOffer) {
Eldar Rello353a7182019-11-25 18:49:44 +02003828 bool state_changes = transceiver->internal()->mid() != content.name ||
3829 transceiver->internal()->mline_index() != mline_index;
3830 if (state_changes) {
3831 transceiver_stable_states_by_transceivers_[transceiver]
3832 .SetMSectionIfUnset(transceiver->internal()->mid(),
3833 transceiver->internal()->mline_index());
Eldar Rello5ab79e62019-10-09 18:29:44 +03003834 }
3835 }
Steve Antondcc3c022017-12-22 16:02:54 -08003836 // Associate the found or created RtpTransceiver with the m= section by
3837 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3838 // section, and establish a mapping between the transceiver and the index of
3839 // the m= section.
3840 transceiver->internal()->set_mid(content.name);
3841 transceiver->internal()->set_mline_index(mline_index);
3842 return std::move(transceiver);
3843}
3844
3845rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3846PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3847 RTC_DCHECK(IsUnifiedPlan());
3848 for (auto transceiver : transceivers_) {
3849 if (transceiver->mid() == mid) {
3850 return transceiver;
3851 }
3852 }
3853 return nullptr;
3854}
3855
3856rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3857PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3858 RTC_DCHECK(IsUnifiedPlan());
3859 for (auto transceiver : transceivers_) {
3860 if (transceiver->internal()->mline_index() == mline_index) {
3861 return transceiver;
3862 }
3863 }
3864 return nullptr;
3865}
3866
3867rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3868PeerConnection::FindAvailableTransceiverToReceive(
3869 cricket::MediaType media_type) const {
3870 RTC_DCHECK(IsUnifiedPlan());
3871 // From JSEP section 5.10 (Applying a Remote Description):
3872 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3873 // the same type that were added to the PeerConnection by addTrack and are not
3874 // associated with any m= section and are not stopped, find the first such
3875 // RtpTransceiver.
3876 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003877 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003878 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3879 !transceiver->stopped()) {
3880 return transceiver;
3881 }
3882 }
3883 return nullptr;
3884}
3885
Steve Antoned10bd92017-12-05 10:52:59 -08003886const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3887 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3888 transceiver,
3889 const SessionDescriptionInterface* sdesc) const {
3890 RTC_DCHECK(transceiver);
3891 RTC_DCHECK(sdesc);
3892 if (IsUnifiedPlan()) {
3893 if (!transceiver->internal()->mid()) {
3894 // This transceiver is not associated with a media section yet.
3895 return nullptr;
3896 }
3897 return sdesc->description()->GetContentByName(
3898 *transceiver->internal()->mid());
3899 } else {
3900 // Plan B only allows at most one audio and one video section, so use the
3901 // first media section of that type.
3902 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003903 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003904 }
3905}
3906
deadbeef46c73892016-11-16 19:42:04 -08003907PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003908 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003909 return configuration_;
3910}
3911
Niels Möller2579f0c2019-08-19 09:58:17 +02003912RTCError PeerConnection::SetConfiguration(
3913 const RTCConfiguration& configuration) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003914 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003915 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003916 if (IsClosed()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003917 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
3918 "SetConfiguration: PeerConnection is closed.");
Steve Antonc79268f2018-04-24 09:54:10 -07003919 }
3920
Qingsi Wanga2d60672018-04-11 16:57:45 -07003921 // According to JSEP, after setLocalDescription, changing the candidate pool
3922 // size is not allowed, and changing the set of ICE servers will not result
3923 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003924 if (local_description() && configuration.ice_candidate_pool_size !=
3925 configuration_.ice_candidate_pool_size) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003926 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3927 "Can't change candidate pool size after calling "
3928 "SetLocalDescription.");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003929 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003930
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003931 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003932 configuration.crypto_options != configuration_.crypto_options) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003933 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3934 "Can't change crypto_options after calling "
3935 "SetLocalDescription.");
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003936 }
3937
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003938 if (local_description() && configuration.use_datagram_transport !=
3939 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003940 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3941 "Can't change use_datagram_transport "
3942 "after calling SetLocalDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003943 }
3944
3945 if (remote_description() && configuration.use_datagram_transport !=
3946 configuration_.use_datagram_transport) {
Niels Möller2579f0c2019-08-19 09:58:17 +02003947 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
3948 "Can't change use_datagram_transport "
3949 "after calling SetRemoteDescription.");
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003950 }
3951
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003952 if (local_description() &&
3953 configuration.use_datagram_transport_for_data_channels !=
3954 configuration_.use_datagram_transport_for_data_channels) {
3955 LOG_AND_RETURN_ERROR(
3956 RTCErrorType::INVALID_MODIFICATION,
3957 "Can't change use_datagram_transport_for_data_channels "
3958 "after calling SetLocalDescription.");
3959 }
3960
3961 if (remote_description() &&
3962 configuration.use_datagram_transport_for_data_channels !=
3963 configuration_.use_datagram_transport_for_data_channels) {
3964 LOG_AND_RETURN_ERROR(
3965 RTCErrorType::INVALID_MODIFICATION,
3966 "Can't change use_datagram_transport_for_data_channels "
3967 "after calling SetRemoteDescription.");
3968 }
3969
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003970 if (local_description() &&
3971 configuration.use_datagram_transport_for_data_channels_receive_only !=
3972 configuration_
3973 .use_datagram_transport_for_data_channels_receive_only) {
3974 LOG_AND_RETURN_ERROR(
3975 RTCErrorType::INVALID_MODIFICATION,
3976 "Can't change use_datagram_transport_for_data_channels_receive_only "
3977 "after calling SetLocalDescription.");
3978 }
3979
3980 if (remote_description() &&
3981 configuration.use_datagram_transport_for_data_channels_receive_only !=
3982 configuration_
3983 .use_datagram_transport_for_data_channels_receive_only) {
3984 LOG_AND_RETURN_ERROR(
3985 RTCErrorType::INVALID_MODIFICATION,
3986 "Can't change use_datagram_transport_for_data_channels_receive_only "
3987 "after calling SetRemoteDescription.");
3988 }
3989
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -08003990 if ((configuration.use_datagram_transport &&
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003991 *configuration.use_datagram_transport) ||
3992 (configuration.use_datagram_transport_for_data_channels &&
3993 *configuration.use_datagram_transport_for_data_channels)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003994 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3995 << "Media transport requires MaxBundle policy.";
3996 }
3997
deadbeef293e9262017-01-11 12:28:30 -08003998 // The simplest (and most future-compatible) way to tell if the config was
3999 // modified in an invalid way is to copy each property we do support
4000 // modifying, then use operator==. There are far more properties we don't
4001 // support modifying than those we do, and more could be added.
4002 RTCConfiguration modified_config = configuration_;
4003 modified_config.servers = configuration.servers;
4004 modified_config.type = configuration.type;
4005 modified_config.ice_candidate_pool_size =
4006 configuration.ice_candidate_pool_size;
4007 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004008 modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
Qingsi Wangbca14852019-06-26 14:56:02 -07004009 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
4010 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08004011 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08004012 modified_config.ice_check_interval_strong_connectivity =
4013 configuration.ice_check_interval_strong_connectivity;
4014 modified_config.ice_check_interval_weak_connectivity =
4015 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07004016 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
4017 modified_config.ice_unwritable_min_checks =
4018 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08004019 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004020 modified_config.stun_candidate_keepalive_interval =
4021 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004022 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004023 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07004024 modified_config.active_reset_srtp_params =
4025 configuration.active_reset_srtp_params;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004026 modified_config.use_datagram_transport = configuration.use_datagram_transport;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004027 modified_config.use_datagram_transport_for_data_channels =
4028 configuration.use_datagram_transport_for_data_channels;
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004029 modified_config.use_datagram_transport_for_data_channels_receive_only =
4030 configuration.use_datagram_transport_for_data_channels_receive_only;
Jonas Oreland3c028422019-08-22 16:16:35 +02004031 modified_config.turn_logging_id = configuration.turn_logging_id;
philipel16cec3b2019-10-25 12:23:02 +02004032 modified_config.allow_codec_switching = configuration.allow_codec_switching;
deadbeef293e9262017-01-11 12:28:30 -08004033 if (configuration != modified_config) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004034 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
4035 "Modifying the configuration in an unsupported way.");
deadbeef293e9262017-01-11 12:28:30 -08004036 }
4037
Steve Anton038834f2017-07-14 15:59:59 -07004038 // Validate the modified configuration.
4039 RTCError validate_error = ValidateConfiguration(modified_config);
4040 if (!validate_error.ok()) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004041 return validate_error;
Steve Anton038834f2017-07-14 15:59:59 -07004042 }
4043
deadbeef293e9262017-01-11 12:28:30 -08004044 // Note that this isn't possible through chromium, since it's an unsigned
4045 // short in WebIDL.
4046 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07004047 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004048 return RTCError(RTCErrorType::INVALID_RANGE);
deadbeef293e9262017-01-11 12:28:30 -08004049 }
4050
4051 // Parse ICE servers before hopping to network thread.
4052 cricket::ServerAddresses stun_servers;
4053 std::vector<cricket::RelayServerConfig> turn_servers;
4054 RTCErrorType parse_error =
4055 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
4056 if (parse_error != RTCErrorType::NONE) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004057 return RTCError(parse_error);
deadbeef293e9262017-01-11 12:28:30 -08004058 }
Jonas Oreland3c028422019-08-22 16:16:35 +02004059 // Add the turn logging id to all turn servers
4060 for (cricket::RelayServerConfig& turn_server : turn_servers) {
4061 turn_server.turn_logging_id = configuration.turn_logging_id;
4062 }
4063
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004064 // Note if STUN or TURN servers were supplied.
4065 if (!stun_servers.empty()) {
4066 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
4067 }
4068 if (!turn_servers.empty()) {
4069 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
4070 }
deadbeef293e9262017-01-11 12:28:30 -08004071
4072 // In theory this shouldn't fail.
4073 if (!network_thread()->Invoke<bool>(
4074 RTC_FROM_HERE,
4075 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
4076 stun_servers, turn_servers, modified_config.type,
4077 modified_config.ice_candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004078 modified_config.GetTurnPortPrunePolicy(),
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004079 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02004080 modified_config.stun_candidate_keepalive_interval,
4081 static_cast<bool>(local_description())))) {
Niels Möller2579f0c2019-08-19 09:58:17 +02004082 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4083 "Failed to apply configuration to PortAllocator.");
deadbeef293e9262017-01-11 12:28:30 -08004084 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004085
deadbeefd1a38b52016-12-10 13:15:33 -08004086 // As described in JSEP, calling setConfiguration with new ICE servers or
4087 // candidate policy must set a "needs-ice-restart" bit so that the next offer
4088 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08004089 if (modified_config.servers != configuration_.servers ||
4090 modified_config.type != configuration_.type ||
Honghai Zhangf8998cf2019-10-14 11:27:50 -07004091 modified_config.GetTurnPortPrunePolicy() !=
4092 configuration_.GetTurnPortPrunePolicy()) {
Steve Antond25da372017-11-06 14:50:29 -08004093 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08004094 }
skvladd1f5fda2017-02-03 16:54:05 -08004095
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08004096 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004097
4098 use_datagram_transport_ = datagram_transport_config_.enabled &&
4099 modified_config.use_datagram_transport.value_or(
4100 datagram_transport_config_.default_value);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004101 use_datagram_transport_for_data_channels_ =
4102 datagram_transport_data_channel_config_.enabled &&
4103 modified_config.use_datagram_transport_for_data_channels.value_or(
4104 datagram_transport_data_channel_config_.default_value);
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004105 use_datagram_transport_for_data_channels_receive_only_ =
4106 modified_config.use_datagram_transport_for_data_channels_receive_only
4107 .value_or(datagram_transport_data_channel_config_.receive_only);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08004108 transport_controller_->SetMediaTransportSettings(
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004109 use_datagram_transport_, use_datagram_transport_for_data_channels_,
4110 use_datagram_transport_for_data_channels_receive_only_);
skvladd1f5fda2017-02-03 16:54:05 -08004111
Zhi Huangb57e1692018-06-12 11:41:11 -07004112 if (configuration_.active_reset_srtp_params !=
4113 modified_config.active_reset_srtp_params) {
4114 transport_controller_->SetActiveResetSrtpParams(
4115 modified_config.active_reset_srtp_params);
4116 }
4117
philipel16cec3b2019-10-25 12:23:02 +02004118 if (modified_config.allow_codec_switching.has_value()) {
philipel01294f02019-11-14 13:03:25 +01004119 cricket::VideoMediaChannel* video_channel = video_media_channel();
4120 if (video_channel) {
4121 video_channel->SetVideoCodecSwitchingEnabled(
4122 *modified_config.allow_codec_switching);
4123 }
philipel16cec3b2019-10-25 12:23:02 +02004124 }
4125
deadbeef293e9262017-01-11 12:28:30 -08004126 configuration_ = modified_config;
Niels Möller2579f0c2019-08-19 09:58:17 +02004127 return RTCError::OK();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00004128}
4129
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004130bool PeerConnection::AddIceCandidate(
4131 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004132 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004133 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07004134 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004135 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004136 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07004137 return false;
4138 }
Steve Antond25da372017-11-06 14:50:29 -08004139
4140 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004141 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004142 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004143 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08004144 return false;
4145 }
4146
4147 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07004148 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004149 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08004150 return false;
4151 }
4152
4153 bool valid = false;
4154 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
4155 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004156 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08004157 return false;
4158 }
4159
4160 // Add this candidate to the remote session description.
4161 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07004162 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004163 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08004164 return false;
4165 }
4166
4167 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02004168 bool result = UseCandidate(ice_candidate);
4169 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004170 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02004171 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
4172 } else {
4173 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
4174 }
4175 return result;
Steve Antond25da372017-11-06 14:50:29 -08004176 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07004177 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02004178 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08004179 return true;
4180 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004181}
4182
Henrik Boströmee6f4f62019-11-06 12:36:12 +01004183void PeerConnection::AddIceCandidate(
4184 std::unique_ptr<IceCandidateInterface> candidate,
4185 std::function<void(RTCError)> callback) {
4186 RTC_DCHECK_RUN_ON(signaling_thread());
4187 // Chain this operation. If asynchronous operations are pending on the chain,
4188 // this operation will be queued to be invoked, otherwise the contents of the
4189 // lambda will execute immediately.
4190 operations_chain_->ChainOperation(
4191 [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(),
4192 candidate = std::move(candidate), callback = std::move(callback)](
4193 std::function<void()> operations_chain_callback) {
4194 if (!this_weak_ptr) {
4195 operations_chain_callback();
4196 callback(RTCError(
4197 RTCErrorType::INVALID_STATE,
4198 "AddIceCandidate failed because the session was shut down"));
4199 return;
4200 }
4201 if (!this_weak_ptr->AddIceCandidate(candidate.get())) {
4202 operations_chain_callback();
4203 // Fail with an error type and message consistent with Chromium.
4204 // TODO(hbos): Fail with error types according to spec.
4205 callback(RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
4206 "Error processing ICE candidate"));
4207 return;
4208 }
4209 operations_chain_callback();
4210 callback(RTCError::OK());
4211 });
4212}
4213
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004214bool PeerConnection::RemoveIceCandidates(
4215 const std::vector<cricket::Candidate>& candidates) {
4216 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004217 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07004218 if (IsClosed()) {
4219 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
4220 return false;
4221 }
4222
Steve Antond25da372017-11-06 14:50:29 -08004223 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004224 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
4225 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08004226 return false;
4227 }
4228
4229 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004230 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08004231 return false;
4232 }
4233
4234 size_t number_removed =
4235 mutable_remote_description()->RemoveCandidates(candidates);
4236 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004237 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07004238 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004239 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01004240 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08004241 }
4242
4243 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07004244 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
4245 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07004246 RTC_LOG(LS_ERROR)
4247 << "RemoveIceCandidates: Error when removing remote candidates: "
4248 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08004249 }
4250 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004251}
4252
Niels Möller0c4f7be2018-05-07 14:01:37 +02004253RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07004254 if (!worker_thread()->IsCurrent()) {
4255 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02004256 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07004257 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01004258 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07004259
Niels Möller0c4f7be2018-05-07 14:01:37 +02004260 const bool has_min = bitrate.min_bitrate_bps.has_value();
4261 const bool has_start = bitrate.start_bitrate_bps.has_value();
4262 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07004263 if (has_min && *bitrate.min_bitrate_bps < 0) {
4264 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4265 "min_bitrate_bps <= 0");
4266 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02004267 if (has_start) {
4268 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004269 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004270 "start_bitrate_bps < min_bitrate_bps");
4271 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07004272 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4273 "curent_bitrate_bps < 0");
4274 }
4275 }
4276 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02004277 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07004278 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02004279 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07004280 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
4281 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4282 "max_bitrate_bps < min_bitrate_bps");
4283 } else if (*bitrate.max_bitrate_bps < 0) {
4284 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4285 "max_bitrate_bps < 0");
4286 }
4287 }
4288
zstein4b979802017-06-02 14:37:37 -07004289 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07004290 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07004291
4292 return RTCError::OK();
4293}
4294
henrika5f6bf242017-11-01 11:06:56 +01004295void PeerConnection::SetAudioPlayout(bool playout) {
4296 if (!worker_thread()->IsCurrent()) {
4297 worker_thread()->Invoke<void>(
4298 RTC_FROM_HERE,
4299 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
4300 return;
4301 }
4302 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004303 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004304 audio_state->SetPlayout(playout);
4305}
4306
4307void PeerConnection::SetAudioRecording(bool recording) {
4308 if (!worker_thread()->IsCurrent()) {
4309 worker_thread()->Invoke<void>(
4310 RTC_FROM_HERE,
4311 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
4312 return;
4313 }
4314 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01004315 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01004316 audio_state->SetRecording(recording);
4317}
4318
Steve Anton8c0f7a72017-10-03 10:03:10 -07004319std::unique_ptr<rtc::SSLCertificate>
4320PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004321 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
4322 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07004323 return nullptr;
4324 }
Steve Antonf25303e2018-10-16 15:23:31 -07004325 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07004326}
4327
Zhi Huang70b820f2018-01-27 14:16:15 -08004328std::unique_ptr<rtc::SSLCertChain>
4329PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01004330 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08004331 auto audio_transceiver = GetFirstAudioTransceiver();
4332 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08004333 return nullptr;
4334 }
Zhi Huang70b820f2018-01-27 14:16:15 -08004335 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08004336 audio_transceiver->internal()->channel()->transport_name());
4337}
4338
4339rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4340PeerConnection::GetFirstAudioTransceiver() const {
4341 for (auto transceiver : transceivers_) {
4342 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4343 return transceiver;
4344 }
4345 }
4346 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08004347}
4348
Bjorn Tereliusde939432017-11-20 17:38:14 +01004349bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
4350 int64_t output_period_ms) {
Bjorn Tereliusde939432017-11-20 17:38:14 +01004351 return worker_thread()->Invoke<bool>(
Danil Chapovalov116ffe72019-09-05 10:21:11 +02004352 RTC_FROM_HERE,
4353 [this, output = std::move(output), output_period_ms]() mutable {
4354 return StartRtcEventLog_w(std::move(output), output_period_ms);
4355 });
ivoc14d5dbe2016-07-04 07:06:55 -07004356}
4357
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004358bool PeerConnection::StartRtcEventLog(
4359 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02004360 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
4361 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
4362 output_period_ms = 5000;
4363 }
4364 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02004365}
4366
ivoc14d5dbe2016-07-04 07:06:55 -07004367void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07004368 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07004369 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
4370}
4371
Harald Alvestrandad88c882018-11-28 16:47:46 +01004372rtc::scoped_refptr<DtlsTransportInterface>
4373PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004374 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01004375 return transport_controller_->LookupDtlsTransportByMid(mid);
4376}
4377
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004378rtc::scoped_refptr<DtlsTransport>
4379PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004380 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01004381 return transport_controller_->LookupDtlsTransportByMid(mid);
4382}
4383
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004384rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
4385 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02004386 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand7a829a82020-02-12 07:38:21 +01004387 if (!sctp_mid_s_) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004388 return nullptr;
4389 }
Harald Alvestrand7a829a82020-02-12 07:38:21 +01004390 return transport_controller_->GetSctpTransport(*sctp_mid_s_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01004391}
4392
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004393const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004394 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004395 return pending_local_description_ ? pending_local_description_.get()
4396 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004397}
4398
4399const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004400 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004401 return pending_remote_description_ ? pending_remote_description_.get()
4402 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004403}
4404
deadbeeffe4a8a42016-12-20 17:56:17 -08004405const SessionDescriptionInterface* PeerConnection::current_local_description()
4406 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004407 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004408 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004409}
4410
4411const SessionDescriptionInterface* PeerConnection::current_remote_description()
4412 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004413 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004414 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004415}
4416
4417const SessionDescriptionInterface* PeerConnection::pending_local_description()
4418 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004419 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004420 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004421}
4422
4423const SessionDescriptionInterface* PeerConnection::pending_remote_description()
4424 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02004425 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004426 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08004427}
4428
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004429void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01004430 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01004431 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004432 // Update stats here so that we have the most recent stats for tracks and
4433 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00004434 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004435
Steve Anton75737c02017-11-06 10:37:17 -08004436 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004437 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08004438
Mirko Bonadei739baf02019-01-27 17:29:42 +01004439 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08004440 transceiver->Stop();
4441 }
Steve Anton25cfeb92018-04-26 11:44:00 -07004442
4443 // Ensure that all asynchronous stats requests are completed before destroying
4444 // the transport controller below.
4445 if (stats_collector_) {
4446 stats_collector_->WaitForPendingRequest();
4447 }
4448
4449 // Don't destroy BaseChannels until after stats has been cleaned up so that
4450 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08004451 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08004452
Qingsi Wang93a84392018-01-30 17:13:09 -08004453 // The event log is used in the transport controller, which must be outlived
4454 // by the former. CreateOffer by the peer connection is implemented
4455 // asynchronously and if the peer connection is closed without resetting the
4456 // WebRTC session description factory, the session description factory would
4457 // call the transport controller.
4458 webrtc_session_desc_factory_.reset();
4459 transport_controller_.reset();
4460
deadbeef42a42632017-03-10 15:18:00 -08004461 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02004462 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
4463 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07004464
Steve Anton978b8762017-09-29 12:15:02 -07004465 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01004466 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07004467 call_.reset();
4468 // The event log must outlive call (and any other object that uses it).
4469 event_log_.reset();
4470 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004471 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004472 // The .h file says that observer can be discarded after close() returns.
4473 // Make sure this is true.
4474 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004475}
4476
Steve Antonad182762018-09-05 20:22:40 +00004477void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01004478 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00004479 switch (msg->message_id) {
4480 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
4481 SetSessionDescriptionMsg* param =
4482 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4483 param->observer->OnSuccess();
4484 delete param;
4485 break;
4486 }
4487 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
4488 SetSessionDescriptionMsg* param =
4489 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
4490 param->observer->OnFailure(std::move(param->error));
4491 delete param;
4492 break;
4493 }
4494 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
4495 CreateSessionDescriptionMsg* param =
4496 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
4497 param->observer->OnFailure(std::move(param->error));
4498 delete param;
4499 break;
4500 }
4501 case MSG_GETSTATS: {
4502 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4503 StatsReports reports;
4504 stats_->GetStats(param->track, &reports);
4505 param->observer->OnComplete(reports);
4506 delete param;
4507 break;
4508 }
Steve Antonad182762018-09-05 20:22:40 +00004509 case MSG_REPORT_USAGE_PATTERN: {
4510 ReportUsagePattern();
4511 break;
4512 }
4513 default:
4514 RTC_NOTREACHED() << "Not implemented";
4515 break;
4516 }
4517}
4518
Steve Antonafb0bb72018-02-20 11:35:37 -08004519cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4520 RTC_DCHECK(!IsUnifiedPlan());
4521 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4522 GetAudioTransceiver()->internal()->channel());
4523 if (voice_channel) {
4524 return voice_channel->media_channel();
4525 } else {
4526 return nullptr;
4527 }
4528}
4529
4530cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4531 RTC_DCHECK(!IsUnifiedPlan());
4532 auto* video_channel = static_cast<cricket::VideoChannel*>(
4533 GetVideoTransceiver()->internal()->channel());
4534 if (video_channel) {
4535 return video_channel->media_channel();
4536 } else {
4537 return nullptr;
4538 }
4539}
4540
Steve Anton4171afb2017-11-20 10:20:22 -08004541void PeerConnection::CreateAudioReceiver(
4542 MediaStreamInterface* stream,
4543 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004544 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4545 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004546 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4547 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004548 auto* audio_receiver = new AudioRtpReceiver(
4549 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004550 audio_receiver->SetMediaChannel(voice_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004551 if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
4552 audio_receiver->SetupUnsignaledMediaChannel();
4553 } else {
4554 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4555 }
Steve Antond3679212018-01-17 17:41:02 -08004556 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4557 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004558 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004559 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004560 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004561}
4562
Steve Anton4171afb2017-11-20 10:20:22 -08004563void PeerConnection::CreateVideoReceiver(
4564 MediaStreamInterface* stream,
4565 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004566 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4567 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004568 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4569 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004570 auto* video_receiver = new VideoRtpReceiver(
4571 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004572 video_receiver->SetMediaChannel(video_media_channel());
Saurav Das7262fc22019-09-11 16:23:05 -07004573 if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
4574 video_receiver->SetupUnsignaledMediaChannel();
4575 } else {
4576 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4577 }
Steve Antond3679212018-01-17 17:41:02 -08004578 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4579 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004580 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004581 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004582 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004583}
4584
deadbeef70ab1a12015-09-28 16:53:55 -07004585// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4586// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004587rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004588 const RtpSenderInfo& remote_sender_info) {
4589 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4590 if (!receiver) {
4591 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4592 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004593 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004594 }
Steve Anton4171afb2017-11-20 10:20:22 -08004595 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4596 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4597 } else {
4598 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4599 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004600 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004601}
4602
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004603void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4604 MediaStreamInterface* stream) {
4605 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004606 RTC_DCHECK(track);
4607 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004608 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004609 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004610 // We already have a sender for this track, so just change the stream_id
4611 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004612 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004613 return;
4614 }
4615
4616 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004617 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004618 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004619 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004620 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004621 // If the sender has already been configured in SDP, we call SetSsrc,
4622 // which will connect the sender to the underlying transport. This can
4623 // occur if a local session description that contains the ID of the sender
4624 // is set before AddStream is called. It can also occur if the local
4625 // session description is not changed and RemoveStream is called, and
4626 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004627 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004628 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004629 if (sender_info) {
4630 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004631 }
4632}
4633
4634// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4635// indefinitely, when we have unified plan SDP.
4636void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4637 MediaStreamInterface* stream) {
4638 RTC_DCHECK(!IsClosed());
4639 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004640 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004641 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4642 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004643 return;
4644 }
Steve Anton4171afb2017-11-20 10:20:22 -08004645 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004646}
4647
4648void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4649 MediaStreamInterface* stream) {
4650 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004651 RTC_DCHECK(track);
4652 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004653 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004654 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004655 // We already have a sender for this track, so just change the stream_id
4656 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004657 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004658 return;
4659 }
4660
4661 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004662 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004663 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004664 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004665 GetVideoTransceiver()->internal()->AddSender(new_sender);
4666 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004667 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004668 if (sender_info) {
4669 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004670 }
4671}
4672
4673void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4674 MediaStreamInterface* stream) {
4675 RTC_DCHECK(!IsClosed());
4676 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004677 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004678 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4679 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004680 return;
4681 }
Steve Anton4171afb2017-11-20 10:20:22 -08004682 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004683}
4684
Steve Antonba818672017-11-06 10:21:57 -08004685void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004686 if (ice_connection_state_ == new_state) {
4687 return;
4688 }
4689
deadbeefcbecd352015-09-23 11:50:27 -07004690 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004691 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004692 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004693 return;
4694 }
Steve Antonba818672017-11-06 10:21:57 -08004695
Mirko Bonadei675513b2017-11-09 11:09:25 +01004696 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4697 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004698 RTC_DCHECK(ice_connection_state_ !=
4699 PeerConnectionInterface::kIceConnectionClosed);
4700
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004701 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004702 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004703}
4704
Alex Loiko9289eda2018-11-23 16:18:59 +00004705void PeerConnection::SetStandardizedIceConnectionState(
4706 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004707 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004708 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004709 }
4710
4711 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004712 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004713 }
4714
4715 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4716 << standardized_ice_connection_state_ << " => " << new_state;
4717
Alex Loiko9289eda2018-11-23 16:18:59 +00004718 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004719 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004720}
4721
Jonas Olsson635474e2018-10-18 15:58:17 +02004722void PeerConnection::SetConnectionState(
4723 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004724 if (connection_state_ == new_state)
4725 return;
4726 if (IsClosed())
4727 return;
4728 connection_state_ = new_state;
4729 Observer()->OnConnectionChange(new_state);
4730}
4731
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004732void PeerConnection::OnIceGatheringChange(
4733 PeerConnectionInterface::IceGatheringState new_state) {
4734 if (IsClosed()) {
4735 return;
4736 }
4737 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004738 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004739}
4740
jbauch81bf7b02017-03-25 08:31:12 -07004741void PeerConnection::OnIceCandidate(
4742 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004743 if (IsClosed()) {
4744 return;
4745 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004746 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004747 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004748}
4749
Eldar Rello0095d372019-12-02 22:22:07 +02004750void PeerConnection::OnIceCandidateError(const std::string& address,
4751 int port,
Eldar Relloda13ea22019-06-01 12:23:43 +03004752 const std::string& url,
4753 int error_code,
4754 const std::string& error_text) {
4755 if (IsClosed()) {
4756 return;
4757 }
Eldar Rello0095d372019-12-02 22:22:07 +02004758 Observer()->OnIceCandidateError(address, port, url, error_code, error_text);
4759 // Leftover not to break wpt test during migration to the new API.
4760 Observer()->OnIceCandidateError(address + ":", url, error_code, error_text);
Eldar Relloda13ea22019-06-01 12:23:43 +03004761}
4762
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004763void PeerConnection::OnIceCandidatesRemoved(
4764 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004765 if (IsClosed()) {
4766 return;
4767 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004768 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004769}
4770
Alex Drake00c7ecf2019-08-06 10:54:47 -07004771void PeerConnection::OnSelectedCandidatePairChanged(
4772 const cricket::CandidatePairChangeEvent& event) {
4773 if (IsClosed()) {
4774 return;
4775 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004776
Qingsi Wangcc46b102019-09-12 11:19:01 -07004777 if (event.selected_candidate_pair.local_candidate().type() ==
4778 LOCAL_PORT_TYPE &&
4779 event.selected_candidate_pair.remote_candidate().type() ==
4780 LOCAL_PORT_TYPE) {
4781 NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
4782 }
4783
Alex Drake00c7ecf2019-08-06 10:54:47 -07004784 Observer()->OnIceSelectedCandidatePairChanged(event);
4785}
4786
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004787void PeerConnection::ChangeSignalingState(
4788 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004789 if (signaling_state_ == signaling_state) {
4790 return;
4791 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004792 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4793 << GetSignalingStateString(signaling_state_)
4794 << " New state: "
4795 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004796 signaling_state_ = signaling_state;
4797 if (signaling_state == kClosed) {
4798 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004799 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004800 standardized_ice_connection_state_ =
4801 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004802 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4803 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004804 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004805 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004806}
4807
deadbeefeb459812015-12-15 19:24:43 -08004808void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4809 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004810 if (IsClosed()) {
4811 return;
4812 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004813 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004814 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004815}
4816
deadbeefeb459812015-12-15 19:24:43 -08004817void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4818 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004819 if (IsClosed()) {
4820 return;
4821 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004822 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004823 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004824}
4825
4826void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4827 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004828 if (IsClosed()) {
4829 return;
4830 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004831 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004832 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004833}
4834
4835void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4836 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004837 if (IsClosed()) {
4838 return;
4839 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004840 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004841 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004842}
4843
Henrik Boström31638672017-11-23 17:48:32 +01004844void PeerConnection::PostSetSessionDescriptionSuccess(
4845 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004846 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4847 signaling_thread()->Post(RTC_FROM_HERE, this,
4848 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004849}
4850
deadbeefab9b2d12015-10-14 11:33:11 -07004851void PeerConnection::PostSetSessionDescriptionFailure(
4852 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004853 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004854 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004855 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4856 msg->error = std::move(error);
4857 signaling_thread()->Post(RTC_FROM_HERE, this,
4858 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004859}
4860
4861void PeerConnection::PostCreateSessionDescriptionFailure(
4862 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004863 RTCError error) {
4864 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004865 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4866 msg->error = std::move(error);
4867 signaling_thread()->Post(RTC_FROM_HERE, this,
4868 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004869}
4870
zhihuang1c378ed2017-08-17 14:10:50 -07004871void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004872 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004873 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004874 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004875
Steve Antondcc3c022017-12-22 16:02:54 -08004876 if (IsUnifiedPlan()) {
4877 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4878 } else {
4879 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4880 }
4881
Steve Antonfa2260d2017-12-28 16:38:23 -08004882 // Intentionally unset the data channel type for RTP data channel with the
4883 // second condition. Otherwise the RTP data channels would be successfully
4884 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4885 // when building with chromium. We want to leave RTP data channels broken, so
4886 // people won't try to use them.
Harald Alvestrand05e4d082019-12-03 14:04:21 +01004887 if (data_channel_controller_.HasRtpDataChannels() ||
4888 data_channel_type() != cricket::DCT_RTP) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004889 session_options->data_channel_type = data_channel_type();
4890 }
4891
Steve Antondcc3c022017-12-22 16:02:54 -08004892 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004893 bool ice_restart = offer_answer_options.ice_restart ||
4894 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004895 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004896 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004897 options.transport_options.enable_ice_renomination =
4898 configuration_.enable_ice_renomination;
4899 }
4900
4901 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004902 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004903 session_options->pooled_ice_credentials =
4904 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4905 RTC_FROM_HERE,
4906 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4907 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004908 session_options->offer_extmap_allow_mixed =
4909 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004910
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004911 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004912 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004913 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004914 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004915 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004916 if (!params) {
4917 continue;
4918 }
4919 options.transport_options.opaque_parameters = params;
4920 if ((use_datagram_transport_ &&
4921 (options.type == cricket::MEDIA_TYPE_AUDIO ||
4922 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
4923 (use_datagram_transport_for_data_channels_ &&
4924 options.type == cricket::MEDIA_TYPE_DATA)) {
4925 options.alt_protocol = params->protocol;
4926 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004927 }
4928 }
4929
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004930 // Allow fallback for using obsolete SCTP syntax.
4931 // Note that the default in |session_options| is true, while
4932 // the default in |options| is false.
4933 session_options->use_obsolete_sctp_sdp =
4934 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004935}
4936
4937void PeerConnection::GetOptionsForPlanBOffer(
4938 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4939 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004940 // Figure out transceiver directional preferences.
4941 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4942 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4943
4944 // By default, generate sendrecv/recvonly m= sections.
4945 bool recv_audio = true;
4946 bool recv_video = true;
4947
4948 // By default, only offer a new m= section if we have media to send with it.
4949 bool offer_new_audio_description = send_audio;
4950 bool offer_new_video_description = send_video;
Harald Alvestrand05e4d082019-12-03 14:04:21 +01004951 bool offer_new_data_description = data_channel_controller_.HasDataChannels();
zhihuang1c378ed2017-08-17 14:10:50 -07004952
4953 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004954 if (offer_answer_options.offer_to_receive_audio !=
4955 RTCOfferAnswerOptions::kUndefined) {
4956 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004957 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004958 offer_new_audio_description ||
4959 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004960 }
Steve Antondcc3c022017-12-22 16:02:54 -08004961 if (offer_answer_options.offer_to_receive_video !=
4962 RTCOfferAnswerOptions::kUndefined) {
4963 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004964 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004965 offer_new_video_description ||
4966 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004967 }
4968
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004969 absl::optional<size_t> audio_index;
4970 absl::optional<size_t> video_index;
4971 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004972 // If a current description exists, generate m= sections in the same order,
4973 // using the first audio/video/data section that appears and rejecting
4974 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004975 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004976 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004977 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004978 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4979 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4980 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004981 }
4982
zhihuang1c378ed2017-08-17 14:10:50 -07004983 // Add audio/video/data m= sections to the end if needed.
4984 if (!audio_index && offer_new_audio_description) {
4985 session_options->media_description_options.push_back(
4986 cricket::MediaDescriptionOptions(
4987 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004988 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4989 false));
Markus Handell0357b3e2020-03-16 13:40:51 +01004990
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004991 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004992 }
zhihuang1c378ed2017-08-17 14:10:50 -07004993 if (!video_index && offer_new_video_description) {
4994 session_options->media_description_options.push_back(
4995 cricket::MediaDescriptionOptions(
4996 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004997 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4998 false));
Markus Handell0357b3e2020-03-16 13:40:51 +01004999
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005000 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07005001 }
zhihuang1c378ed2017-08-17 14:10:50 -07005002 if (!data_index && offer_new_data_description) {
5003 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005004 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005005 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005006 }
5007
5008 cricket::MediaDescriptionOptions* audio_media_description_options =
5009 !audio_index ? nullptr
5010 : &session_options->media_description_options[*audio_index];
5011 cricket::MediaDescriptionOptions* video_media_description_options =
5012 !video_index ? nullptr
5013 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005014
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005015 AddPlanBRtpSenderOptions(GetSendersInternal(),
5016 audio_media_description_options,
5017 video_media_description_options,
5018 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005019}
5020
Steve Antondcc3c022017-12-22 16:02:54 -08005021static cricket::MediaDescriptionOptions
5022GetMediaDescriptionOptionsForTransceiver(
5023 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5024 transceiver,
5025 const std::string& mid) {
5026 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08005027 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08005028 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02005029 media_description_options.codec_preferences =
5030 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08005031 // This behavior is specified in JSEP. The gist is that:
5032 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
5033 // sendrecv.
5034 // 2. If the MSID is included, then it must be included in any subsequent
5035 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005036 if (transceiver->stopped() ||
5037 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
5038 !transceiver->internal()->has_ever_been_used_to_send())) {
5039 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08005040 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005041
5042 cricket::SenderOptions sender_options;
5043 sender_options.track_id = transceiver->sender()->id();
5044 sender_options.stream_ids = transceiver->sender()->stream_ids();
5045
5046 // The following sets up RIDs and Simulcast.
5047 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08005048 RtpParameters send_parameters =
5049 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005050 bool has_rids = std::any_of(send_parameters.encodings.begin(),
5051 send_parameters.encodings.end(),
5052 [](const RtpEncodingParameters& encoding) {
5053 return !encoding.rid.empty();
5054 });
5055
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08005056 std::vector<RidDescription> send_rids;
5057 SimulcastLayerList send_layers;
5058 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
5059 if (encoding.rid.empty()) {
5060 continue;
5061 }
5062 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
5063 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
5064 }
5065
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005066 if (has_rids) {
5067 sender_options.rids = send_rids;
5068 }
5069
5070 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08005071 // When RIDs are configured, we must set num_sim_layers to 0 to.
5072 // Otherwise, num_sim_layers must be 1 because either there is no
5073 // simulcast, or simulcast is acheived by munging the SDP.
5074 sender_options.num_sim_layers = has_rids ? 0 : 1;
5075 media_description_options.sender_options.push_back(sender_options);
5076
Steve Antondcc3c022017-12-22 16:02:54 -08005077 return media_description_options;
5078}
5079
Steve Anton5c72e712018-12-10 14:25:30 -08005080// Returns the ContentInfo at mline index |i|, or null if none exists.
5081static const ContentInfo* GetContentByIndex(
5082 const SessionDescriptionInterface* sdesc,
5083 size_t i) {
5084 if (!sdesc) {
5085 return nullptr;
5086 }
5087 const ContentInfos& contents = sdesc->description()->contents();
5088 return (i < contents.size() ? &contents[i] : nullptr);
5089}
5090
Steve Antondcc3c022017-12-22 16:02:54 -08005091void PeerConnection::GetOptionsForUnifiedPlanOffer(
5092 const RTCOfferAnswerOptions& offer_answer_options,
5093 cricket::MediaSessionOptions* session_options) {
5094 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
5095 // Offers) and 5.2.2 (Subsequent Offers).
5096 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02005097 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08005098 const ContentInfos& local_contents =
5099 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005100 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005101 const ContentInfos& remote_contents =
5102 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02005103 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08005104 // The mline indices that can be recycled. New transceivers should reuse these
5105 // slots first.
5106 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08005107 // First, go through each media section that exists in either the local or
5108 // remote description and generate a media section in this offer for the
5109 // associated transceiver. If a media section can be recycled, generate a
5110 // default, rejected media section here that can be later overwritten.
5111 for (size_t i = 0;
5112 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
5113 // Either |local_content| or |remote_content| is non-null.
5114 const ContentInfo* local_content =
5115 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005116 const ContentInfo* current_local_content =
5117 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08005118 const ContentInfo* remote_content =
5119 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08005120 const ContentInfo* current_remote_content =
5121 GetContentByIndex(current_remote_description(), i);
5122 bool had_been_rejected =
5123 (current_local_content && current_local_content->rejected) ||
5124 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08005125 const std::string& mid =
5126 (local_content ? local_content->name : remote_content->name);
5127 cricket::MediaType media_type =
5128 (local_content ? local_content->media_description()->type()
5129 : remote_content->media_description()->type());
5130 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5131 media_type == cricket::MEDIA_TYPE_VIDEO) {
5132 auto transceiver = GetAssociatedTransceiver(mid);
5133 RTC_CHECK(transceiver);
5134 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08005135 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005136 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08005137 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08005138 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
5139 RtpTransceiverDirection::kInactive,
5140 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08005141 recycleable_mline_indices.push(i);
5142 } else {
5143 session_options->media_description_options.push_back(
5144 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
5145 // CreateOffer shouldn't really cause any state changes in
5146 // PeerConnection, but we need a way to match new transceivers to new
5147 // media sections in SetLocalDescription and JSEP specifies this is done
5148 // by recording the index of the media section generated for the
5149 // transceiver in the offer.
5150 transceiver->internal()->set_mline_index(i);
5151 }
5152 } else {
5153 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonc8ff1602020-02-05 13:53:38 -08005154 if (had_been_rejected) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005155 session_options->media_description_options.push_back(
5156 GetMediaDescriptionOptionsForRejectedData(mid));
5157 } else {
Steve Antonc8ff1602020-02-05 13:53:38 -08005158 RTC_CHECK(GetDataMid());
5159 if (mid == *GetDataMid()) {
5160 session_options->media_description_options.push_back(
5161 GetMediaDescriptionOptionsForActiveData(mid));
5162 } else {
5163 session_options->media_description_options.push_back(
5164 GetMediaDescriptionOptionsForRejectedData(mid));
5165 }
Steve Antonfa2260d2017-12-28 16:38:23 -08005166 }
Steve Antondcc3c022017-12-22 16:02:54 -08005167 }
5168 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08005169
Steve Antondcc3c022017-12-22 16:02:54 -08005170 // Next, look for transceivers that are newly added (that is, are not stopped
5171 // and not associated). Reuse media sections marked as recyclable first,
5172 // otherwise append to the end of the offer. New media sections should be
5173 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005174 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08005175 if (transceiver->mid() || transceiver->stopped()) {
5176 continue;
5177 }
5178 size_t mline_index;
5179 if (!recycleable_mline_indices.empty()) {
5180 mline_index = recycleable_mline_indices.front();
5181 recycleable_mline_indices.pop();
5182 session_options->media_description_options[mline_index] =
5183 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005184 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08005185 } else {
5186 mline_index = session_options->media_description_options.size();
5187 session_options->media_description_options.push_back(
5188 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08005189 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08005190 }
5191 // See comment above for why CreateOffer changes the transceiver's state.
5192 transceiver->internal()->set_mline_index(mline_index);
5193 }
Steve Antonfa2260d2017-12-28 16:38:23 -08005194 // Lastly, add a m-section if we have local data channels and an m section
5195 // does not already exist.
Harald Alvestrand05e4d082019-12-03 14:04:21 +01005196 if (!GetDataMid() && data_channel_controller_.HasDataChannels()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005197 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08005198 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08005199 }
Steve Antondcc3c022017-12-22 16:02:54 -08005200}
5201
5202void PeerConnection::GetOptionsForAnswer(
5203 const RTCOfferAnswerOptions& offer_answer_options,
5204 cricket::MediaSessionOptions* session_options) {
5205 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
5206
5207 if (IsUnifiedPlan()) {
5208 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
5209 } else {
5210 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
5211 }
5212
Steve Antonfa2260d2017-12-28 16:38:23 -08005213 // Intentionally unset the data channel type for RTP data channel. Otherwise
5214 // the RTP data channels would be successfully negotiated by default and the
5215 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
5216 // We want to leave RTP data channels broken, so people won't try to use them.
Harald Alvestrand05e4d082019-12-03 14:04:21 +01005217 if (data_channel_controller_.HasRtpDataChannels() ||
5218 data_channel_type() != cricket::DCT_RTP) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005219 session_options->data_channel_type = data_channel_type();
5220 }
5221
Steve Antondcc3c022017-12-22 16:02:54 -08005222 // Apply ICE renomination flag.
5223 for (auto& options : session_options->media_description_options) {
5224 options.transport_options.enable_ice_renomination =
5225 configuration_.enable_ice_renomination;
5226 }
zhihuang8f65cdf2016-05-06 18:40:30 -07005227
5228 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005229 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02005230 session_options->pooled_ice_credentials =
5231 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
5232 RTC_FROM_HERE,
5233 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
5234 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005235
5236 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005237 if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005238 for (auto& options : session_options->media_description_options) {
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005239 absl::optional<cricket::OpaqueTransportParameters> params =
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005240 transport_controller_->GetTransportParameters(options.mid);
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07005241 if (!params) {
5242 continue;
5243 }
5244 options.transport_options.opaque_parameters = params;
5245 if ((use_datagram_transport_ &&
5246 (options.type == cricket::MEDIA_TYPE_AUDIO ||
5247 options.type == cricket::MEDIA_TYPE_VIDEO)) ||
5248 (use_datagram_transport_for_data_channels_ &&
5249 options.type == cricket::MEDIA_TYPE_DATA)) {
5250 options.alt_protocol = params->protocol;
5251 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07005252 }
5253 }
deadbeefab9b2d12015-10-14 11:33:11 -07005254}
5255
Steve Antondcc3c022017-12-22 16:02:54 -08005256void PeerConnection::GetOptionsForPlanBAnswer(
5257 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07005258 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005259 // Figure out transceiver directional preferences.
5260 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
5261 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
5262
5263 // By default, generate sendrecv/recvonly m= sections. The direction is also
5264 // restricted by the direction in the offer.
5265 bool recv_audio = true;
5266 bool recv_video = true;
5267
5268 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08005269 if (offer_answer_options.offer_to_receive_audio !=
5270 RTCOfferAnswerOptions::kUndefined) {
5271 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08005272 }
Steve Antondcc3c022017-12-22 16:02:54 -08005273 if (offer_answer_options.offer_to_receive_video !=
5274 RTCOfferAnswerOptions::kUndefined) {
5275 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07005276 }
5277
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005278 absl::optional<size_t> audio_index;
5279 absl::optional<size_t> video_index;
5280 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08005281
5282 // Generate m= sections that match those in the offer.
5283 // Note that mediasession.cc will handle intersection our preferred
5284 // direction with the offered direction.
5285 GenerateMediaDescriptionOptions(
5286 remote_description(),
5287 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
5288 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
5289 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07005290
5291 cricket::MediaDescriptionOptions* audio_media_description_options =
5292 !audio_index ? nullptr
5293 : &session_options->media_description_options[*audio_index];
5294 cricket::MediaDescriptionOptions* video_media_description_options =
5295 !video_index ? nullptr
5296 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07005297
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08005298 AddPlanBRtpSenderOptions(GetSendersInternal(),
5299 audio_media_description_options,
5300 video_media_description_options,
5301 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08005302}
zhihuangaf388472016-11-02 16:49:48 -07005303
Steve Antondcc3c022017-12-22 16:02:54 -08005304void PeerConnection::GetOptionsForUnifiedPlanAnswer(
5305 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
5306 cricket::MediaSessionOptions* session_options) {
5307 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
5308 // Answers) and 5.3.2 (Subsequent Answers).
5309 RTC_DCHECK(remote_description());
5310 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
5311 for (const ContentInfo& content :
5312 remote_description()->description()->contents()) {
5313 cricket::MediaType media_type = content.media_description()->type();
5314 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
5315 media_type == cricket::MEDIA_TYPE_VIDEO) {
5316 auto transceiver = GetAssociatedTransceiver(content.name);
5317 RTC_CHECK(transceiver);
5318 session_options->media_description_options.push_back(
5319 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
5320 } else {
5321 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08005322 // Reject all data sections if data channels are disabled.
5323 // Reject a data section if it has already been rejected.
5324 // Reject all data sections except for the first one.
Harald Alvestrand05e4d082019-12-03 14:04:21 +01005325 if (data_channel_type() == cricket::DCT_NONE || content.rejected ||
Steve Antondbf9d032018-01-19 15:23:40 -08005326 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005327 session_options->media_description_options.push_back(
5328 GetMediaDescriptionOptionsForRejectedData(content.name));
5329 } else {
5330 session_options->media_description_options.push_back(
5331 GetMediaDescriptionOptionsForActiveData(content.name));
5332 }
Steve Antondcc3c022017-12-22 16:02:54 -08005333 }
5334 }
htaa2a49d92016-03-04 02:51:39 -08005335}
5336
zhihuang1c378ed2017-08-17 14:10:50 -07005337void PeerConnection::GenerateMediaDescriptionOptions(
5338 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08005339 RtpTransceiverDirection audio_direction,
5340 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005341 absl::optional<size_t>* audio_index,
5342 absl::optional<size_t>* video_index,
5343 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08005344 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07005345 for (const cricket::ContentInfo& content :
5346 session_desc->description()->contents()) {
5347 if (IsAudioContent(&content)) {
5348 // If we already have an audio m= section, reject this extra one.
5349 if (*audio_index) {
5350 session_options->media_description_options.push_back(
5351 cricket::MediaDescriptionOptions(
5352 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005353 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005354 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005355 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005356 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005357 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
5358 content.name, audio_direction,
5359 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005360 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005361 }
5362 } else if (IsVideoContent(&content)) {
5363 // If we already have an video m= section, reject this extra one.
5364 if (*video_index) {
5365 session_options->media_description_options.push_back(
5366 cricket::MediaDescriptionOptions(
5367 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08005368 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07005369 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08005370 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07005371 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08005372 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
5373 content.name, video_direction,
5374 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005375 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005376 }
5377 } else {
5378 RTC_DCHECK(IsDataContent(&content));
5379 // If we already have an data m= section, reject this extra one.
5380 if (*data_index) {
5381 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005382 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07005383 } else {
5384 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08005385 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005386 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07005387 }
5388 }
htaa2a49d92016-03-04 02:51:39 -08005389 }
deadbeefab9b2d12015-10-14 11:33:11 -07005390}
5391
Steve Antonfa2260d2017-12-28 16:38:23 -08005392cricket::MediaDescriptionOptions
5393PeerConnection::GetMediaDescriptionOptionsForActiveData(
5394 const std::string& mid) const {
5395 // Direction for data sections is meaningless, but legacy endpoints might
5396 // expect sendrecv.
5397 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5398 RtpTransceiverDirection::kSendRecv,
5399 /*stopped=*/false);
Harald Alvestrand05e4d082019-12-03 14:04:21 +01005400 AddRtpDataChannelOptions(*data_channel_controller_.rtp_data_channels(),
5401 &options);
Steve Antonfa2260d2017-12-28 16:38:23 -08005402 return options;
5403}
5404
5405cricket::MediaDescriptionOptions
5406PeerConnection::GetMediaDescriptionOptionsForRejectedData(
5407 const std::string& mid) const {
5408 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
5409 RtpTransceiverDirection::kInactive,
5410 /*stopped=*/true);
Harald Alvestrand05e4d082019-12-03 14:04:21 +01005411 AddRtpDataChannelOptions(*data_channel_controller_.rtp_data_channels(),
5412 &options);
Steve Antonfa2260d2017-12-28 16:38:23 -08005413 return options;
5414}
5415
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005416absl::optional<std::string> PeerConnection::GetDataMid() const {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01005417 switch (data_channel_type()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08005418 case cricket::DCT_RTP:
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01005419 if (!data_channel_controller_.rtp_data_channel()) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005420 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005421 }
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01005422 return data_channel_controller_.rtp_data_channel()->content_name();
Steve Antonfa2260d2017-12-28 16:38:23 -08005423 case cricket::DCT_SCTP:
Bjorn A Mellemb689af42019-08-21 10:44:59 -07005424 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
5425 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Harald Alvestrand7a829a82020-02-12 07:38:21 +01005426 return sctp_mid_s_;
Steve Antonfa2260d2017-12-28 16:38:23 -08005427 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005428 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08005429 }
5430}
5431
Steve Anton4171afb2017-11-20 10:20:22 -08005432void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
5433 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
5434 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08005435 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08005436}
5437
Steve Anton4171afb2017-11-20 10:20:22 -08005438void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07005439 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08005440 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07005441 cricket::MediaType media_type,
5442 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005443 RTC_DCHECK(!IsUnifiedPlan());
5444
Steve Anton4171afb2017-11-20 10:20:22 -08005445 std::vector<RtpSenderInfo>* current_senders =
5446 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005447
Steve Anton4171afb2017-11-20 10:20:22 -08005448 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08005449 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005450 for (auto sender_it = current_senders->begin();
5451 sender_it != current_senders->end();
5452 /* incremented manually */) {
5453 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005454 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005455 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07005456 std::string params_stream_id;
5457 if (params) {
5458 params_stream_id =
5459 (!params->first_stream_id().empty() ? params->first_stream_id()
5460 : kDefaultStreamId);
5461 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07005462 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07005463 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08005464 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08005465 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08005466 sender_exists) {
5467 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08005468 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005469 OnRemoteSenderRemoved(info, media_type);
5470 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005471 }
5472 }
5473
Steve Anton4171afb2017-11-20 10:20:22 -08005474 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005475 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07005476 if (!params.has_ssrcs()) {
5477 // The remote endpoint has streams, but didn't signal ssrcs. For an active
5478 // sender, this means it is coming from a Unified Plan endpoint,so we just
5479 // create a default.
5480 default_sender_needed = true;
5481 break;
5482 }
5483
Seth Hampson845e8782018-03-02 11:34:10 -08005484 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07005485 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07005486 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
5487 // not supported in Plan B, we just take the first here and create the
5488 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08005489 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07005490 (!params.first_stream_id().empty() ? params.first_stream_id()
5491 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08005492 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005493 uint32_t ssrc = params.first_ssrc();
5494
5495 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005496 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005497 if (!stream) {
5498 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005499 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08005500 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07005501 remote_streams_->AddStream(stream);
5502 new_streams->AddStream(stream);
5503 }
5504
Steve Anton4171afb2017-11-20 10:20:22 -08005505 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005506 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005507 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005508 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005509 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005510 }
5511 }
deadbeefbda7e0b2015-12-08 17:13:40 -08005512
Steve Anton4171afb2017-11-20 10:20:22 -08005513 // Add default sender if necessary.
5514 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08005515 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08005516 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08005517 if (!default_stream) {
5518 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07005519 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08005520 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08005521 remote_streams_->AddStream(default_stream);
5522 new_streams->AddStream(default_stream);
5523 }
Steve Anton4171afb2017-11-20 10:20:22 -08005524 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
5525 ? kDefaultAudioSenderId
5526 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08005527 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005528 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005529 if (!default_sender_info) {
5530 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01005531 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08005532 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08005533 }
5534 }
deadbeefab9b2d12015-10-14 11:33:11 -07005535}
5536
Steve Anton4171afb2017-11-20 10:20:22 -08005537void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5538 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005539 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5540 << " receiver for track_id=" << sender_info.sender_id
5541 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005542
Steve Anton3d954a62018-04-02 11:27:23 -07005543 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005544 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005545 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005546 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005547 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005548 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005549 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005550 }
5551}
5552
Steve Anton4171afb2017-11-20 10:20:22 -08005553void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5554 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005555 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5556 << " receiver for track_id=" << sender_info.sender_id
5557 << " and stream_id=" << sender_info.stream_id;
5558
Seth Hampson845e8782018-03-02 11:34:10 -08005559 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005560
Henrik Boström933d8b02017-10-10 10:05:16 -07005561 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005562 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005563 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5564 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005565 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005566 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005567 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005568 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005569 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005570 }
5571 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005572 // Stopping or destroying a VideoRtpReceiver will end the
5573 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005574 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005575 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005576 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005577 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005578 // There's no guarantee the track is still available, e.g. the track may
5579 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005580 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005581 }
5582 } else {
nisseede5da42017-01-12 05:15:36 -08005583 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005584 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005585 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005586 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005587 }
deadbeefab9b2d12015-10-14 11:33:11 -07005588}
5589
5590void PeerConnection::UpdateEndedRemoteMediaStreams() {
5591 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5592 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5593 MediaStreamInterface* stream = remote_streams_->at(i);
5594 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5595 streams_to_remove.push_back(stream);
5596 }
5597 }
5598
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005599 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005600 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005601 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005602 }
5603}
5604
Steve Anton4171afb2017-11-20 10:20:22 -08005605void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005606 const std::vector<cricket::StreamParams>& streams,
5607 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005608 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005609
Seth Hampson845e8782018-03-02 11:34:10 -08005610 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005611 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005612 for (auto sender_it = current_senders->begin();
5613 sender_it != current_senders->end();
5614 /* incremented manually */) {
5615 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005616 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005617 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5618 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005619 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005620 OnLocalSenderRemoved(info, media_type);
5621 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005622 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005623 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005624 }
5625 }
5626
Steve Anton4171afb2017-11-20 10:20:22 -08005627 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005628 for (const cricket::StreamParams& params : streams) {
5629 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005630 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005631 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005632 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005633 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005634 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005635 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005636 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005637 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005638 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005639 }
5640 }
5641}
5642
Steve Anton4171afb2017-11-20 10:20:22 -08005643void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5644 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005645 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005646 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005647 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005648 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5649 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005650 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005651 return;
5652 }
5653
deadbeeffac06552015-11-25 11:26:01 -08005654 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005655 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005656 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005657 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005658 }
deadbeeffac06552015-11-25 11:26:01 -08005659
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005660 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005661 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005662}
5663
Steve Anton4171afb2017-11-20 10:20:22 -08005664void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5665 cricket::MediaType media_type) {
5666 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005667 if (!sender) {
5668 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005669 // SessionDescriptions has been renegotiated.
5670 return;
5671 }
deadbeeffac06552015-11-25 11:26:01 -08005672
5673 // A sender has been removed from the SessionDescription but it's still
5674 // associated with the PeerConnection. This only occurs if the SDP doesn't
5675 // match with the calls to CreateSender, AddStream and RemoveStream.
5676 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005677 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005678 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005679 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005680 }
deadbeeffac06552015-11-25 11:26:01 -08005681
Steve Anton4171afb2017-11-20 10:20:22 -08005682 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005683}
5684
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01005685void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
5686 // Since data_channel_controller doesn't do signals, this
5687 // signal is relayed here.
5688 data_channel_controller_.OnSctpDataChannelClosed(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005689}
5690
Steve Anton4171afb2017-11-20 10:20:22 -08005691rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5692PeerConnection::GetAudioTransceiver() const {
5693 // This method only works with Plan B SDP, where there is a single
5694 // audio/video transceiver.
5695 RTC_DCHECK(!IsUnifiedPlan());
5696 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005697 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005698 return transceiver;
5699 }
5700 }
5701 RTC_NOTREACHED();
5702 return nullptr;
5703}
5704
5705rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5706PeerConnection::GetVideoTransceiver() const {
5707 // This method only works with Plan B SDP, where there is a single
5708 // audio/video transceiver.
5709 RTC_DCHECK(!IsUnifiedPlan());
5710 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005711 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005712 return transceiver;
5713 }
5714 }
5715 RTC_NOTREACHED();
5716 return nullptr;
5717}
5718
5719// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5720// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005721bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005722 switch (type) {
5723 case cricket::MEDIA_TYPE_AUDIO:
5724 return !GetAudioTransceiver()->internal()->senders().empty();
5725 case cricket::MEDIA_TYPE_VIDEO:
5726 return !GetVideoTransceiver()->internal()->senders().empty();
5727 case cricket::MEDIA_TYPE_DATA:
5728 return false;
5729 }
5730 RTC_NOTREACHED();
5731 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005732}
5733
Steve Anton4171afb2017-11-20 10:20:22 -08005734rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5735PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005736 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005737 for (auto sender : transceiver->internal()->senders()) {
5738 if (sender->track() == track) {
5739 return sender;
5740 }
5741 }
5742 }
5743 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005744}
5745
Steve Anton4171afb2017-11-20 10:20:22 -08005746rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5747PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005748 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005749 for (auto sender : transceiver->internal()->senders()) {
5750 if (sender->id() == sender_id) {
5751 return sender;
5752 }
5753 }
5754 }
5755 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005756}
5757
Steve Anton4171afb2017-11-20 10:20:22 -08005758rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5759PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005760 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005761 for (auto receiver : transceiver->internal()->receivers()) {
5762 if (receiver->id() == receiver_id) {
5763 return receiver;
5764 }
5765 }
5766 }
5767 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005768}
5769
Steve Anton4171afb2017-11-20 10:20:22 -08005770std::vector<PeerConnection::RtpSenderInfo>*
5771PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5772 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5773 media_type == cricket::MEDIA_TYPE_VIDEO);
5774 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5775 ? &remote_audio_sender_infos_
5776 : &remote_video_sender_infos_;
5777}
5778
5779std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005780 cricket::MediaType media_type) {
5781 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5782 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005783 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5784 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005785}
5786
Steve Anton4171afb2017-11-20 10:20:22 -08005787const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5788 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005789 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005790 const std::string sender_id) const {
5791 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005792 if (sender_info.stream_id == stream_id &&
5793 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005794 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005795 }
5796 }
5797 return nullptr;
5798}
5799
5800DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01005801 return data_channel_controller_.FindDataChannelBySid(sid);
deadbeefab9b2d12015-10-14 11:33:11 -07005802}
5803
Karl Wibergfb3be392019-03-22 14:13:22 +01005804PeerConnection::InitializePortAllocatorResult
5805PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005806 const cricket::ServerAddresses& stun_servers,
5807 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005808 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005809 RTC_DCHECK_RUN_ON(network_thread());
5810
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005811 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005812 // To handle both internal and externally created port allocator, we will
5813 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005814 int port_allocator_flags = port_allocator_->flags();
5815 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5816 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5817 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005818 // If the disable-IPv6 flag was specified, we'll not override it
5819 // by experiment.
5820 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005821 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005822 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5823 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005824 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005825 }
5826
zhihuangb09b3f92017-03-07 14:40:51 -08005827 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005828 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005829 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005830 }
5831
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005832 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005833 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005834 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005835 }
5836
honghaiz60347052016-05-31 18:29:12 -07005837 if (configuration.candidate_network_policy ==
5838 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005839 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005840 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005841 }
5842
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005843 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005844 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005845 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5846 }
5847
Karl Wibergfb3be392019-03-22 14:13:22 +01005848 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005849 // No step delay is used while allocating ports.
5850 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005851 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005852 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005853 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005854
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005855 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005856 for (auto& turn_server : turn_servers_copy) {
5857 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005858 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005859 // Call this last since it may create pooled allocator sessions using the
5860 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005861 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005862 stun_servers, std::move(turn_servers_copy),
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005863 configuration.ice_candidate_pool_size,
5864 configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005865 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005866
5867 InitializePortAllocatorResult res;
5868 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5869 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005870}
5871
deadbeef91dd5672016-05-18 16:55:30 -07005872bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005873 const cricket::ServerAddresses& stun_servers,
5874 const std::vector<cricket::RelayServerConfig>& turn_servers,
5875 IceTransportsType type,
5876 int candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005877 PortPrunePolicy turn_port_prune_policy,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005878 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005879 absl::optional<int> stun_candidate_keepalive_interval,
5880 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005881 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005882 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005883 // According to JSEP, after setLocalDescription, changing the candidate pool
5884 // size is not allowed, and changing the set of ICE servers will not result
5885 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005886 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005887 port_allocator_->FreezeCandidatePool();
5888 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005889 // Add the custom tls turn servers if they exist.
5890 auto turn_servers_copy = turn_servers;
5891 for (auto& turn_server : turn_servers_copy) {
5892 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5893 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005894 // Call this last since it may create pooled allocator sessions using the
5895 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005896 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005897 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
Honghai Zhangf8998cf2019-10-14 11:27:50 -07005898 turn_port_prune_policy, turn_customizer,
5899 stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005900}
5901
Steve Antonba818672017-11-06 10:21:57 -08005902cricket::ChannelManager* PeerConnection::channel_manager() const {
5903 return factory_->channel_manager();
5904}
5905
Elad Alon99c3fe52017-10-13 16:29:40 +02005906bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005907 std::unique_ptr<RtcEventLogOutput> output,
5908 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005909 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005910 if (!event_log_) {
5911 return false;
5912 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005913 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005914}
5915
5916void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005917 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005918 if (event_log_) {
5919 event_log_->StopLogging();
5920 }
ivoc14d5dbe2016-07-04 07:06:55 -07005921}
nisseeaabdf62017-05-05 02:23:02 -07005922
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005923cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005924 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005925 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005926 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005927 if (channel && channel->content_name() == content_name) {
5928 return channel;
5929 }
Steve Anton75737c02017-11-06 10:37:17 -08005930 }
5931 if (rtp_data_channel() &&
5932 rtp_data_channel()->content_name() == content_name) {
5933 return rtp_data_channel();
5934 }
5935 return nullptr;
5936}
5937
5938bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005939 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005940 if (!local_description() || !remote_description()) {
Harald Alvestrand977b2652019-12-12 13:40:50 +01005941 RTC_LOG(LS_VERBOSE)
Mirko Bonadei675513b2017-11-09 11:09:25 +01005942 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005943 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005944 return false;
5945 }
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01005946 if (!data_channel_controller_.data_channel_transport()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005947 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005948 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005949 return false;
5950 }
5951
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005952 absl::optional<rtc::SSLRole> dtls_role;
Harald Alvestrand7a829a82020-02-12 07:38:21 +01005953 if (sctp_mid_s_) {
5954 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_s_);
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07005955 if (!dtls_role && is_caller_.has_value()) {
5956 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5957 }
Zhi Huange830e682018-03-30 10:48:35 -07005958 *role = *dtls_role;
5959 return true;
5960 }
5961 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005962}
5963
5964bool PeerConnection::GetSslRole(const std::string& content_name,
5965 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005966 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005967 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005968 RTC_LOG(LS_INFO)
5969 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005970 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005971 return false;
5972 }
5973
Zhi Huange830e682018-03-30 10:48:35 -07005974 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5975 if (dtls_role) {
5976 *role = *dtls_role;
5977 return true;
5978 }
5979 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005980}
5981
Steve Antonf8470812017-12-04 10:46:21 -08005982void PeerConnection::SetSessionError(SessionError error,
5983 const std::string& error_desc) {
5984 RTC_DCHECK_RUN_ON(signaling_thread());
5985 if (error != session_error_) {
5986 session_error_ = error;
5987 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005988 }
5989}
5990
Zhi Huange830e682018-03-30 10:48:35 -07005991RTCError PeerConnection::UpdateSessionState(
5992 SdpType type,
5993 cricket::ContentSource source,
5994 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005995 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005996
5997 // If there's already a pending error then no state transition should happen.
5998 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005999 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006000
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006001 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08006002 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08006003 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006004 }
6005
6006 // Update the signaling state according to the specified state machine (see
6007 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08006008 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006009 ChangeSignalingState(source == cricket::CS_LOCAL
6010 ? PeerConnectionInterface::kHaveLocalOffer
6011 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08006012 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006013 ChangeSignalingState(source == cricket::CS_LOCAL
6014 ? PeerConnectionInterface::kHaveLocalPrAnswer
6015 : PeerConnectionInterface::kHaveRemotePrAnswer);
6016 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006017 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006018 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Rello5ab79e62019-10-09 18:29:44 +03006019 transceiver_stable_states_by_transceivers_.clear();
Eldar Rellod9ebe012020-03-18 20:41:45 +02006020 have_pending_rtp_data_channel_ = false;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006021 }
6022
6023 // Update internal objects according to the session description's media
6024 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07006025 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006026 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08006027 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08006028 }
6029
Steve Anton8a006912017-12-04 15:25:56 -08006030 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006031}
6032
Steve Anton8a006912017-12-04 15:25:56 -08006033RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08006034 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08006035 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08006036 const SessionDescriptionInterface* sdesc =
6037 (source == cricket::CS_LOCAL ? local_description()
6038 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08006039 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08006040
6041 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01006042 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08006043 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08006044 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006045 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006046 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08006047 continue;
6048 }
6049 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006050 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006051 if (!content_desc) {
6052 continue;
6053 }
6054 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02006055 bool success = (source == cricket::CS_LOCAL)
6056 ? channel->SetLocalContent(content_desc, type, &error)
6057 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006058 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006059 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006060 }
6061 }
6062
6063 // If using the RtpDataChannel, push down the new SDP section for it too.
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006064 if (data_channel_controller_.rtp_data_channel()) {
Steve Antoned10bd92017-12-05 10:52:59 -08006065 const ContentInfo* data_content =
6066 cricket::GetFirstDataContent(sdesc->description());
6067 if (data_content && !data_content->rejected) {
6068 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08006069 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08006070 if (data_desc) {
6071 std::string error;
6072 bool success =
6073 (source == cricket::CS_LOCAL)
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006074 ? data_channel_controller_.rtp_data_channel()->SetLocalContent(
6075 data_desc, type, &error)
6076 : data_channel_controller_.rtp_data_channel()->SetRemoteContent(
6077 data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08006078 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01006079 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08006080 }
Steve Anton75737c02017-11-06 10:37:17 -08006081 }
6082 }
6083 }
Steve Antoned10bd92017-12-05 10:52:59 -08006084
Steve Anton75737c02017-11-06 10:37:17 -08006085 // Need complete offer/answer with an SCTP m= section before starting SCTP,
6086 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006087 if (sctp_mid_s_ && local_description() && remote_description()) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006088 rtc::scoped_refptr<SctpTransport> sctp_transport =
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006089 transport_controller_->GetSctpTransport(*sctp_mid_s_);
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006090 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
6091 local_description()->description());
6092 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
6093 remote_description()->description());
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006094 if (sctp_transport && local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02006095 int max_message_size;
6096 // A remote max message size of zero means "any size supported".
6097 // We configure the connection with our own max message size.
6098 if (remote_sctp_description->max_message_size() == 0) {
6099 max_message_size = local_sctp_description->max_message_size();
6100 } else {
6101 max_message_size =
6102 std::min(local_sctp_description->max_message_size(),
6103 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02006104 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006105 sctp_transport->Start(local_sctp_description->port(),
6106 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08006107 }
Steve Anton75737c02017-11-06 10:37:17 -08006108 }
Steve Antoned10bd92017-12-05 10:52:59 -08006109
Steve Anton8a006912017-12-04 15:25:56 -08006110 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006111}
6112
Steve Anton8a006912017-12-04 15:25:56 -08006113RTCError PeerConnection::PushdownTransportDescription(
6114 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08006115 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08006116 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006117
Zhi Huange830e682018-03-30 10:48:35 -07006118 if (source == cricket::CS_LOCAL) {
6119 const SessionDescriptionInterface* sdesc = local_description();
6120 RTC_DCHECK(sdesc);
6121 return transport_controller_->SetLocalDescription(type,
6122 sdesc->description());
6123 } else {
6124 const SessionDescriptionInterface* sdesc = remote_description();
6125 RTC_DCHECK(sdesc);
6126 return transport_controller_->SetRemoteDescription(type,
6127 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08006128 }
Steve Anton75737c02017-11-06 10:37:17 -08006129}
6130
6131bool PeerConnection::GetTransportDescription(
6132 const SessionDescription* description,
6133 const std::string& content_name,
6134 cricket::TransportDescription* tdesc) {
6135 if (!description || !tdesc) {
6136 return false;
6137 }
6138 const TransportInfo* transport_info =
6139 description->GetTransportInfoByName(content_name);
6140 if (!transport_info) {
6141 return false;
6142 }
6143 *tdesc = transport_info->description;
6144 return true;
6145}
6146
Steve Anton75737c02017-11-06 10:37:17 -08006147cricket::IceConfig PeerConnection::ParseIceConfig(
6148 const PeerConnectionInterface::RTCConfiguration& config) const {
6149 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08006150 switch (config.continual_gathering_policy) {
6151 case PeerConnectionInterface::GATHER_ONCE:
6152 gathering_policy = cricket::GATHER_ONCE;
6153 break;
6154 case PeerConnectionInterface::GATHER_CONTINUALLY:
6155 gathering_policy = cricket::GATHER_CONTINUALLY;
6156 break;
6157 default:
6158 RTC_NOTREACHED();
6159 gathering_policy = cricket::GATHER_ONCE;
6160 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006161
Steve Anton75737c02017-11-06 10:37:17 -08006162 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07006163 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
6164 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08006165 ice_config.prioritize_most_likely_candidate_pairs =
6166 config.prioritize_most_likely_ice_candidate_pairs;
6167 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07006168 RTCConfigurationToIceConfigOptionalInt(
6169 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08006170 ice_config.continual_gathering_policy = gathering_policy;
6171 ice_config.presume_writable_when_fully_relayed =
6172 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006173 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
6174 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08006175 ice_config.ice_check_interval_strong_connectivity =
6176 config.ice_check_interval_strong_connectivity;
6177 ice_config.ice_check_interval_weak_connectivity =
6178 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08006179 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08006180 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
6181 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08006182 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08006183 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08006184 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08006185 return ice_config;
6186}
6187
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006188absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006189 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006190 if (sctp_mid_s_ && transport_controller_) {
6191 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_s_);
Zhi Huange830e682018-03-30 10:48:35 -07006192 if (dtls_transport) {
6193 return dtls_transport->transport_name();
6194 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006195 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006196 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006197 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006198}
6199
Qingsi Wang72a43a12018-02-20 16:03:18 -08006200cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6201 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006202 network_thread()->Invoke<void>(
6203 RTC_FROM_HERE,
6204 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6205 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006206 return candidate_states_list;
6207}
6208
Steve Anton5dfde182018-02-06 10:34:40 -08006209std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6210 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006211 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006212 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006213 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006214 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006215 if (channel) {
6216 transport_names_by_mid[channel->content_name()] =
6217 channel->transport_name();
6218 }
Steve Anton75737c02017-11-06 10:37:17 -08006219 }
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006220 if (data_channel_controller_.rtp_data_channel()) {
6221 transport_names_by_mid[data_channel_controller_.rtp_data_channel()
6222 ->content_name()] =
6223 data_channel_controller_.rtp_data_channel()->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006224 }
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006225 if (data_channel_controller_.data_channel_transport()) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006226 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006227 RTC_DCHECK(transport_name);
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006228 transport_names_by_mid[*sctp_mid_s_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006229 }
Steve Anton5dfde182018-02-06 10:34:40 -08006230 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006231}
6232
Steve Anton5dfde182018-02-06 10:34:40 -08006233std::map<std::string, cricket::TransportStats>
6234PeerConnection::GetTransportStatsByNames(
6235 const std::set<std::string>& transport_names) {
6236 if (!network_thread()->IsCurrent()) {
6237 return network_thread()
6238 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6239 RTC_FROM_HERE,
6240 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006241 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006242 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006243 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6244 for (const std::string& transport_name : transport_names) {
6245 cricket::TransportStats transport_stats;
6246 bool success =
6247 transport_controller_->GetStats(transport_name, &transport_stats);
6248 if (success) {
6249 transport_stats_by_name[transport_name] = std::move(transport_stats);
6250 } else {
6251 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6252 << transport_name;
6253 }
6254 }
6255 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006256}
6257
6258bool PeerConnection::GetLocalCertificate(
6259 const std::string& transport_name,
6260 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006261 if (!certificate) {
6262 return false;
6263 }
6264 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6265 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006266}
6267
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006268std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006269 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006270 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006271}
6272
6273cricket::DataChannelType PeerConnection::data_channel_type() const {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01006274 return data_channel_controller_.data_channel_type();
Steve Anton75737c02017-11-06 10:37:17 -08006275}
6276
6277bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006278 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006279 return pending_ice_restarts_.find(content_name) !=
6280 pending_ice_restarts_.end();
6281}
6282
Steve Anton75737c02017-11-06 10:37:17 -08006283bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6284 return transport_controller_->NeedsIceRestart(content_name);
6285}
6286
6287void PeerConnection::OnCertificateReady(
6288 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6289 transport_controller_->SetLocalCertificate(certificate);
6290}
6291
6292void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006293 SetSessionError(SessionError::kTransport,
6294 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006295}
6296
Alex Loiko9289eda2018-11-23 16:18:59 +00006297void PeerConnection::OnTransportControllerConnectionState(
6298 cricket::IceConnectionState state) {
6299 switch (state) {
6300 case cricket::kIceConnectionConnecting:
6301 // If the current state is Connected or Completed, then there were
6302 // writable channels but now there are not, so the next state must
6303 // be Disconnected.
6304 // kIceConnectionConnecting is currently used as the default,
6305 // un-connected state by the TransportController, so its only use is
6306 // detecting disconnections.
6307 if (ice_connection_state_ ==
6308 PeerConnectionInterface::kIceConnectionConnected ||
6309 ice_connection_state_ ==
6310 PeerConnectionInterface::kIceConnectionCompleted) {
6311 SetIceConnectionState(
6312 PeerConnectionInterface::kIceConnectionDisconnected);
6313 }
6314 break;
6315 case cricket::kIceConnectionFailed:
6316 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6317 break;
6318 case cricket::kIceConnectionConnected:
6319 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6320 "all transports are writable.";
6321 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6322 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6323 break;
6324 case cricket::kIceConnectionCompleted:
6325 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6326 "all transports are complete.";
6327 if (ice_connection_state_ !=
6328 PeerConnectionInterface::kIceConnectionConnected) {
6329 // If jumping directly from "checking" to "connected",
6330 // signal "connected" first.
6331 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6332 }
6333 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6334 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6335 ReportTransportStats();
6336 break;
6337 default:
6338 RTC_NOTREACHED();
6339 }
6340}
6341
Steve Anton75737c02017-11-06 10:37:17 -08006342void PeerConnection::OnTransportControllerCandidatesGathered(
6343 const std::string& transport_name,
6344 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006345 int sdp_mline_index;
6346 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006347 RTC_LOG(LS_ERROR)
6348 << "OnTransportControllerCandidatesGathered: content name "
6349 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006350 return;
6351 }
6352
6353 for (cricket::Candidates::const_iterator citer = candidates.begin();
6354 citer != candidates.end(); ++citer) {
6355 // Use transport_name as the candidate media id.
6356 std::unique_ptr<JsepIceCandidate> candidate(
6357 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6358 if (local_description()) {
6359 mutable_local_description()->AddCandidate(candidate.get());
6360 }
6361 OnIceCandidate(std::move(candidate));
6362 }
6363}
6364
Eldar Relloda13ea22019-06-01 12:23:43 +03006365void PeerConnection::OnTransportControllerCandidateError(
6366 const cricket::IceCandidateErrorEvent& event) {
Eldar Rello0095d372019-12-02 22:22:07 +02006367 OnIceCandidateError(event.address, event.port, event.url, event.error_code,
Eldar Relloda13ea22019-06-01 12:23:43 +03006368 event.error_text);
6369}
6370
Steve Anton75737c02017-11-06 10:37:17 -08006371void PeerConnection::OnTransportControllerCandidatesRemoved(
6372 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006373 // Sanity check.
6374 for (const cricket::Candidate& candidate : candidates) {
6375 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006376 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006377 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006378 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006379 return;
6380 }
6381 }
6382
6383 if (local_description()) {
6384 mutable_local_description()->RemoveCandidates(candidates);
6385 }
6386 OnIceCandidatesRemoved(candidates);
6387}
6388
Alex Drake00c7ecf2019-08-06 10:54:47 -07006389void PeerConnection::OnTransportControllerCandidateChanged(
6390 const cricket::CandidatePairChangeEvent& event) {
6391 OnSelectedCandidatePairChanged(event);
6392}
6393
Steve Anton75737c02017-11-06 10:37:17 -08006394void PeerConnection::OnTransportControllerDtlsHandshakeError(
6395 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006396 RTC_HISTOGRAM_ENUMERATION(
6397 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6398 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006399}
6400
Steve Antoned10bd92017-12-05 10:52:59 -08006401void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006402 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006403 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006404 if (channel && !channel->enabled()) {
6405 channel->Enable(true);
6406 }
Steve Anton75737c02017-11-06 10:37:17 -08006407 }
6408
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006409 if (data_channel_controller_.rtp_data_channel() &&
6410 !data_channel_controller_.rtp_data_channel()->enabled()) {
6411 data_channel_controller_.rtp_data_channel()->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006412 }
Steve Anton75737c02017-11-06 10:37:17 -08006413}
6414
6415// Returns the media index for a local ice candidate given the content name.
6416bool PeerConnection::GetLocalCandidateMediaIndex(
6417 const std::string& content_name,
6418 int* sdp_mline_index) {
6419 if (!local_description() || !sdp_mline_index) {
6420 return false;
6421 }
6422
6423 bool content_found = false;
6424 const ContentInfos& contents = local_description()->description()->contents();
6425 for (size_t index = 0; index < contents.size(); ++index) {
6426 if (contents[index].name == content_name) {
6427 *sdp_mline_index = static_cast<int>(index);
6428 content_found = true;
6429 break;
6430 }
6431 }
6432 return content_found;
6433}
6434
6435bool PeerConnection::UseCandidatesInSessionDescription(
6436 const SessionDescriptionInterface* remote_desc) {
6437 if (!remote_desc) {
6438 return true;
6439 }
6440 bool ret = true;
6441
6442 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6443 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6444 for (size_t n = 0; n < candidates->count(); ++n) {
6445 const IceCandidateInterface* candidate = candidates->at(n);
6446 bool valid = false;
6447 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6448 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006449 RTC_LOG(LS_INFO)
6450 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006451 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006452 }
6453 continue;
6454 }
6455 ret = UseCandidate(candidate);
6456 if (!ret) {
6457 break;
6458 }
6459 }
6460 }
6461 return ret;
6462}
6463
6464bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006465 RTCErrorOr<const cricket::ContentInfo*> result =
6466 FindContentInfo(remote_description(), candidate);
6467 if (!result.ok()) {
6468 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6469 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006470 return false;
6471 }
Steve Anton75737c02017-11-06 10:37:17 -08006472 std::vector<cricket::Candidate> candidates;
6473 candidates.push_back(candidate->candidate());
6474 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006475 RTCError error = transport_controller_->AddRemoteCandidates(
6476 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006477 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006478 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006479 // Candidates successfully submitted for checking.
6480 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6481 ice_connection_state_ ==
6482 PeerConnectionInterface::kIceConnectionDisconnected) {
6483 // If state is New, then the session has just gotten its first remote ICE
6484 // candidates, so go to Checking.
6485 // If state is Disconnected, the session is re-using old candidates or
6486 // receiving additional ones, so go to Checking.
6487 // If state is Connected, stay Connected.
6488 // TODO(bemasc): If state is Connected, and the new candidates are for a
6489 // newly added transport, then the state actually _should_ move to
6490 // checking. Add a way to distinguish that case.
6491 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6492 }
6493 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006494 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006495 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006496 }
6497 return true;
6498}
6499
Guido Urdaneta41633172019-05-23 20:12:29 +02006500RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6501 const SessionDescriptionInterface* description,
6502 const IceCandidateInterface* candidate) {
6503 if (candidate->sdp_mline_index() >= 0) {
6504 size_t mediacontent_index =
6505 static_cast<size_t>(candidate->sdp_mline_index());
6506 size_t content_size = description->description()->contents().size();
6507 if (mediacontent_index < content_size) {
6508 return &description->description()->contents()[mediacontent_index];
6509 } else {
6510 return RTCError(RTCErrorType::INVALID_RANGE,
6511 "Media line index (" +
6512 rtc::ToString(candidate->sdp_mline_index()) +
6513 ") out of range (number of mlines: " +
6514 rtc::ToString(content_size) + ").");
6515 }
6516 } else if (!candidate->sdp_mid().empty()) {
6517 auto& contents = description->description()->contents();
6518 auto it = absl::c_find_if(
6519 contents, [candidate](const cricket::ContentInfo& content_info) {
6520 return content_info.mid() == candidate->sdp_mid();
6521 });
6522 if (it == contents.end()) {
6523 return RTCError(
6524 RTCErrorType::INVALID_PARAMETER,
6525 "Mid " + candidate->sdp_mid() +
6526 " specified but no media section with that mid found.");
6527 } else {
6528 return &*it;
6529 }
6530 }
6531
6532 return RTCError(RTCErrorType::INVALID_PARAMETER,
6533 "Neither sdp_mline_index nor sdp_mid specified.");
6534}
6535
Steve Anton75737c02017-11-06 10:37:17 -08006536void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006537 // Destroy video channel first since it may have a pointer to the
6538 // voice channel.
6539 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006540 if (!video_info || video_info->rejected) {
6541 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006542 }
6543
Steve Anton6fec8802017-12-04 10:37:29 -08006544 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6545 if (!audio_info || audio_info->rejected) {
6546 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006547 }
6548
6549 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6550 if (!data_info || data_info->rejected) {
Harald Alvestrand408cb4b2019-11-16 12:09:08 +01006551 DestroyDataChannelTransport();
Steve Anton75737c02017-11-06 10:37:17 -08006552 }
6553}
6554
Steve Antondcc3c022017-12-22 16:02:54 -08006555RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6556 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006557 const cricket::ContentGroup* bundle_group = nullptr;
6558 if (configuration_.bundle_policy ==
6559 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006560 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006561 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006562 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6563 "max-bundle configured but session description "
6564 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006565 }
6566 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006567 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006568}
6569
6570RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006571 // Creating the media channels. Transports should already have been created
6572 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006573 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006574 if (voice && !voice->rejected &&
6575 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006576 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006577 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006578 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6579 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006580 }
6581 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6582 }
6583
Steve Antondcc3c022017-12-22 16:02:54 -08006584 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006585 if (video && !video->rejected &&
6586 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006587 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006588 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006589 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6590 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006591 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006592 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006593 }
6594
Steve Antondcc3c022017-12-22 16:02:54 -08006595 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Harald Alvestrand05e4d082019-12-03 14:04:21 +01006596 if (data_channel_type() != cricket::DCT_NONE && data && !data->rejected &&
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006597 !data_channel_controller_.rtp_data_channel() &&
6598 !data_channel_controller_.data_channel_transport()) {
Zhi Huange830e682018-03-30 10:48:35 -07006599 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006600 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6601 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006602 }
6603 }
6604
Steve Anton8a006912017-12-04 15:25:56 -08006605 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006606}
6607
Steve Anton4171afb2017-11-20 10:20:22 -08006608// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006609cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006610 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006611 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006612 MediaTransportConfig media_transport_config =
6613 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006614
Steve Anton75737c02017-11-06 10:37:17 -08006615 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006616 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006617 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6618 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006619 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006620 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006621 }
Steve Anton75737c02017-11-06 10:37:17 -08006622 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6623 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006624 voice_channel->SignalSentPacket.connect(this,
6625 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006626 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006627
Steve Antoneda6ccd2017-12-04 10:21:55 -08006628 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006629}
6630
Steve Anton4171afb2017-11-20 10:20:22 -08006631// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006632cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006633 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006634 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006635 MediaTransportConfig media_transport_config =
6636 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006637
Steve Anton75737c02017-11-06 10:37:17 -08006638 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006639 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006640 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6641 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006642 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006643 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006644 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006645 }
Steve Anton75737c02017-11-06 10:37:17 -08006646 video_channel->SignalDtlsSrtpSetupFailure.connect(
6647 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006648 video_channel->SignalSentPacket.connect(this,
6649 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006650 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006651
Steve Antoneda6ccd2017-12-04 10:21:55 -08006652 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006653}
6654
Zhi Huange830e682018-03-30 10:48:35 -07006655bool PeerConnection::CreateDataChannel(const std::string& mid) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01006656 switch (data_channel_type()) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006657 case cricket::DCT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006658 case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
Qingsi Wang437077d2019-09-10 17:52:26 +00006659 case cricket::DCT_DATA_CHANNEL_TRANSPORT:
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006660 if (network_thread()->Invoke<bool>(
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006661 RTC_FROM_HERE,
6662 rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
6663 mid))) {
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006664 sctp_mid_s_ = mid;
6665 } else {
Qingsi Wang437077d2019-09-10 17:52:26 +00006666 return false;
6667 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006668
6669 // All non-RTP data channels must initialize |sctp_data_channels_|.
Harald Alvestrand05e4d082019-12-03 14:04:21 +01006670 for (const auto& channel :
6671 *data_channel_controller_.sctp_data_channels()) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006672 channel->OnTransportChannelCreated();
6673 }
6674 return true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006675 case cricket::DCT_RTP:
6676 default:
6677 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006678 data_channel_controller_.set_rtp_data_channel(
6679 channel_manager()->CreateRtpDataChannel(
6680 configuration_.media_config, rtp_transport, signaling_thread(),
6681 mid, SrtpRequired(), GetCryptoOptions(), &ssrc_generator_));
6682 if (!data_channel_controller_.rtp_data_channel()) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006683 return false;
6684 }
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006685 data_channel_controller_.rtp_data_channel()
6686 ->SignalDtlsSrtpSetupFailure.connect(
6687 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6688 data_channel_controller_.rtp_data_channel()->SignalSentPacket.connect(
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006689 this, &PeerConnection::OnSentPacket_w);
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006690 data_channel_controller_.rtp_data_channel()->SetRtpTransport(
6691 rtp_transport);
Eldar Rellod9ebe012020-03-18 20:41:45 +02006692 have_pending_rtp_data_channel_ = true;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006693 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006694 }
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006695 return false;
Steve Anton75737c02017-11-06 10:37:17 -08006696}
6697
6698Call::Stats PeerConnection::GetCallStats() {
6699 if (!worker_thread()->IsCurrent()) {
6700 return worker_thread()->Invoke<Call::Stats>(
6701 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6702 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006703 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006704 if (call_) {
6705 return call_->GetStats();
6706 } else {
6707 return Call::Stats();
6708 }
6709}
6710
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006711bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006712 DataChannelTransportInterface* transport =
6713 transport_controller_->GetDataChannelTransport(mid);
6714 if (!transport) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006715 RTC_LOG(LS_ERROR)
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006716 << "Data channel transport is not available for data channels, mid="
6717 << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006718 return false;
6719 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006720 RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006721
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006722 data_channel_controller_.set_data_channel_transport(transport);
6723 data_channel_controller_.SetupDataChannelTransport_n();
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006724 sctp_mid_n_ = mid;
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07006725
6726 // Note: setting the data sink and checking initial state must be done last,
6727 // after setting up the data channel. Setting the data sink may trigger
6728 // callbacks to PeerConnection which require the transport to be completely
6729 // set up (eg. OnReadyToSend()).
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006730 transport->SetDataSink(&data_channel_controller_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006731 return true;
6732}
6733
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006734void PeerConnection::TeardownDataChannelTransport_n() {
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006735 if (!sctp_mid_n_ && !data_channel_controller_.data_channel_transport()) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006736 return;
6737 }
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006738 RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006739 << *sctp_mid_n_;
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006740
Bjorn A Mellemb689af42019-08-21 10:44:59 -07006741 // |sctp_mid_| may still be active through an SCTP transport. If not, unset
6742 // it.
Harald Alvestrand7a829a82020-02-12 07:38:21 +01006743 sctp_mid_n_.reset();
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01006744 data_channel_controller_.TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006745}
6746
Steve Anton75737c02017-11-06 10:37:17 -08006747// Returns false if bundle is enabled and rtcp_mux is disabled.
6748bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6749 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6750 if (!bundle_enabled)
6751 return true;
6752
6753 const cricket::ContentGroup* bundle_group =
6754 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6755 RTC_DCHECK(bundle_group != NULL);
6756
6757 const cricket::ContentInfos& contents = desc->contents();
6758 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6759 citer != contents.end(); ++citer) {
6760 const cricket::ContentInfo* content = (&*citer);
6761 RTC_DCHECK(content != NULL);
6762 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006763 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006764 if (!HasRtcpMuxEnabled(content))
6765 return false;
6766 }
6767 }
6768 // RTCP-MUX is enabled in all the contents.
6769 return true;
6770}
6771
6772bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006773 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006774}
6775
Steve Anton06817cd2018-12-18 15:55:30 -08006776static RTCError ValidateMids(const cricket::SessionDescription& description) {
6777 std::set<std::string> mids;
6778 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006779 if (content.name.empty()) {
6780 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6781 "A media section is missing a MID attribute.");
6782 }
Steve Anton06817cd2018-12-18 15:55:30 -08006783 if (!mids.insert(content.name).second) {
6784 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6785 "Duplicate a=mid value '" + content.name + "'.");
6786 }
6787 }
6788 return RTCError::OK();
6789}
6790
Steve Anton8a006912017-12-04 15:25:56 -08006791RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006792 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006793 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006794 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006795 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006796 }
6797
6798 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006799 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006800 }
6801
Steve Anton3828c062017-12-06 10:34:51 -08006802 SdpType type = sdesc->GetType();
6803 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6804 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006805 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006806 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006807 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006808 }
6809
Steve Anton06817cd2018-12-18 15:55:30 -08006810 RTCError error = ValidateMids(*sdesc->description());
6811 if (!error.ok()) {
6812 return error;
6813 }
6814
Steve Anton75737c02017-11-06 10:37:17 -08006815 // Verify crypto settings.
6816 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006817 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6818 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006819 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006820 if (!crypto_error.ok()) {
6821 return crypto_error;
6822 }
Steve Anton75737c02017-11-06 10:37:17 -08006823 }
6824
6825 // Verify ice-ufrag and ice-pwd.
6826 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006827 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6828 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006829 }
6830
6831 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006832 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6833 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006834 }
6835
6836 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6837 // m-lines that do not rtcp-mux enabled.
6838
6839 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006840 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006841 // With an answer we want to compare the new answer session description with
6842 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006843 const cricket::SessionDescription* offer_desc =
6844 (source == cricket::CS_LOCAL) ? remote_description()->description()
6845 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006846 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6847 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6848 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6850 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006851 }
6852 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006853 // The re-offers should respect the order of m= sections in current
6854 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006855 // With a re-offer, either the current local or current remote descriptions
6856 // could be the most up to date, so we would like to check against both of
6857 // them if they exist. It could be the case that one of them has a 0 port
6858 // for a media section, but the other does not. This is important to check
6859 // against in the case that we are recycling an m= section.
6860 const cricket::SessionDescription* current_desc = nullptr;
6861 const cricket::SessionDescription* secondary_current_desc = nullptr;
6862 if (local_description()) {
6863 current_desc = local_description()->description();
6864 if (remote_description()) {
6865 secondary_current_desc = remote_description()->description();
6866 }
6867 } else if (remote_description()) {
6868 current_desc = remote_description()->description();
6869 }
Steve Anton75737c02017-11-06 10:37:17 -08006870 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006871 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6872 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006873 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6874 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006875 }
6876 }
6877
Steve Antonba42e992018-04-09 14:10:01 -07006878 if (IsUnifiedPlan()) {
6879 // Ensure that each audio and video media section has at most one
6880 // "StreamParams". This will return an error if receiving a session
6881 // description from a "Plan B" endpoint which adds multiple tracks of the
6882 // same type. With Unified Plan, there can only be at most one track per
6883 // media section.
6884 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006885 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006886 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6887 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6888 desc.streams().size() > 1u) {
6889 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6890 "Media section has more than one track specified "
6891 "with a=ssrc lines which is not supported with "
6892 "Unified Plan.");
6893 }
6894 }
6895 }
6896
Steve Anton8a006912017-12-04 15:25:56 -08006897 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006898}
6899
Steve Anton3828c062017-12-06 10:34:51 -08006900bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006901 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006902 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006903 return (state == PeerConnectionInterface::kStable) ||
6904 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006905 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006906 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006907 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6908 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6909 }
6910}
6911
Steve Anton3828c062017-12-06 10:34:51 -08006912bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006913 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006914 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006915 return (state == PeerConnectionInterface::kStable) ||
6916 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006917 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006918 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006919 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6920 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6921 }
6922}
6923
Steve Antonf8470812017-12-04 10:46:21 -08006924const char* PeerConnection::SessionErrorToString(SessionError error) const {
6925 switch (error) {
6926 case SessionError::kNone:
6927 return "ERROR_NONE";
6928 case SessionError::kContent:
6929 return "ERROR_CONTENT";
6930 case SessionError::kTransport:
6931 return "ERROR_TRANSPORT";
6932 }
6933 RTC_NOTREACHED();
6934 return "";
6935}
6936
Steve Anton75737c02017-11-06 10:37:17 -08006937std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006938 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006939 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6940 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006941 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006942}
6943
Steve Anton8e20f172018-03-06 10:55:04 -08006944void PeerConnection::ReportSdpFormatReceived(
6945 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006946 int num_audio_mlines = 0;
6947 int num_video_mlines = 0;
6948 int num_audio_tracks = 0;
6949 int num_video_tracks = 0;
6950 for (const ContentInfo& content : remote_offer.description()->contents()) {
6951 cricket::MediaType media_type = content.media_description()->type();
6952 int num_tracks = std::max(
6953 1, static_cast<int>(content.media_description()->streams().size()));
6954 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6955 num_audio_mlines += 1;
6956 num_audio_tracks += num_tracks;
6957 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6958 num_video_mlines += 1;
6959 num_video_tracks += num_tracks;
6960 }
6961 }
6962 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6963 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6964 format = kSdpFormatReceivedComplexUnifiedPlan;
6965 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6966 format = kSdpFormatReceivedComplexPlanB;
6967 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6968 format = kSdpFormatReceivedSimple;
6969 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006970 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6971 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006972}
6973
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006974void PeerConnection::ReportIceCandidateCollected(
6975 const cricket::Candidate& candidate) {
6976 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
6977 if (candidate.address().IsPrivateIP()) {
6978 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
6979 }
6980 if (candidate.address().IsUnresolvedIP()) {
6981 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
6982 }
6983 if (candidate.address().family() == AF_INET6) {
6984 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
6985 }
6986}
6987
6988void PeerConnection::ReportRemoteIceCandidateAdded(
6989 const cricket::Candidate& candidate) {
6990 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
6991 if (candidate.address().IsPrivateIP()) {
6992 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
6993 }
6994 if (candidate.address().IsUnresolvedIP()) {
6995 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
6996 }
6997 if (candidate.address().family() == AF_INET6) {
6998 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
6999 }
7000}
7001
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007002void PeerConnection::NoteUsageEvent(UsageEvent event) {
7003 RTC_DCHECK_RUN_ON(signaling_thread());
7004 usage_event_accumulator_ |= static_cast<int>(event);
7005}
7006
7007void PeerConnection::ReportUsagePattern() const {
7008 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007009 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
7010 usage_event_accumulator_,
7011 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007012 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007013 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007014 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
7015 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07007016 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007017 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
7018 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
7019 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
7020 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007021 // If called after close(), we can't report, because observer may have
7022 // been deallocated, and therefore pointer is null. Write to log instead.
7023 if (observer_) {
7024 Observer()->OnInterestingUsage(usage_event_accumulator_);
7025 } else {
7026 RTC_LOG(LS_INFO) << "Interesting usage signature "
7027 << usage_event_accumulator_
7028 << " observed after observer shutdown";
7029 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007030 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007031}
7032
Steve Anton0ffaaa22018-02-23 10:31:30 -08007033void PeerConnection::ReportNegotiatedSdpSemantics(
7034 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007035 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007036 switch (answer.description()->msid_signaling()) {
7037 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007038 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007039 break;
7040 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007041 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007042 break;
7043 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007044 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007045 break;
7046 case cricket::kMsidSignalingMediaSection |
7047 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007048 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007049 break;
7050 default:
7051 RTC_NOTREACHED();
7052 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007053 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7054 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007055}
7056
Steve Anton75737c02017-11-06 10:37:17 -08007057// We need to check the local/remote description for the Transport instead of
7058// the session, because a new Transport added during renegotiation may have
7059// them unset while the session has them set from the previous negotiation.
7060// Not doing so may trigger the auto generation of transport description and
7061// mess up DTLS identity information, ICE credential, etc.
7062bool PeerConnection::ReadyToUseRemoteCandidate(
7063 const IceCandidateInterface* candidate,
7064 const SessionDescriptionInterface* remote_desc,
7065 bool* valid) {
7066 *valid = true;
7067
7068 const SessionDescriptionInterface* current_remote_desc =
7069 remote_desc ? remote_desc : remote_description();
7070
7071 if (!current_remote_desc) {
7072 return false;
7073 }
7074
Guido Urdaneta41633172019-05-23 20:12:29 +02007075 RTCErrorOr<const cricket::ContentInfo*> result =
7076 FindContentInfo(current_remote_desc, candidate);
7077 if (!result.ok()) {
7078 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7079 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007080
7081 *valid = false;
7082 return false;
7083 }
7084
Guido Urdaneta41633172019-05-23 20:12:29 +02007085 std::string transport_name = GetTransportName(result.value()->name);
7086 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007087}
7088
7089bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007090 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007091 (dtls_enabled_ ||
7092 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007093}
7094
7095void PeerConnection::OnTransportControllerGatheringState(
7096 cricket::IceGatheringState state) {
7097 RTC_DCHECK(signaling_thread()->IsCurrent());
7098 if (state == cricket::kIceGatheringGathering) {
7099 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7100 } else if (state == cricket::kIceGatheringComplete) {
7101 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7102 }
7103}
7104
7105void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007106 std::map<std::string, std::set<cricket::MediaType>>
7107 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007108 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007109 if (transceiver->internal()->channel()) {
7110 const std::string& transport_name =
7111 transceiver->internal()->channel()->transport_name();
7112 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007113 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007114 }
Steve Anton75737c02017-11-06 10:37:17 -08007115 }
7116 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007117 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7118 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007119 }
Zhi Huange830e682018-03-30 10:48:35 -07007120
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007121 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007122 if (transport_name) {
7123 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007124 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007125 }
Zhi Huange830e682018-03-30 10:48:35 -07007126
Steve Antonc7b964c2018-02-01 14:39:45 -08007127 for (const auto& entry : media_types_by_transport_name) {
7128 const std::string& transport_name = entry.first;
7129 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007130 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007131 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007132 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007133 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007134 }
7135 }
7136}
7137// Walk through the ConnectionInfos to gather best connection usage
7138// for IPv4 and IPv6.
7139void PeerConnection::ReportBestConnectionState(
7140 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007141 for (const cricket::TransportChannelStats& channel_stats :
7142 stats.channel_stats) {
7143 for (const cricket::ConnectionInfo& connection_info :
Jonas Oreland149dc722019-08-28 08:10:27 +02007144 channel_stats.ice_transport_stats.connection_infos) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007145 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007146 continue;
7147 }
7148
Steve Antonc7b964c2018-02-01 14:39:45 -08007149 const cricket::Candidate& local = connection_info.local_candidate;
7150 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007151
7152 // Increment the counter for IceCandidatePairType.
7153 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7154 (local.type() == RELAY_PORT_TYPE &&
7155 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007156 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7157 GetIceCandidatePairCounter(local, remote),
7158 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007159 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007160 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7161 GetIceCandidatePairCounter(local, remote),
7162 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007163 } else {
7164 RTC_CHECK(0);
7165 }
Steve Anton75737c02017-11-06 10:37:17 -08007166
7167 // Increment the counter for IP type.
7168 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007169 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7170 kBestConnections_IPv4,
7171 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007172 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007173 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7174 kBestConnections_IPv6,
7175 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007176 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007177 RTC_CHECK(!local.address().hostname().empty() &&
7178 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007179 }
7180
7181 return;
7182 }
7183 }
7184}
7185
7186void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007187 const cricket::TransportStats& stats,
7188 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007189 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7190 return;
7191 }
7192
7193 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7194 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7195 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7196 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7197 return;
7198 }
7199
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007200 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7201 for (cricket::MediaType media_type : media_types) {
7202 switch (media_type) {
7203 case cricket::MEDIA_TYPE_AUDIO:
7204 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7205 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7206 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7207 break;
7208 case cricket::MEDIA_TYPE_VIDEO:
7209 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7210 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7211 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7212 break;
7213 case cricket::MEDIA_TYPE_DATA:
7214 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7215 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7216 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7217 break;
7218 default:
7219 RTC_NOTREACHED();
7220 continue;
7221 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007222 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007223 }
7224
7225 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7226 for (cricket::MediaType media_type : media_types) {
7227 switch (media_type) {
7228 case cricket::MEDIA_TYPE_AUDIO:
7229 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7230 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7231 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7232 break;
7233 case cricket::MEDIA_TYPE_VIDEO:
7234 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7235 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7236 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7237 break;
7238 case cricket::MEDIA_TYPE_DATA:
7239 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7240 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7241 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7242 break;
7243 default:
7244 RTC_NOTREACHED();
7245 continue;
7246 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007247 }
Steve Anton75737c02017-11-06 10:37:17 -08007248 }
7249}
7250
7251void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007252 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007253 RTC_DCHECK(call_);
7254 call_->OnSentPacket(sent_packet);
7255}
7256
7257const std::string PeerConnection::GetTransportName(
7258 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007259 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007260 if (channel) {
7261 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007262 }
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01007263 if (data_channel_controller_.data_channel_transport()) {
Harald Alvestrand7a829a82020-02-12 07:38:21 +01007264 RTC_DCHECK(sctp_mid_s_);
7265 if (content_name == *sctp_mid_s_) {
Zhi Huange830e682018-03-30 10:48:35 -07007266 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007267 }
7268 }
7269 // Return an empty string if failed to retrieve the transport name.
7270 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007271}
7272
Steve Anton6fec8802017-12-04 10:37:29 -08007273void PeerConnection::DestroyTransceiverChannel(
7274 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7275 transceiver) {
7276 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007277
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007278 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007279 if (channel) {
7280 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007281 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007282 }
7283}
7284
Harald Alvestrand408cb4b2019-11-16 12:09:08 +01007285void PeerConnection::DestroyDataChannelTransport() {
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01007286 if (data_channel_controller_.rtp_data_channel()) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01007287 data_channel_controller_.OnTransportChannelClosed();
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01007288 DestroyChannelInterface(data_channel_controller_.rtp_data_channel());
7289 data_channel_controller_.set_rtp_data_channel(nullptr);
Steve Anton6fec8802017-12-04 10:37:29 -08007290 }
7291
7292 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7293 // grab a reference to this PeerConnection. If this is called from the
7294 // PeerConnection destructor, the RefCountedObject vtable will have already
7295 // been destroyed (since it is a subclass of PeerConnection) and using
7296 // rtc::Bind will cause "Pure virtual function called" error to appear.
7297
Harald Alvestrand7a829a82020-02-12 07:38:21 +01007298 if (sctp_mid_s_) {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01007299 data_channel_controller_.OnTransportChannelClosed();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007300 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7301 RTC_DCHECK_RUN_ON(network_thread());
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007302 TeardownDataChannelTransport_n();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007303 });
Harald Alvestrand7a829a82020-02-12 07:38:21 +01007304 sctp_mid_s_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007305 }
Steve Anton6fec8802017-12-04 10:37:29 -08007306}
7307
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007308void PeerConnection::DestroyChannelInterface(
7309 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007310 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007311 switch (channel->media_type()) {
7312 case cricket::MEDIA_TYPE_AUDIO:
7313 channel_manager()->DestroyVoiceChannel(
7314 static_cast<cricket::VoiceChannel*>(channel));
7315 break;
7316 case cricket::MEDIA_TYPE_VIDEO:
7317 channel_manager()->DestroyVideoChannel(
7318 static_cast<cricket::VideoChannel*>(channel));
7319 break;
7320 case cricket::MEDIA_TYPE_DATA:
7321 channel_manager()->DestroyRtpDataChannel(
7322 static_cast<cricket::RtpDataChannel*>(channel));
7323 break;
7324 default:
7325 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7326 break;
7327 }
Zhi Huange830e682018-03-30 10:48:35 -07007328}
Steve Anton6fec8802017-12-04 10:37:29 -08007329
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007330bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007331 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007332 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007333 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07007334 DataChannelTransportInterface* data_channel_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007335 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007336 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007337 auto base_channel = GetChannel(mid);
7338 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007339 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007340 }
Harald Alvestrand7a829a82020-02-12 07:38:21 +01007341 if (mid == sctp_mid_n_) {
Harald Alvestrand00cf34c2019-12-02 09:56:02 +01007342 data_channel_controller_.OnTransportChanged(data_channel_transport);
Bjorn A Mellemb689af42019-08-21 10:44:59 -07007343 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007344 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007345}
7346
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007347void PeerConnection::OnSetStreams() {
7348 RTC_DCHECK_RUN_ON(signaling_thread());
7349 if (IsUnifiedPlan())
7350 UpdateNegotiationNeeded();
7351}
7352
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007353PeerConnectionObserver* PeerConnection::Observer() const {
Harald Alvestrand05e4d082019-12-03 14:04:21 +01007354 RTC_DCHECK_RUN_ON(signaling_thread());
7355 RTC_DCHECK(observer_);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007356 return observer_;
7357}
7358
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007359CryptoOptions PeerConnection::GetCryptoOptions() {
7360 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7361 // after it has been removed.
7362 return configuration_.crypto_options.has_value()
7363 ? *configuration_.crypto_options
7364 : factory_->options().crypto_options;
7365}
7366
Harald Alvestrand89061872018-01-02 14:08:34 +01007367void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007368 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007369 if (stats_collector_) {
7370 stats_collector_->ClearCachedStatsReport();
7371 }
7372}
7373
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007374void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007375 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7376 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007377}
7378
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007379void PeerConnection::UpdateNegotiationNeeded() {
7380 RTC_DCHECK_RUN_ON(signaling_thread());
7381 if (!IsUnifiedPlan()) {
7382 Observer()->OnRenegotiationNeeded();
7383 return;
7384 }
7385
7386 // If connection's [[IsClosed]] slot is true, abort these steps.
7387 if (IsClosed())
7388 return;
7389
7390 // If connection's signaling state is not "stable", abort these steps.
7391 if (signaling_state() != kStable)
7392 return;
7393
7394 // NOTE
7395 // The negotiation-needed flag will be updated once the state transitions to
7396 // "stable", as part of the steps for setting an RTCSessionDescription.
7397
7398 // If the result of checking if negotiation is needed is false, clear the
7399 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7400 // to false, and abort these steps.
7401 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7402 if (!is_negotiation_needed) {
7403 is_negotiation_needed_ = false;
7404 return;
7405 }
7406
7407 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7408 // steps.
7409 if (is_negotiation_needed_)
7410 return;
7411
7412 // Set connection's [[NegotiationNeeded]] slot to true.
7413 is_negotiation_needed_ = true;
7414
7415 // Queue a task that runs the following steps:
7416 // If connection's [[IsClosed]] slot is true, abort these steps.
7417 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7418 // Fire an event named negotiationneeded at connection.
7419 Observer()->OnRenegotiationNeeded();
7420}
7421
7422bool PeerConnection::CheckIfNegotiationIsNeeded() {
7423 RTC_DCHECK_RUN_ON(signaling_thread());
7424 // 1. If any implementation-specific negotiation is required, as described at
7425 // the start of this section, return true.
7426
Henrik Boström79b69802019-07-18 11:16:56 +02007427 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7428 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7429 return true;
7430 }
7431
7432 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007433 const SessionDescriptionInterface* description = current_local_description();
7434 if (!description)
7435 return true;
7436
Henrik Boström79b69802019-07-18 11:16:56 +02007437 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007438 // description has been negotiated yet for data, return true.
Harald Alvestrand05e4d082019-12-03 14:04:21 +01007439 if (data_channel_controller_.HasSctpDataChannels()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007440 if (!cricket::GetFirstDataContent(description->description()->contents()))
7441 return true;
7442 }
7443
Henrik Boström79b69802019-07-18 11:16:56 +02007444 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007445 // following checks:
7446 for (const auto& transceiver : transceivers_) {
7447 const ContentInfo* current_local_msection =
7448 FindTransceiverMSection(transceiver.get(), description);
7449
7450 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7451 transceiver.get(), current_remote_description());
7452
Henrik Boström79b69802019-07-18 11:16:56 +02007453 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007454 // but the associated m= section is not yet rejected in
7455 // connection.[[CurrentLocalDescription]] or
7456 // connection.[[CurrentRemoteDescription]], return true.
7457 if (transceiver->stopped()) {
7458 if (current_local_msection && !current_local_msection->rejected &&
7459 ((current_remote_msection && !current_remote_msection->rejected) ||
7460 !current_remote_msection)) {
7461 return true;
7462 }
7463 continue;
7464 }
7465
Henrik Boström79b69802019-07-18 11:16:56 +02007466 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007467 // section in description, return true.
7468 if (!current_local_msection)
7469 return true;
7470
7471 const MediaContentDescription* current_local_media_description =
7472 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007473 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007474 // in description then perform the following checks:
7475
Henrik Boström79b69802019-07-18 11:16:56 +02007476 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007477 // associated m= section in description either doesn't contain a single
7478 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7479 // m= section, or the MSID values themselves, differ from what is in
7480 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7481 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7482 if (current_local_media_description->streams().size() == 0)
7483 return true;
7484
7485 std::vector<std::string> msection_msids;
7486 for (const auto& stream : current_local_media_description->streams()) {
7487 for (const std::string& msid : stream.stream_ids())
7488 msection_msids.push_back(msid);
7489 }
7490
7491 std::vector<std::string> transceiver_msids =
7492 transceiver->sender()->stream_ids();
7493 if (msection_msids.size() != transceiver_msids.size())
7494 return true;
7495
7496 absl::c_sort(transceiver_msids);
7497 absl::c_sort(msection_msids);
7498 if (transceiver_msids != msection_msids)
7499 return true;
7500 }
7501
Henrik Boström79b69802019-07-18 11:16:56 +02007502 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007503 // associated m= section in neither connection.[[CurrentLocalDescription]]
7504 // nor connection.[[CurrentRemoteDescription]] matches
7505 // transceiver.[[Direction]], return true.
7506 if (description->GetType() == SdpType::kOffer) {
7507 if (!current_remote_description())
7508 return true;
7509
7510 if (!current_remote_msection)
7511 return true;
7512
7513 RtpTransceiverDirection current_local_direction =
7514 current_local_media_description->direction();
7515 RtpTransceiverDirection current_remote_direction =
7516 current_remote_msection->media_description()->direction();
7517 if (transceiver->direction() != current_local_direction &&
7518 transceiver->direction() !=
7519 RtpTransceiverDirectionReversed(current_remote_direction)) {
7520 return true;
7521 }
7522 }
7523
Henrik Boström79b69802019-07-18 11:16:56 +02007524 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007525 // associated m= section in the description does not match
7526 // transceiver.[[Direction]] intersected with the offered direction (as
7527 // described in [JSEP] (section 5.3.1.)), return true.
7528 if (description->GetType() == SdpType::kAnswer) {
7529 if (!remote_description())
7530 return true;
7531
7532 const ContentInfo* offered_remote_msection =
7533 FindTransceiverMSection(transceiver.get(), remote_description());
7534
7535 RtpTransceiverDirection offered_direction =
7536 offered_remote_msection
7537 ? offered_remote_msection->media_description()->direction()
7538 : RtpTransceiverDirection::kInactive;
7539
7540 if (current_local_media_description->direction() !=
7541 (RtpTransceiverDirectionIntersection(
7542 transceiver->direction(),
7543 RtpTransceiverDirectionReversed(offered_direction)))) {
7544 return true;
7545 }
7546 }
7547 }
7548
7549 // If all the preceding checks were performed and true was not returned,
7550 // nothing remains to be negotiated; return false.
7551 return false;
7552}
7553
Eldar Relloead0ec92019-10-21 23:01:31 +03007554RTCError PeerConnection::Rollback(SdpType sdp_type) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03007555 auto state = signaling_state();
7556 if (state != PeerConnectionInterface::kHaveLocalOffer &&
7557 state != PeerConnectionInterface::kHaveRemoteOffer) {
7558 return RTCError(RTCErrorType::INVALID_STATE,
7559 "Called in wrong signalingState: " +
7560 GetSignalingStateString(signaling_state()));
7561 }
7562 RTC_DCHECK_RUN_ON(signaling_thread());
7563 RTC_DCHECK(IsUnifiedPlan());
Eldar Rello353a7182019-11-25 18:49:44 +02007564 std::vector<rtc::scoped_refptr<MediaStreamInterface>> all_added_streams;
7565 std::vector<rtc::scoped_refptr<MediaStreamInterface>> all_removed_streams;
7566 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> removed_receivers;
Eldar Rello5ab79e62019-10-09 18:29:44 +03007567
7568 for (auto&& transceivers_stable_state_pair :
7569 transceiver_stable_states_by_transceivers_) {
7570 auto transceiver = transceivers_stable_state_pair.first;
7571 auto state = transceivers_stable_state_pair.second;
Eldar Rello353a7182019-11-25 18:49:44 +02007572
7573 if (state.remote_stream_ids()) {
7574 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
7575 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
7576 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
7577 state.remote_stream_ids().value(),
7578 &added_streams, &removed_streams);
7579 all_added_streams.insert(all_added_streams.end(), added_streams.begin(),
7580 added_streams.end());
7581 all_removed_streams.insert(all_removed_streams.end(),
7582 removed_streams.begin(),
7583 removed_streams.end());
7584 if (!state.has_m_section() && !state.newly_created()) {
7585 continue;
7586 }
7587 }
7588
Eldar Rello5ab79e62019-10-09 18:29:44 +03007589 RTC_DCHECK(transceiver->internal()->mid().has_value());
Eldar Rello5ab79e62019-10-09 18:29:44 +03007590 DestroyTransceiverChannel(transceiver);
7591
Eldar Relloead0ec92019-10-21 23:01:31 +03007592 if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
7593 transceiver->receiver()) {
Eldar Rello353a7182019-11-25 18:49:44 +02007594 removed_receivers.push_back(transceiver->receiver());
Eldar Relloead0ec92019-10-21 23:01:31 +03007595 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007596 if (state.newly_created()) {
Eldar Rello353a7182019-11-25 18:49:44 +02007597 if (transceiver->internal()->reused_for_addtrack()) {
Eldar Rello5ab79e62019-10-09 18:29:44 +03007598 transceiver->internal()->set_created_by_addtrack(true);
7599 } else {
7600 int remaining_transceiver_count = 0;
7601 for (auto&& t : transceivers_) {
7602 if (t != transceiver) {
7603 transceivers_[remaining_transceiver_count++] = t;
7604 }
7605 }
7606 transceivers_.resize(remaining_transceiver_count);
7607 }
7608 }
7609 transceiver->internal()->sender_internal()->set_transport(nullptr);
7610 transceiver->internal()->receiver_internal()->set_transport(nullptr);
Eldar Rello5ab79e62019-10-09 18:29:44 +03007611 transceiver->internal()->set_mid(state.mid());
7612 transceiver->internal()->set_mline_index(state.mline_index());
7613 }
Eldar Rellod85ea752020-02-19 20:41:07 +02007614 transport_controller_->RollbackTransports();
Eldar Rellod9ebe012020-03-18 20:41:45 +02007615 if (have_pending_rtp_data_channel_) {
7616 DestroyDataChannelTransport();
7617 have_pending_rtp_data_channel_ = false;
7618 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007619 transceiver_stable_states_by_transceivers_.clear();
7620 pending_local_description_.reset();
7621 pending_remote_description_.reset();
7622 ChangeSignalingState(PeerConnectionInterface::kStable);
Eldar Relloead0ec92019-10-21 23:01:31 +03007623
Eldar Rello353a7182019-11-25 18:49:44 +02007624 // Once all processing has finished, fire off callbacks.
7625 for (const auto& receiver : removed_receivers) {
7626 Observer()->OnRemoveTrack(receiver);
7627 }
7628 for (const auto& stream : all_added_streams) {
7629 Observer()->OnAddStream(stream);
7630 }
7631 for (const auto& stream : all_removed_streams) {
7632 Observer()->OnRemoveStream(stream);
7633 }
7634
Eldar Relloead0ec92019-10-21 23:01:31 +03007635 // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
7636 // gets called in SetRemoteDescription.
7637 if (sdp_type == SdpType::kRollback) {
7638 UpdateNegotiationNeeded();
7639 if (is_negotiation_needed_) {
7640 Observer()->OnRenegotiationNeeded();
7641 }
7642 }
Eldar Rello5ab79e62019-10-09 18:29:44 +03007643 return RTCError::OK();
7644}
7645
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007646} // namespace webrtc