blob: 55b264e1c5c79a85cfe0aae0456fb9ea52a1773b [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
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";
113
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800114// UMA metric names.
115const char kSimulcastVersionApplyLocalDescription[] =
116 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
117const char kSimulcastVersionApplyRemoteDescription[] =
118 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
119const char kSimulcastNumberOfEncodings[] =
120 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
121const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
122
Seth Hampson845e8782018-03-02 11:34:10 -0800123static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800124static const char kDefaultAudioSenderId[] = "defaulta0";
125static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700126
zhihuang8f65cdf2016-05-06 18:40:30 -0700127// The length of RTCP CNAMEs.
128static const int kRtcpCnameLength = 16;
129
Steve Antonad182762018-09-05 20:22:40 +0000130enum {
131 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
132 MSG_SET_SESSIONDESCRIPTION_FAILED,
133 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
134 MSG_GETSTATS,
135 MSG_FREE_DATACHANNELS,
136 MSG_REPORT_USAGE_PATTERN,
137};
138
Harald Alvestrand19793842018-06-25 12:03:50 +0200139static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
140
Steve Antonad182762018-09-05 20:22:40 +0000141struct SetSessionDescriptionMsg : public rtc::MessageData {
142 explicit SetSessionDescriptionMsg(
143 webrtc::SetSessionDescriptionObserver* observer)
144 : observer(observer) {}
145
146 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
147 RTCError error;
148};
149
150struct CreateSessionDescriptionMsg : public rtc::MessageData {
151 explicit CreateSessionDescriptionMsg(
152 webrtc::CreateSessionDescriptionObserver* observer)
153 : observer(observer) {}
154
155 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
156 RTCError error;
157};
158
159struct GetStatsMsg : public rtc::MessageData {
160 GetStatsMsg(webrtc::StatsObserver* observer,
161 webrtc::MediaStreamTrackInterface* track)
162 : observer(observer), track(track) {}
163 rtc::scoped_refptr<webrtc::StatsObserver> observer;
164 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
165};
166
deadbeefab9b2d12015-10-14 11:33:11 -0700167// Check if we can send |new_stream| on a PeerConnection.
168bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
169 webrtc::MediaStreamInterface* new_stream) {
170 if (!new_stream || !current_streams) {
171 return false;
172 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700173 if (current_streams->find(new_stream->id()) != nullptr) {
174 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100175 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700176 return false;
177 }
178 return true;
179}
180
deadbeef5e97fb52015-10-15 12:49:08 -0700181// If the direction is "recvonly" or "inactive", treat the description
182// as containing no streams.
183// See: https://code.google.com/p/webrtc/issues/detail?id=5054
184std::vector<cricket::StreamParams> GetActiveStreams(
185 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800186 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700187 ? desc->streams()
188 : std::vector<cricket::StreamParams>();
189}
190
deadbeefab9b2d12015-10-14 11:33:11 -0700191bool IsValidOfferToReceiveMedia(int value) {
192 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
193 return (value >= Options::kUndefined) &&
194 (value <= Options::kMaxOfferToReceiveMedia);
195}
196
zhihuang1c378ed2017-08-17 14:10:50 -0700197// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800198void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700199 const std::vector<rtc::scoped_refptr<
200 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700201 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200202 cricket::MediaDescriptionOptions* video_media_description_options,
203 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700204 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
206 if (audio_media_description_options) {
207 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700208 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700209 }
210 } else {
211 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
212 if (video_media_description_options) {
213 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800214 sender->id(), sender->internal()->stream_ids(), {},
215 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700216 }
217 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700218 }
zhihuang1c378ed2017-08-17 14:10:50 -0700219}
olka3c747662017-08-17 06:50:32 -0700220
zhihuang1c378ed2017-08-17 14:10:50 -0700221// Add options to |session_options| from |rtp_data_channels|.
222void AddRtpDataChannelOptions(
223 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
224 rtp_data_channels,
225 cricket::MediaDescriptionOptions* data_media_description_options) {
226 if (!data_media_description_options) {
227 return;
228 }
deadbeefab9b2d12015-10-14 11:33:11 -0700229 // Check for data channels.
230 for (const auto& kv : rtp_data_channels) {
231 const DataChannel* channel = kv.second;
232 if (channel->state() == DataChannel::kConnecting ||
233 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700234 // Legacy RTP data channels are signaled with the track/stream ID set to
235 // the data channel's label.
236 data_media_description_options->AddRtpDataChannel(channel->label(),
237 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700238 }
239 }
240}
241
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700242uint32_t ConvertIceTransportTypeToCandidateFilter(
243 PeerConnectionInterface::IceTransportsType type) {
244 switch (type) {
245 case PeerConnectionInterface::kNone:
246 return cricket::CF_NONE;
247 case PeerConnectionInterface::kRelay:
248 return cricket::CF_RELAY;
249 case PeerConnectionInterface::kNoHost:
250 return (cricket::CF_ALL & ~cricket::CF_HOST);
251 case PeerConnectionInterface::kAll:
252 return cricket::CF_ALL;
253 default:
nissec80e7412017-01-11 05:56:46 -0800254 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700255 }
256 return cricket::CF_NONE;
257}
258
deadbeef293e9262017-01-11 12:28:30 -0800259// Helper to set an error and return from a method.
260bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
261 if (error) {
262 error->set_type(type);
263 }
264 return type == webrtc::RTCErrorType::NONE;
265}
266
Steve Anton038834f2017-07-14 15:59:59 -0700267bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700269 if (error_out) {
270 *error_out = std::move(error);
271 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700272 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700273}
274
Steve Antonba818672017-11-06 10:21:57 -0800275std::string GetSignalingStateString(
276 PeerConnectionInterface::SignalingState state) {
277 switch (state) {
278 case PeerConnectionInterface::kStable:
279 return "kStable";
280 case PeerConnectionInterface::kHaveLocalOffer:
281 return "kHaveLocalOffer";
282 case PeerConnectionInterface::kHaveLocalPrAnswer:
283 return "kHavePrAnswer";
284 case PeerConnectionInterface::kHaveRemoteOffer:
285 return "kHaveRemoteOffer";
286 case PeerConnectionInterface::kHaveRemotePrAnswer:
287 return "kHaveRemotePrAnswer";
288 case PeerConnectionInterface::kClosed:
289 return "kClosed";
290 }
291 RTC_NOTREACHED();
292 return "";
293}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700294
Steve Anton75737c02017-11-06 10:37:17 -0800295IceCandidatePairType GetIceCandidatePairCounter(
296 const cricket::Candidate& local,
297 const cricket::Candidate& remote) {
298 const auto& l = local.type();
299 const auto& r = remote.type();
300 const auto& host = LOCAL_PORT_TYPE;
301 const auto& srflx = STUN_PORT_TYPE;
302 const auto& relay = RELAY_PORT_TYPE;
303 const auto& prflx = PRFLX_PORT_TYPE;
304 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800305 bool local_hostname =
306 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
307 bool remote_hostname = !remote.address().hostname().empty() &&
308 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800309 bool local_private = IPIsPrivate(local.address().ipaddr());
310 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800311 if (local_hostname) {
312 if (remote_hostname) {
313 return kIceCandidatePairHostNameHostName;
314 } else if (remote_private) {
315 return kIceCandidatePairHostNameHostPrivate;
316 } else {
317 return kIceCandidatePairHostNameHostPublic;
318 }
319 } else if (local_private) {
320 if (remote_hostname) {
321 return kIceCandidatePairHostPrivateHostName;
322 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800323 return kIceCandidatePairHostPrivateHostPrivate;
324 } else {
325 return kIceCandidatePairHostPrivateHostPublic;
326 }
327 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800328 if (remote_hostname) {
329 return kIceCandidatePairHostPublicHostName;
330 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800331 return kIceCandidatePairHostPublicHostPrivate;
332 } else {
333 return kIceCandidatePairHostPublicHostPublic;
334 }
335 }
336 }
337 if (l == host && r == srflx)
338 return kIceCandidatePairHostSrflx;
339 if (l == host && r == relay)
340 return kIceCandidatePairHostRelay;
341 if (l == host && r == prflx)
342 return kIceCandidatePairHostPrflx;
343 if (l == srflx && r == host)
344 return kIceCandidatePairSrflxHost;
345 if (l == srflx && r == srflx)
346 return kIceCandidatePairSrflxSrflx;
347 if (l == srflx && r == relay)
348 return kIceCandidatePairSrflxRelay;
349 if (l == srflx && r == prflx)
350 return kIceCandidatePairSrflxPrflx;
351 if (l == relay && r == host)
352 return kIceCandidatePairRelayHost;
353 if (l == relay && r == srflx)
354 return kIceCandidatePairRelaySrflx;
355 if (l == relay && r == relay)
356 return kIceCandidatePairRelayRelay;
357 if (l == relay && r == prflx)
358 return kIceCandidatePairRelayPrflx;
359 if (l == prflx && r == host)
360 return kIceCandidatePairPrflxHost;
361 if (l == prflx && r == srflx)
362 return kIceCandidatePairPrflxSrflx;
363 if (l == prflx && r == relay)
364 return kIceCandidatePairPrflxRelay;
365 return kIceCandidatePairMax;
366}
367
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368// Logic to decide if an m= section can be recycled. This means that the new
369// m= section is not rejected, but the old local or remote m= section is
370// rejected. |old_content_one| and |old_content_two| refer to the m= section
371// of the old remote and old local descriptions in no particular order.
372// We need to check both the old local and remote because either
373// could be the most current from the latest negotation.
374bool IsMediaSectionBeingRecycled(SdpType type,
375 const ContentInfo& content,
376 const ContentInfo* old_content_one,
377 const ContentInfo* old_content_two) {
378 return type == SdpType::kOffer && !content.rejected &&
379 ((old_content_one && old_content_one->rejected) ||
380 (old_content_two && old_content_two->rejected));
381}
382
Steve Anton75737c02017-11-06 10:37:17 -0800383// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800384// |current_desc|. The number of m= sections in |new_desc| should be no
385// less than |current_desc|. In the case of checking an answer's
386// |new_desc|, the |current_desc| is the last offer that was set as the
387// local or remote. In the case of checking an offer's |new_desc| we
388// check against the local and remote descriptions stored from the last
389// negotiation, because either of these could be the most up to date for
390// possible rejected m sections. These are the |current_desc| and
391// |secondary_current_desc|.
392bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
393 const SessionDescription* secondary_current_desc,
394 const SessionDescription& new_desc,
395 const SdpType type) {
396 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800400 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
401 const cricket::ContentInfo* secondary_content_info = nullptr;
402 if (secondary_current_desc &&
403 i < secondary_current_desc->contents().size()) {
404 secondary_content_info = &secondary_current_desc->contents()[i];
405 }
406 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
407 &current_desc.contents()[i],
408 secondary_content_info)) {
409 // For new offer descriptions, if the media section can be recycled, it's
410 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800411 continue;
412 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800414 return false;
415 }
416 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800417 new_desc.contents()[i].media_description();
418 const MediaContentDescription* current_desc_mdesc =
419 current_desc.contents()[i].media_description();
420 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800421 return false;
422 }
423 }
424 return true;
425}
426
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800427bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
428 const SessionDescription& desc2) {
429 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800430}
431
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700432void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
433 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200434 // Array of structs needed to map {KeyExchangeProtocolType,
435 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
436 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
437 static constexpr struct {
438 KeyExchangeProtocolType protocol_type;
439 cricket::MediaType media_type;
440 KeyExchangeProtocolMedia protocol_media;
441 } kEnumCounterKeyProtocolMediaMap[] = {
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
443 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
444 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
445 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
446 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
447 kEnumCounterKeyProtocolMediaTypeDtlsData},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
449 kEnumCounterKeyProtocolMediaTypeSdesAudio},
450 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
451 kEnumCounterKeyProtocolMediaTypeSdesVideo},
452 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
453 kEnumCounterKeyProtocolMediaTypeSdesData},
454 };
455
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700456 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
457 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100458
Mirko Bonadeiab499822018-09-11 10:43:20 +0200459 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
460 if (i.protocol_type == protocol_type && i.media_type == media_type) {
461 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
462 i.protocol_media,
463 kEnumCounterKeyProtocolMediaTypeMax);
464 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100465 }
466}
467
Harald Alvestrand76829d72018-07-18 23:24:36 +0200468void NoteAddIceCandidateResult(int result) {
469 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
470 kAddIceCandidateMax);
471}
472
Steve Anton75737c02017-11-06 10:37:17 -0800473// Checks that each non-rejected content has SDES crypto keys or a DTLS
474// fingerprint, unless it's in a BUNDLE group, in which case only the
475// BUNDLE-tag section (first media section/description in the BUNDLE group)
476// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
477// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
478// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700479RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 const cricket::ContentGroup* bundle =
481 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800482 for (const cricket::ContentInfo& content_info : desc->contents()) {
483 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800484 continue;
485 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100486 // Note what media is used with each crypto protocol, for all sections.
487 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
488 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700489 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800490 const std::string& mid = content_info.name;
491 if (bundle && bundle->HasContentName(mid) &&
492 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 // This isn't the first media section in the BUNDLE group, so it's not
494 // required to have crypto attributes, since only the crypto attributes
495 // from the first section actually get used.
496 continue;
497 }
498
499 // If the content isn't rejected or bundled into another m= section, crypto
500 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800501 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800502 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800503 if (!media || !tinfo) {
504 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800506 }
507 if (dtls_enabled) {
508 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_WARNING)
510 << "Session description must have DTLS fingerprint if "
511 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800512 return RTCError(RTCErrorType::INVALID_PARAMETER,
513 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800514 }
515 } else {
516 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100517 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800518 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800520 }
521 }
522 }
Steve Anton8a006912017-12-04 15:25:56 -0800523 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800524}
525
526// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
527// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
528// media section/description in the BUNDLE group) needs a ufrag and pwd.
529bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
530 const cricket::ContentGroup* bundle =
531 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800532 for (const cricket::ContentInfo& content_info : desc->contents()) {
533 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800534 continue;
535 }
Steve Anton8a006912017-12-04 15:25:56 -0800536 const std::string& mid = content_info.name;
537 if (bundle && bundle->HasContentName(mid) &&
538 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800539 // This isn't the first media section in the BUNDLE group, so it's not
540 // required to have ufrag/password, since only the ufrag/password from
541 // the first section actually get used.
542 continue;
543 }
544
545 // If the content isn't rejected or bundled into another m= section,
546 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800547 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800548 if (!tinfo) {
549 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100550 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800551 return false;
552 }
553 if (tinfo->description.ice_ufrag.empty() ||
554 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100555 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800556 return false;
557 }
558 }
559 return true;
560}
561
Steve Anton75737c02017-11-06 10:37:17 -0800562// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
563bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
564 const SessionDescriptionInterface* new_desc,
565 const std::string& content_name) {
566 if (!old_desc) {
567 return false;
568 }
569 const SessionDescription* new_sd = new_desc->description();
570 const SessionDescription* old_sd = old_desc->description();
571 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
572 if (!cinfo || cinfo->rejected) {
573 return false;
574 }
575 // If the content isn't rejected, check if ufrag and password has changed.
576 const cricket::TransportDescription* new_transport_desc =
577 new_sd->GetTransportDescriptionByName(content_name);
578 const cricket::TransportDescription* old_transport_desc =
579 old_sd->GetTransportDescriptionByName(content_name);
580 if (!new_transport_desc || !old_transport_desc) {
581 // No transport description exists. This is not an ICE restart.
582 return false;
583 }
584 if (cricket::IceCredentialsChanged(
585 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
586 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100587 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
588 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800589 return true;
590 }
591 return false;
592}
593
Steve Anton80dd7b52018-02-16 17:08:42 -0800594// Generates a string error message for SetLocalDescription/SetRemoteDescription
595// from an RTCError.
596std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
597 SdpType type,
598 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200599 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800600 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
601 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200602 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800603}
604
Seth Hampson5b4f0752018-04-02 16:31:36 -0700605std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
606 std::string output = "streams=[";
607 const char* separator = "";
608 for (const auto& stream_id : stream_ids) {
609 output.append(separator).append(stream_id);
610 separator = ", ";
611 }
612 output.append("]");
613 return output;
614}
615
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 int rtc_configuration_parameter) {
618 if (rtc_configuration_parameter ==
619 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200620 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700621 }
622 return rtc_configuration_parameter;
623}
624
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800625cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
626 switch (type) {
627 case DataMessageType::kText:
628 return cricket::DMT_TEXT;
629 case DataMessageType::kBinary:
630 return cricket::DMT_BINARY;
631 case DataMessageType::kControl:
632 return cricket::DMT_CONTROL;
633 default:
634 return cricket::DMT_NONE;
635 }
636 return cricket::DMT_NONE;
637}
638
639DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
640 switch (type) {
641 case cricket::DMT_TEXT:
642 return DataMessageType::kText;
643 case cricket::DMT_BINARY:
644 return DataMessageType::kBinary;
645 case cricket::DMT_CONTROL:
646 return DataMessageType::kControl;
647 case cricket::DMT_NONE:
648 default:
649 RTC_NOTREACHED();
650 }
651 return DataMessageType::kControl;
652}
653
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800654void ReportSimulcastApiVersion(const char* name,
655 const SessionDescription& session) {
656 bool has_legacy = false;
657 bool has_spec_compliant = false;
658 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200659 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800660 continue;
661 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200662 has_spec_compliant |= content.media_description()->HasSimulcast();
663 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800664 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
665 }
666 }
667
668 if (has_legacy) {
669 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
670 kSimulcastApiVersionMax);
671 }
672 if (has_spec_compliant) {
673 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
674 kSimulcastApiVersionMax);
675 }
676 if (!has_legacy && !has_spec_compliant) {
677 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
678 kSimulcastApiVersionMax);
679 }
680}
681
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200682const ContentInfo* FindTransceiverMSection(
683 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
684 const SessionDescriptionInterface* session_description) {
685 return transceiver->mid()
686 ? session_description->description()->GetContentByName(
687 *transceiver->mid())
688 : nullptr;
689}
690
Steve Anton75737c02017-11-06 10:37:17 -0800691} // namespace
692
Henrik Boström79b69802019-07-18 11:16:56 +0200693class PeerConnection::LocalIceCredentialsToReplace {
694 public:
695 // Sets the ICE credentials that need restarting to the ICE credentials of
696 // the current and pending descriptions.
697 void SetIceCredentialsFromLocalDescriptions(
698 const SessionDescriptionInterface* current_local_description,
699 const SessionDescriptionInterface* pending_local_description) {
700 ice_credentials_.clear();
701 if (current_local_description) {
702 AppendIceCredentialsFromSessionDescription(*current_local_description);
703 }
704 if (pending_local_description) {
705 AppendIceCredentialsFromSessionDescription(*pending_local_description);
706 }
707 }
708
709 void ClearIceCredentials() { ice_credentials_.clear(); }
710
711 // Returns true if we have ICE credentials that need restarting.
712 bool HasIceCredentials() const { return !ice_credentials_.empty(); }
713
714 // Returns true if |local_description| shares no ICE credentials with the
715 // ICE credentials that need restarting.
716 bool SatisfiesIceRestart(
717 const SessionDescriptionInterface& local_description) const {
718 for (const auto& transport_info :
719 local_description.description()->transport_infos()) {
720 if (ice_credentials_.find(std::make_pair(
721 transport_info.description.ice_ufrag,
722 transport_info.description.ice_pwd)) != ice_credentials_.end()) {
723 return false;
724 }
725 }
726 return true;
727 }
728
729 private:
730 void AppendIceCredentialsFromSessionDescription(
731 const SessionDescriptionInterface& desc) {
732 for (const auto& transport_info : desc.description()->transport_infos()) {
733 ice_credentials_.insert(
734 std::make_pair(transport_info.description.ice_ufrag,
735 transport_info.description.ice_pwd));
736 }
737 }
738
739 std::set<std::pair<std::string, std::string>> ice_credentials_;
740};
741
Henrik Boström31638672017-11-23 17:48:32 +0100742// Upon completion, posts a task to execute the callback of the
743// SetSessionDescriptionObserver asynchronously on the same thread. At this
744// point, the state of the peer connection might no longer reflect the effects
745// of the SetRemoteDescription operation, as the peer connection could have been
746// modified during the post.
747// TODO(hbos): Remove this class once we remove the version of
748// PeerConnectionInterface::SetRemoteDescription() that takes a
749// SetSessionDescriptionObserver as an argument.
750class PeerConnection::SetRemoteDescriptionObserverAdapter
751 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
752 public:
753 SetRemoteDescriptionObserverAdapter(
754 rtc::scoped_refptr<PeerConnection> pc,
755 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
756 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
757
758 // SetRemoteDescriptionObserverInterface implementation.
759 void OnSetRemoteDescriptionComplete(RTCError error) override {
760 if (error.ok())
761 pc_->PostSetSessionDescriptionSuccess(wrapper_);
762 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100763 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100764 }
765
766 private:
767 rtc::scoped_refptr<PeerConnection> pc_;
768 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
769};
770
deadbeef293e9262017-01-11 12:28:30 -0800771bool PeerConnectionInterface::RTCConfiguration::operator==(
772 const PeerConnectionInterface::RTCConfiguration& o) const {
773 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700774 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800775 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000776 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700777 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800778 BundlePolicy bundle_policy;
779 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700780 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
781 int ice_candidate_pool_size;
782 bool disable_ipv6;
783 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700784 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100785 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700786 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200787 absl::optional<int> screencast_min_bitrate;
788 absl::optional<bool> combined_audio_video_bwe;
789 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800790 TcpCandidatePolicy tcp_candidate_policy;
791 CandidateNetworkPolicy candidate_network_policy;
792 int audio_jitter_buffer_max_packets;
793 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100794 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100795 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800796 int ice_connection_receiving_timeout;
797 int ice_backup_candidate_pair_ping_interval;
798 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800799 bool prioritize_most_likely_ice_candidate_pairs;
800 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800801 bool prune_turn_ports;
802 bool presume_writable_when_fully_relayed;
803 bool enable_ice_renomination;
804 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700805 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200806 absl::optional<int> ice_check_interval_strong_connectivity;
807 absl::optional<int> ice_check_interval_weak_connectivity;
808 absl::optional<int> ice_check_min_interval;
809 absl::optional<int> ice_unwritable_timeout;
810 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800811 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200812 absl::optional<int> stun_candidate_keepalive_interval;
813 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200814 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800815 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200816 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700817 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700818 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700819 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700820 absl::optional<bool> use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700821 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100822 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800823 };
824 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
825 "Did you add something to RTCConfiguration and forget to "
826 "update operator==?");
827 return type == o.type && servers == o.servers &&
828 bundle_policy == o.bundle_policy &&
829 rtcp_mux_policy == o.rtcp_mux_policy &&
830 tcp_candidate_policy == o.tcp_candidate_policy &&
831 candidate_network_policy == o.candidate_network_policy &&
832 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
833 audio_jitter_buffer_fast_accelerate ==
834 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100835 audio_jitter_buffer_min_delay_ms ==
836 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100837 audio_jitter_buffer_enable_rtx_handling ==
838 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800839 ice_connection_receiving_timeout ==
840 o.ice_connection_receiving_timeout &&
841 ice_backup_candidate_pair_ping_interval ==
842 o.ice_backup_candidate_pair_ping_interval &&
843 continual_gathering_policy == o.continual_gathering_policy &&
844 certificates == o.certificates &&
845 prioritize_most_likely_ice_candidate_pairs ==
846 o.prioritize_most_likely_ice_candidate_pairs &&
847 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800848 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700849 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100850 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800851 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800852 screencast_min_bitrate == o.screencast_min_bitrate &&
853 combined_audio_video_bwe == o.combined_audio_video_bwe &&
854 enable_dtls_srtp == o.enable_dtls_srtp &&
855 ice_candidate_pool_size == o.ice_candidate_pool_size &&
856 prune_turn_ports == o.prune_turn_ports &&
857 presume_writable_when_fully_relayed ==
858 o.presume_writable_when_fully_relayed &&
859 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800860 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700861 surface_ice_candidates_on_ice_transport_type_changed ==
862 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800863 ice_check_interval_strong_connectivity ==
864 o.ice_check_interval_strong_connectivity &&
865 ice_check_interval_weak_connectivity ==
866 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700867 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700868 ice_unwritable_timeout == o.ice_unwritable_timeout &&
869 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800870 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800871 stun_candidate_keepalive_interval ==
872 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200873 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800874 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800875 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700876 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700877 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700878 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700879 use_media_transport_for_data_channels ==
880 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700881 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100882 crypto_options == o.crypto_options &&
883 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800884}
885
886bool PeerConnectionInterface::RTCConfiguration::operator!=(
887 const PeerConnectionInterface::RTCConfiguration& o) const {
888 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800889}
890
zhihuang8f65cdf2016-05-06 18:40:30 -0700891// Generate a RTCP CNAME when a PeerConnection is created.
892std::string GenerateRtcpCname() {
893 std::string cname;
894 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800896 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700897 }
898 return cname;
899}
900
zhihuang1c378ed2017-08-17 14:10:50 -0700901bool ValidateOfferAnswerOptions(
902 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
903 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
904 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700905}
906
zhihuang1c378ed2017-08-17 14:10:50 -0700907// From |rtc_options|, fill parts of |session_options| shared by all generated
908// m= sections (in other words, nothing that involves a map/array).
909void ExtractSharedMediaSessionOptions(
910 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
911 cricket::MediaSessionOptions* session_options) {
912 session_options->vad_enabled = rtc_options.voice_activity_detection;
913 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200914 session_options->raw_packetization_for_video =
915 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700916}
zhihuanga77e6bb2017-08-14 18:17:48 -0700917
zhihuang38ede132017-06-15 12:52:32 -0700918PeerConnection::PeerConnection(PeerConnectionFactory* factory,
919 std::unique_ptr<RtcEventLog> event_log,
920 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700922 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100923 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700924 datagram_transport_config_(
925 field_trial::FindFullName(kDatagramTransportFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700926 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700927 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700928 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100929 call_(std::move(call)),
Henrik Boström79b69802019-07-18 11:16:56 +0200930 call_ptr_(call_.get()),
931 local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932
933PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100934 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800935 RTC_DCHECK_RUN_ON(signaling_thread());
936
Steve Anton8af21862017-12-15 11:20:13 -0800937 // Need to stop transceivers before destroying the stats collector because
938 // AudioRtpSender has a reference to the StatsCollector it will update when
939 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100940 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800941 transceiver->Stop();
942 }
Steve Anton4171afb2017-11-20 10:20:22 -0800943
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700944 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800945 if (stats_collector_) {
946 stats_collector_->WaitForPendingRequest();
947 stats_collector_ = nullptr;
948 }
Steve Anton75737c02017-11-06 10:37:17 -0800949
Steve Anton8af21862017-12-15 11:20:13 -0800950 // Don't destroy BaseChannels until after stats has been cleaned up so that
951 // the last stats request can still read from the channels.
952 DestroyAllChannels();
953
Mirko Bonadei675513b2017-11-09 11:09:25 +0100954 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800955
956 webrtc_session_desc_factory_.reset();
957 sctp_invoker_.reset();
958 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800959 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800960 transport_controller_.reset();
961
deadbeef91dd5672016-05-18 16:55:30 -0700962 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100963 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
964 RTC_DCHECK_RUN_ON(network_thread());
965 port_allocator_.reset();
966 });
eladalon248fd4f2017-09-06 05:18:15 -0700967 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700968 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100969 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700970 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800971 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700972 event_log_.reset();
973 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974}
975
Steve Anton8af21862017-12-15 11:20:13 -0800976void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800977 // Destroy video channels first since they may have a pointer to a voice
978 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100979 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800980 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800981 DestroyTransceiverChannel(transceiver);
982 }
983 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100984 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800985 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800986 DestroyTransceiverChannel(transceiver);
987 }
988 }
989 DestroyDataChannel();
990}
991
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000993 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700994 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100995 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100996 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100997 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700998
999 RTCError config_error = ValidateConfiguration(configuration);
1000 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001001 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -07001002 return false;
1003 }
1004
Benjamin Wrightcab58882018-05-02 15:12:47 -07001005 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001006 RTC_LOG(LS_ERROR)
1007 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001008 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -08001009 return false;
1010 }
Jonas Orelandbdcee282017-10-10 14:01:40 +02001011
Benjamin Wrightcab58882018-05-02 15:12:47 -07001012 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -08001013 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001014 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +01001015 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -08001016 return false;
1017 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001018
Benjamin Wrightcab58882018-05-02 15:12:47 -07001019 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -07001020 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -07001021 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001022 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -08001023
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001024 cricket::ServerAddresses stun_servers;
1025 std::vector<cricket::RelayServerConfig> turn_servers;
1026
1027 RTCErrorType parse_error =
1028 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1029 if (parse_error != RTCErrorType::NONE) {
1030 return false;
1031 }
1032
deadbeef91dd5672016-05-18 16:55:30 -07001033 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001034 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +01001035 const auto pa_result =
1036 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001037 RTC_FROM_HERE,
1038 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +01001039 stun_servers, turn_servers, configuration));
1040
Harald Alvestrandb2a74782018-06-28 13:54:07 +02001041 // If initialization was successful, note if STUN or TURN servers
1042 // were supplied.
1043 if (!stun_servers.empty()) {
1044 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
1045 }
1046 if (!turn_servers.empty()) {
1047 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
1048 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001050 // Send information about IPv4/IPv6 status.
1051 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001052 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001053 address_family = kPeerConnection_IPv6;
1054 } else {
1055 address_family = kPeerConnection_IPv4;
1056 }
1057 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1058 kPeerConnectionAddressFamilyCounter_Max);
1059
Zhi Huange830e682018-03-30 10:48:35 -07001060 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1061
Steve Anton75737c02017-11-06 10:37:17 -08001062 // RFC 3264: The numeric value of the session id and version in the
1063 // o line MUST be representable with a "64 bit signed integer".
1064 // Due to this constraint session id |session_id_| is max limited to
1065 // LLONG_MAX.
1066 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001067 JsepTransportController::Config config;
1068 config.redetermine_role_on_ice_restart =
1069 configuration.redetermine_role_on_ice_restart;
1070 config.ssl_max_version = factory_->options().ssl_max_version;
1071 config.disable_encryption = options.disable_encryption;
1072 config.bundle_policy = configuration.bundle_policy;
1073 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001074 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1075 // stub.
1076 config.crypto_options = configuration.crypto_options.has_value()
1077 ? *configuration.crypto_options
1078 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001079 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001080 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001081#if defined(ENABLE_EXTERNAL_AUTH)
1082 config.enable_external_auth = true;
1083#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001084 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001085
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001086 use_datagram_transport_ = datagram_transport_config_.enabled &&
Bjorn A Mellem238aab92019-07-02 11:06:00 -07001087 configuration.use_datagram_transport.value_or(
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001088 datagram_transport_config_.default_value);
1089 if (use_datagram_transport_ || configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001090 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001091 if (!factory_->media_transport_factory()) {
1092 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001093 << "PeerConnecton is initialized with use_media_transport = true or "
1094 << "use_media_transport_for_data_channels = true "
1095 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001096 return false;
1097 }
1098
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001099 if (configuration.use_media_transport ||
1100 configuration.use_media_transport_for_data_channels) {
1101 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1102 // RTP media transport is introduced. But until then, we require SDES to
1103 // be enabled.
1104 if (configuration.enable_dtls_srtp.has_value() &&
1105 configuration.enable_dtls_srtp.value()) {
1106 RTC_LOG(LS_WARNING)
1107 << "When media transport is used, SDES must be enabled. Set "
1108 "configuration.enable_dtls_srtp to false. use_media_transport="
1109 << configuration.use_media_transport
1110 << ", use_media_transport_for_data_channels="
1111 << configuration.use_media_transport_for_data_channels;
1112 return false;
1113 }
1114 }
1115
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001116 config.use_media_transport_for_media = configuration.use_media_transport;
1117 config.use_media_transport_for_data_channels =
1118 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001119 config.use_datagram_transport = use_datagram_transport_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001120 config.media_transport_factory = factory_->media_transport_factory();
1121 }
1122
Zhi Huange830e682018-03-30 10:48:35 -07001123 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001124 signaling_thread(), network_thread(), port_allocator_.get(),
1125 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001126 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001127 this, &PeerConnection::OnTransportControllerConnectionState);
1128 transport_controller_->SignalStandardizedIceConnectionState.connect(
1129 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001130 transport_controller_->SignalConnectionState.connect(
1131 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001132 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001133 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001134 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001135 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001136 transport_controller_->SignalIceCandidateError.connect(
1137 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001138 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001139 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1140 transport_controller_->SignalDtlsHandshakeError.connect(
1141 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Alex Drake00c7ecf2019-08-06 10:54:47 -07001142 transport_controller_->SignalIceCandidatePairChanged.connect(
1143 this, &PeerConnection::OnTransportControllerCandidateChanged);
Steve Anton75737c02017-11-06 10:37:17 -08001144
1145 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001146
deadbeefab9b2d12015-10-14 11:33:11 -07001147 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001148 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001149
Steve Antonba818672017-11-06 10:21:57 -08001150 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001151 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001152
Steve Anton75737c02017-11-06 10:37:17 -08001153 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1154 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1155 if (!configuration.certificates.empty()) {
1156 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1157 // just picking the first one. The decision should be made based on the DTLS
1158 // handshake. The DTLS negotiations need to know about all certificates.
1159 certificate = configuration.certificates[0];
1160 }
1161
Steve Antond25da372017-11-06 14:50:29 -08001162 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001163
1164 if (options.disable_encryption) {
1165 dtls_enabled_ = false;
1166 } else {
1167 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001168 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001169 // |configuration| can override the default |dtls_enabled_| value.
1170 if (configuration.enable_dtls_srtp) {
1171 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1172 }
1173 }
1174
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001175 if (configuration.use_media_transport_for_data_channels) {
1176 if (configuration.enable_rtp_data_channel) {
1177 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1178 "use_media_transport_for_data_channels are "
1179 "incompatible and cannot both be set to true";
1180 return false;
1181 }
1182 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1183 } else if (configuration.enable_rtp_data_channel) {
1184 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1185 // set. It takes precendence over the disable_sctp_data_channels
1186 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001187 data_channel_type_ = cricket::DCT_RTP;
1188 } else {
1189 // DTLS has to be enabled to use SCTP.
1190 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1191 data_channel_type_ = cricket::DCT_SCTP;
1192 }
1193 }
1194
1195 video_options_.screencast_min_bitrate_kbps =
1196 configuration.screencast_min_bitrate;
1197 audio_options_.combined_audio_video_bwe =
1198 configuration.combined_audio_video_bwe;
1199
1200 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001201 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001202
1203 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001204 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001205
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001206 audio_options_.audio_jitter_buffer_min_delay_ms =
1207 configuration.audio_jitter_buffer_min_delay_ms;
1208
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001209 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1210 configuration.audio_jitter_buffer_enable_rtx_handling;
1211
Steve Anton75737c02017-11-06 10:37:17 -08001212 // Whether the certificate generator/certificate is null or not determines
1213 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1214 // the right instructions by clearing the variables if needed.
1215 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001216 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001217 certificate = nullptr;
1218 } else if (certificate) {
1219 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001220 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001221 }
1222
1223 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1224 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001225 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001226 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1227 this, &PeerConnection::OnCertificateReady);
1228
1229 if (options.disable_encryption) {
1230 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1231 }
1232
1233 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001234 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001235 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236
Steve Anton4171afb2017-11-20 10:20:22 -08001237 // Add default audio/video transceivers for Plan B SDP.
1238 if (!IsUnifiedPlan()) {
1239 transceivers_.push_back(
1240 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1241 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1242 transceivers_.push_back(
1243 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1244 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1245 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001246 int delay_ms =
1247 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001248 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1249 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001250
1251 if (dependencies.video_bitrate_allocator_factory) {
1252 video_bitrate_allocator_factory_ =
1253 std::move(dependencies.video_bitrate_allocator_factory);
1254 } else {
1255 video_bitrate_allocator_factory_ =
1256 CreateBuiltinVideoBitrateAllocatorFactory();
1257 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 return true;
1259}
1260
Steve Anton038834f2017-07-14 15:59:59 -07001261RTCError PeerConnection::ValidateConfiguration(
1262 const RTCConfiguration& config) const {
1263 if (config.ice_regather_interval_range &&
1264 config.continual_gathering_policy == GATHER_ONCE) {
1265 return RTCError(RTCErrorType::INVALID_PARAMETER,
1266 "ice_regather_interval_range specified but continual "
1267 "gathering policy is GATHER_ONCE");
1268 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001269 auto result =
1270 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1271 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001272}
1273
Yves Gerey665174f2018-06-19 15:03:05 +02001274rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001275 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001276 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1277 "Plan SdpSemantics. Please use GetSenders "
1278 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001279 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280}
1281
Yves Gerey665174f2018-06-19 15:03:05 +02001282rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001283 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001284 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1285 "Plan SdpSemantics. Please use GetReceivers "
1286 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001287 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288}
1289
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001290bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001291 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001292 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1293 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001294 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 if (IsClosed()) {
1296 return false;
1297 }
deadbeefab9b2d12015-10-14 11:33:11 -07001298 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 return false;
1300 }
deadbeefab9b2d12015-10-14 11:33:11 -07001301
1302 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001303 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1304 observer->SignalAudioTrackAdded.connect(this,
1305 &PeerConnection::OnAudioTrackAdded);
1306 observer->SignalAudioTrackRemoved.connect(
1307 this, &PeerConnection::OnAudioTrackRemoved);
1308 observer->SignalVideoTrackAdded.connect(this,
1309 &PeerConnection::OnVideoTrackAdded);
1310 observer->SignalVideoTrackRemoved.connect(
1311 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001312 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001313
deadbeefab9b2d12015-10-14 11:33:11 -07001314 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001315 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001316 }
1317 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001318 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001319 }
1320
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001321 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001322 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 return true;
1324}
1325
1326void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001327 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001328 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1329 "Plan SdpSemantics. Please use RemoveTrack "
1330 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001331 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001332 if (!IsClosed()) {
1333 for (const auto& track : local_stream->GetAudioTracks()) {
1334 RemoveAudioTrack(track.get(), local_stream);
1335 }
1336 for (const auto& track : local_stream->GetVideoTracks()) {
1337 RemoveVideoTrack(track.get(), local_stream);
1338 }
deadbeefab9b2d12015-10-14 11:33:11 -07001339 }
deadbeefab9b2d12015-10-14 11:33:11 -07001340 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001341 stream_observers_.erase(
1342 std::remove_if(
1343 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001344 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001345 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001346 }),
1347 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001348
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 if (IsClosed()) {
1350 return;
1351 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001352 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353}
1354
Steve Anton2d6c76a2018-01-05 17:10:52 -08001355RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001356 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001357 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001358 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001359 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001360 if (!track) {
1361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1362 }
1363 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1364 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1365 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1366 "Track has invalid kind: " + track->kind());
1367 }
Steve Antonf9381f02017-12-14 10:23:57 -08001368 if (IsClosed()) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1370 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001371 }
Steve Anton4171afb2017-11-20 10:20:22 -08001372 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001373 LOG_AND_RETURN_ERROR(
1374 RTCErrorType::INVALID_PARAMETER,
1375 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001376 }
Steve Antonf9381f02017-12-14 10:23:57 -08001377 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001378 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1379 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001380 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001381 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001382 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001383 }
1384 return sender_or_error;
1385}
deadbeefe1f9d832016-01-14 15:35:42 -08001386
Steve Antonf9381f02017-12-14 10:23:57 -08001387RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1388PeerConnection::AddTrackPlanB(
1389 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001390 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001391 if (stream_ids.size() > 1u) {
1392 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1393 "AddTrack with more than one stream is not "
1394 "supported with Plan B semantics.");
1395 }
1396 std::vector<std::string> adjusted_stream_ids = stream_ids;
1397 if (adjusted_stream_ids.empty()) {
1398 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1399 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001400 cricket::MediaType media_type =
1401 (track->kind() == MediaStreamTrackInterface::kAudioKind
1402 ? cricket::MEDIA_TYPE_AUDIO
1403 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001404 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001405 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001406 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001407 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001408 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001409 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001410 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001411 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001412 if (sender_info) {
1413 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001414 }
Steve Antonf9381f02017-12-14 10:23:57 -08001415 } else {
1416 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001417 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001418 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001419 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001420 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001421 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001422 if (sender_info) {
1423 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001424 }
deadbeefe1f9d832016-01-14 15:35:42 -08001425 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001426 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001427}
deadbeefe1f9d832016-01-14 15:35:42 -08001428
Steve Antonf9381f02017-12-14 10:23:57 -08001429RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1430PeerConnection::AddTrackUnifiedPlan(
1431 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001432 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001433 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1434 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001435 RTC_LOG(LS_INFO) << "Reusing an existing "
1436 << cricket::MediaTypeToString(transceiver->media_type())
1437 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001438 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001439 transceiver->internal()->set_direction(
1440 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001441 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001442 transceiver->internal()->set_direction(
1443 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001444 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001445 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001446 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001447 } else {
1448 cricket::MediaType media_type =
1449 (track->kind() == MediaStreamTrackInterface::kAudioKind
1450 ? cricket::MEDIA_TYPE_AUDIO
1451 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001452 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1453 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001454 std::string sender_id = track->id();
1455 // Avoid creating a sender with an existing ID by generating a random ID.
1456 // This can happen if this is the second time AddTrack has created a sender
1457 // for this track.
1458 if (FindSenderById(sender_id)) {
1459 sender_id = rtc::CreateRandomUuid();
1460 }
Florent Castelli892acf02018-10-01 22:47:20 +02001461 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001462 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1463 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001464 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001465 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001466 }
Steve Antonf9381f02017-12-14 10:23:57 -08001467 return transceiver->sender();
1468}
1469
1470rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1471PeerConnection::FindFirstTransceiverForAddedTrack(
1472 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1473 RTC_DCHECK(track);
1474 for (auto transceiver : transceivers_) {
1475 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001476 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001477 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001478 !transceiver->internal()->has_ever_been_used_to_send() &&
1479 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001480 return transceiver;
1481 }
1482 }
1483 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001484}
1485
1486bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1487 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001488 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001489}
1490
Steve Anton24db5732018-07-23 10:27:33 -07001491RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001492 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001493 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001494 if (!sender) {
1495 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1496 }
deadbeefe1f9d832016-01-14 15:35:42 -08001497 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1499 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001500 }
Steve Antonf9381f02017-12-14 10:23:57 -08001501 if (IsUnifiedPlan()) {
1502 auto transceiver = FindTransceiverBySender(sender);
1503 if (!transceiver || !sender->track()) {
1504 return RTCError::OK();
1505 }
1506 sender->SetTrack(nullptr);
1507 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001508 transceiver->internal()->set_direction(
1509 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001510 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001511 transceiver->internal()->set_direction(
1512 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001513 }
Steve Anton4171afb2017-11-20 10:20:22 -08001514 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001515 bool removed;
1516 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1517 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1518 } else {
1519 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1520 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1521 }
1522 if (!removed) {
1523 LOG_AND_RETURN_ERROR(
1524 RTCErrorType::INVALID_PARAMETER,
1525 "Couldn't find sender " + sender->id() + " to remove.");
1526 }
Steve Anton4171afb2017-11-20 10:20:22 -08001527 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001528 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001529 return RTCError::OK();
1530}
1531
1532rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1533PeerConnection::FindTransceiverBySender(
1534 rtc::scoped_refptr<RtpSenderInterface> sender) {
1535 for (auto transceiver : transceivers_) {
1536 if (transceiver->sender() == sender) {
1537 return transceiver;
1538 }
1539 }
1540 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001541}
1542
Steve Anton9158ef62017-11-27 13:01:52 -08001543RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1544PeerConnection::AddTransceiver(
1545 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1546 return AddTransceiver(track, RtpTransceiverInit());
1547}
1548
1549RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1550PeerConnection::AddTransceiver(
1551 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1552 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001553 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001554 RTC_CHECK(IsUnifiedPlan())
1555 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001556 if (!track) {
1557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1558 }
1559 cricket::MediaType media_type;
1560 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1561 media_type = cricket::MEDIA_TYPE_AUDIO;
1562 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1563 media_type = cricket::MEDIA_TYPE_VIDEO;
1564 } else {
1565 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1566 "Track kind is not audio or video");
1567 }
1568 return AddTransceiver(media_type, track, init);
1569}
1570
1571RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1572PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1573 return AddTransceiver(media_type, RtpTransceiverInit());
1574}
1575
1576RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1577PeerConnection::AddTransceiver(cricket::MediaType media_type,
1578 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001579 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001580 RTC_CHECK(IsUnifiedPlan())
1581 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001582 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1583 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1584 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1585 "media type is not audio or video");
1586 }
1587 return AddTransceiver(media_type, nullptr, init);
1588}
1589
1590RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1591PeerConnection::AddTransceiver(
1592 cricket::MediaType media_type,
1593 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001594 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001595 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001596 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1597 media_type == cricket::MEDIA_TYPE_VIDEO));
1598 if (track) {
1599 RTC_DCHECK_EQ(media_type,
1600 (track->kind() == MediaStreamTrackInterface::kAudioKind
1601 ? cricket::MEDIA_TYPE_AUDIO
1602 : cricket::MEDIA_TYPE_VIDEO));
1603 }
1604
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001605 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1606 init.send_encodings.size(), 0, 7, 8);
1607
Amit Hilbuchaa584152019-02-06 17:09:52 -08001608 size_t num_rids = absl::c_count_if(init.send_encodings,
1609 [](const RtpEncodingParameters& encoding) {
1610 return !encoding.rid.empty();
1611 });
1612 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001613 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001614 RTCErrorType::INVALID_PARAMETER,
1615 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001616 }
1617
Amit Hilbuchf4770402019-04-08 14:11:57 -07001618 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1619 [](const RtpEncodingParameters& encoding) {
1620 return !IsLegalRsidName(encoding.rid);
1621 })) {
1622 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1623 "Invalid RID value provided.");
1624 }
1625
Amit Hilbuchaa584152019-02-06 17:09:52 -08001626 if (absl::c_any_of(init.send_encodings,
1627 [](const RtpEncodingParameters& encoding) {
1628 return encoding.ssrc.has_value();
1629 })) {
1630 LOG_AND_RETURN_ERROR(
1631 RTCErrorType::UNSUPPORTED_PARAMETER,
1632 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001633 }
1634
1635 RtpParameters parameters;
1636 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001637
1638 // Encodings are dropped from the tail if too many are provided.
1639 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1640 parameters.encodings.erase(
1641 parameters.encodings.begin() + kMaxSimulcastStreams,
1642 parameters.encodings.end());
1643 }
1644
1645 // Single RID should be removed.
1646 if (parameters.encodings.size() == 1 &&
1647 !parameters.encodings[0].rid.empty()) {
1648 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1649 parameters.encodings[0].rid.clear();
1650 }
1651
1652 // If RIDs were not provided, they are generated for simulcast scenario.
1653 if (parameters.encodings.size() > 1 && num_rids == 0) {
1654 rtc::UniqueStringGenerator rid_generator;
1655 for (RtpEncodingParameters& encoding : parameters.encodings) {
1656 encoding.rid = rid_generator();
1657 }
1658 }
1659
Florent Castelli892acf02018-10-01 22:47:20 +02001660 if (UnimplementedRtpParameterHasValue(parameters)) {
1661 LOG_AND_RETURN_ERROR(
1662 RTCErrorType::UNSUPPORTED_PARAMETER,
1663 "Attempted to set an unimplemented parameter of RtpParameters.");
1664 }
Steve Anton9158ef62017-11-27 13:01:52 -08001665
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001666 auto result = cricket::CheckRtpParametersValues(parameters);
1667 if (!result.ok()) {
1668 LOG_AND_RETURN_ERROR(result.type(), result.message());
1669 }
1670
Steve Anton3d954a62018-04-02 11:27:23 -07001671 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1672 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001673 // Set the sender ID equal to the track ID if the track is specified unless
1674 // that sender ID is already in use.
1675 std::string sender_id =
1676 (track && !FindSenderById(track->id()) ? track->id()
1677 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001678 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001679 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001680 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1681 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1682 transceiver->internal()->set_direction(init.direction);
1683
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001684 if (update_negotiation_needed) {
1685 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001686 }
Steve Antonf9381f02017-12-14 10:23:57 -08001687
1688 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1689}
1690
Steve Anton02ee47c2018-01-10 16:26:06 -08001691rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1692PeerConnection::CreateSender(
1693 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001694 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001695 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001696 const std::vector<std::string>& stream_ids,
1697 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001698 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001699 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001700 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1701 RTC_DCHECK(!track ||
1702 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1703 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1704 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001705 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001706 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001707 } else {
1708 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1709 RTC_DCHECK(!track ||
1710 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1711 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001712 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001713 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001714 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001715 bool set_track_succeeded = sender->SetTrack(track);
1716 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001717 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001718 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001719 return sender;
1720}
1721
1722rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1723PeerConnection::CreateReceiver(cricket::MediaType media_type,
1724 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001725 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1726 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001727 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001728 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001729 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1730 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001731 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001732 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001733 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001734 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001735 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1736 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001737 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001738 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001739 return receiver;
1740}
1741
1742rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1743PeerConnection::CreateAndAddTransceiver(
1744 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1745 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1746 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001747 // Ensure that the new sender does not have an ID that is already in use by
1748 // another sender.
1749 // Allow receiver IDs to conflict since those come from remote SDP (which
1750 // could be invalid, but should not cause a crash).
1751 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001752 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001753 signaling_thread(),
1754 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001755 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001756 transceiver->internal()->SignalNegotiationNeeded.connect(
1757 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001758 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001759}
1760
Steve Anton52d86772018-02-20 15:48:12 -08001761void PeerConnection::OnNegotiationNeeded() {
1762 RTC_DCHECK_RUN_ON(signaling_thread());
1763 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001764 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001765}
1766
deadbeeffac06552015-11-25 11:26:01 -08001767rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001768 const std::string& kind,
1769 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001770 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001771 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1772 "Plan SdpSemantics. Please use AddTransceiver "
1773 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001774 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001775 if (IsClosed()) {
1776 return nullptr;
1777 }
Steve Anton4171afb2017-11-20 10:20:22 -08001778
Seth Hampson5b4f0752018-04-02 16:31:36 -07001779 // Internally we need to have one stream with Plan B semantics, so we
1780 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001781 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001782 if (stream_id.empty()) {
1783 stream_ids.push_back(rtc::CreateRandomUuid());
1784 RTC_LOG(LS_INFO)
1785 << "No stream_id specified for sender. Generated stream ID: "
1786 << stream_ids[0];
1787 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001788 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001789 }
1790
Steve Anton4171afb2017-11-20 10:20:22 -08001791 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001792 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001793 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001794 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001795 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001796 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001797 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001798 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001799 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001800 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001801 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001802 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001803 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001804 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001805 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001806 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001807 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001808 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001809 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001810 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001811 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001812
deadbeefe1f9d832016-01-14 15:35:42 -08001813 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001814}
1815
deadbeef70ab1a12015-09-28 16:53:55 -07001816std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1817 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001818 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001819 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001820 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001821 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001822 }
1823 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001824}
1825
Steve Anton4171afb2017-11-20 10:20:22 -08001826std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1827PeerConnection::GetSendersInternal() const {
1828 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1829 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001830 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001831 auto senders = transceiver->internal()->senders();
1832 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1833 }
1834 return all_senders;
1835}
1836
deadbeef70ab1a12015-09-28 16:53:55 -07001837std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1838PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001839 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001840 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001841 for (const auto& receiver : GetReceiversInternal()) {
1842 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001843 }
1844 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001845}
1846
Steve Anton4171afb2017-11-20 10:20:22 -08001847std::vector<
1848 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1849PeerConnection::GetReceiversInternal() const {
1850 std::vector<
1851 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1852 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001853 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001854 auto receivers = transceiver->internal()->receivers();
1855 all_receivers.insert(all_receivers.end(), receivers.begin(),
1856 receivers.end());
1857 }
1858 return all_receivers;
1859}
1860
Steve Anton9158ef62017-11-27 13:01:52 -08001861std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1862PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001863 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001864 RTC_CHECK(IsUnifiedPlan())
1865 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001866 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001867 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001868 all_transceivers.push_back(transceiver);
1869 }
1870 return all_transceivers;
1871}
1872
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001873bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001874 MediaStreamTrackInterface* track,
1875 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001876 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001877 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001878 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001879 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001880 return false;
1881 }
1882
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001883 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001884 // The StatsCollector is used to tell if a track is valid because it may
1885 // remember tracks that the PeerConnection previously removed.
1886 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001887 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1888 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001889 return false;
1890 }
Steve Antonad182762018-09-05 20:22:40 +00001891 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1892 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 return true;
1894}
1895
hbos74e1a4f2016-09-15 23:33:01 -07001896void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001897 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001898 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001899 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001900 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001901 stats_collector_->GetStatsReport(callback);
1902}
1903
Henrik Boström1df1bf82018-03-20 13:24:20 +01001904void PeerConnection::GetStats(
1905 rtc::scoped_refptr<RtpSenderInterface> selector,
1906 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1907 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001908 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001909 RTC_DCHECK(callback);
1910 RTC_DCHECK(stats_collector_);
1911 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1912 if (selector) {
1913 for (const auto& proxy_transceiver : transceivers_) {
1914 for (const auto& proxy_sender :
1915 proxy_transceiver->internal()->senders()) {
1916 if (proxy_sender == selector) {
1917 internal_sender = proxy_sender->internal();
1918 break;
1919 }
1920 }
1921 if (internal_sender)
1922 break;
1923 }
1924 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001925 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001926 // belong to the PeerConnection (in Plan B, senders can be removed from the
1927 // PeerConnection). This means that "all the stats objects representing the
1928 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1929 // produces an empty stats report.
1930 stats_collector_->GetStatsReport(internal_sender, callback);
1931}
1932
1933void PeerConnection::GetStats(
1934 rtc::scoped_refptr<RtpReceiverInterface> selector,
1935 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1936 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001937 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001938 RTC_DCHECK(callback);
1939 RTC_DCHECK(stats_collector_);
1940 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1941 if (selector) {
1942 for (const auto& proxy_transceiver : transceivers_) {
1943 for (const auto& proxy_receiver :
1944 proxy_transceiver->internal()->receivers()) {
1945 if (proxy_receiver == selector) {
1946 internal_receiver = proxy_receiver->internal();
1947 break;
1948 }
1949 }
1950 if (internal_receiver)
1951 break;
1952 }
1953 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001954 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001955 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1956 // the PeerConnection). This means that "all the stats objects representing
1957 // the selector" is an empty set. Invoking GetStatsReport() with a null
1958 // selector produces an empty stats report.
1959 stats_collector_->GetStatsReport(internal_receiver, callback);
1960}
1961
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001962PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001963 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 return signaling_state_;
1965}
1966
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967PeerConnectionInterface::IceConnectionState
1968PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001969 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 return ice_connection_state_;
1971}
1972
Alex Loiko9289eda2018-11-23 16:18:59 +00001973PeerConnectionInterface::IceConnectionState
1974PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001975 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001976 return standardized_ice_connection_state_;
1977}
1978
Jonas Olsson635474e2018-10-18 15:58:17 +02001979PeerConnectionInterface::PeerConnectionState
1980PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001981 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001982 return connection_state_;
1983}
1984
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985PeerConnectionInterface::IceGatheringState
1986PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001987 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001988 return ice_gathering_state_;
1989}
1990
Yves Gerey665174f2018-06-19 15:03:05 +02001991rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 const std::string& label,
1993 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001994 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001995 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001996
deadbeefab9b2d12015-10-14 11:33:11 -07001997 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001998
kwibergd1fe2812016-04-27 06:47:29 -07001999 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002000 if (config) {
2001 internal_config.reset(new InternalDataChannelInit(*config));
2002 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002003 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07002004 InternalCreateDataChannel(label, internal_config.get()));
2005 if (!channel.get()) {
2006 return nullptr;
2007 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002009 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
2010 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08002011 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002012 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00002013 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002014 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 return DataChannelProxy::Create(signaling_thread(), channel.get());
2016}
2017
Henrik Boström79b69802019-07-18 11:16:56 +02002018void PeerConnection::RestartIce() {
2019 RTC_DCHECK_RUN_ON(signaling_thread());
2020 local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
2021 current_local_description_.get(), pending_local_description_.get());
2022 UpdateNegotiationNeeded();
2023}
2024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002026 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002027 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002028 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07002029
nisse7ce109a2017-01-31 00:57:56 -08002030 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002031 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00002032 return;
2033 }
deadbeefab9b2d12015-10-14 11:33:11 -07002034
Steve Anton8d3444d2017-10-20 15:30:51 -07002035 if (IsClosed()) {
2036 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002037 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002038 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002039 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002040 return;
2041 }
2042
Steve Anton25ca0ac2019-06-25 10:40:48 -07002043 // If a session error has occurred the PeerConnection is in a possibly
2044 // inconsistent state so fail right away.
2045 if (session_error() != SessionError::kNone) {
2046 std::string error_message = GetSessionErrorMsg();
2047 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
2048 PostCreateSessionDescriptionFailure(
2049 observer,
2050 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2051 return;
2052 }
2053
zhihuang1c378ed2017-08-17 14:10:50 -07002054 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002055 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002056 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002057 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002058 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002059 return;
2060 }
2061
Steve Anton22da89f2018-01-25 13:58:07 -08002062 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2063 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2064 if (IsUnifiedPlan()) {
2065 RTCError error = HandleLegacyOfferOptions(options);
2066 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002067 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002068 return;
2069 }
2070 }
2071
zhihuang1c378ed2017-08-17 14:10:50 -07002072 cricket::MediaSessionOptions session_options;
2073 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002074 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002075}
2076
Steve Anton22da89f2018-01-25 13:58:07 -08002077RTCError PeerConnection::HandleLegacyOfferOptions(
2078 const RTCOfferAnswerOptions& options) {
2079 RTC_DCHECK(IsUnifiedPlan());
2080
2081 if (options.offer_to_receive_audio == 0) {
2082 RemoveRecvDirectionFromReceivingTransceiversOfType(
2083 cricket::MEDIA_TYPE_AUDIO);
2084 } else if (options.offer_to_receive_audio == 1) {
2085 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2086 } else if (options.offer_to_receive_audio > 1) {
2087 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2088 "offer_to_receive_audio > 1 is not supported.");
2089 }
2090
2091 if (options.offer_to_receive_video == 0) {
2092 RemoveRecvDirectionFromReceivingTransceiversOfType(
2093 cricket::MEDIA_TYPE_VIDEO);
2094 } else if (options.offer_to_receive_video == 1) {
2095 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2096 } else if (options.offer_to_receive_video > 1) {
2097 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2098 "offer_to_receive_video > 1 is not supported.");
2099 }
2100
2101 return RTCError::OK();
2102}
2103
2104void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2105 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002106 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002107 RtpTransceiverDirection new_direction =
2108 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2109 if (new_direction != transceiver->direction()) {
2110 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2111 << " transceiver (MID="
2112 << transceiver->mid().value_or("<not set>") << ") from "
2113 << RtpTransceiverDirectionToString(
2114 transceiver->direction())
2115 << " to "
2116 << RtpTransceiverDirectionToString(new_direction)
2117 << " since CreateOffer specified offer_to_receive=0";
2118 transceiver->internal()->set_direction(new_direction);
2119 }
Steve Anton22da89f2018-01-25 13:58:07 -08002120 }
2121}
2122
2123void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2124 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002125 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002126 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002127 RTC_LOG(LS_INFO)
2128 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2129 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002130 RtpTransceiverInit init;
2131 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002132 AddTransceiver(media_type, nullptr, init,
2133 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002134 }
2135}
2136
2137std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2138PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2139 std::vector<
2140 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2141 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002142 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002143 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002144 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2145 receiving_transceivers.push_back(transceiver);
2146 }
2147 }
2148 return receiving_transceivers;
2149}
2150
htaa2a49d92016-03-04 02:51:39 -08002151void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2152 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002153 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002154 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002155 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002156 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002157 return;
2158 }
2159
Steve Anton25ca0ac2019-06-25 10:40:48 -07002160 // If a session error has occurred the PeerConnection is in a possibly
2161 // inconsistent state so fail right away.
2162 if (session_error() != SessionError::kNone) {
2163 std::string error_message = GetSessionErrorMsg();
2164 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2165 PostCreateSessionDescriptionFailure(
2166 observer,
2167 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2168 return;
2169 }
2170
Steve Antondffead82018-02-06 10:31:29 -08002171 if (!(signaling_state_ == kHaveRemoteOffer ||
2172 signaling_state_ == kHaveLocalPrAnswer)) {
2173 std::string error =
2174 "PeerConnection cannot create an answer in a state other than "
2175 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002176 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002177 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002178 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002179 return;
2180 }
2181
Steve Antondffead82018-02-06 10:31:29 -08002182 // The remote description should be set if we're in the right state.
2183 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002184
Steve Anton22da89f2018-01-25 13:58:07 -08002185 if (IsUnifiedPlan()) {
2186 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2187 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2188 "supported with Unified Plan semantics. Use the "
2189 "RtpTransceiver API instead.";
2190 }
2191 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2192 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2193 "supported with Unified Plan semantics. Use the "
2194 "RtpTransceiver API instead.";
2195 }
2196 }
2197
htaa2a49d92016-03-04 02:51:39 -08002198 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002199 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002200
Steve Antond25da372017-11-06 14:50:29 -08002201 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202}
2203
2204void PeerConnection::SetLocalDescription(
2205 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002206 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002207 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002208 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002209
Steve Anton80dd7b52018-02-16 17:08:42 -08002210 // The SetLocalDescription contract is that we take ownership of the session
2211 // description regardless of the outcome, so wrap it in a unique_ptr right
2212 // away. Ideally, SetLocalDescription's signature will be changed to take the
2213 // description as a unique_ptr argument to formalize this agreement.
2214 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2215
nisse7ce109a2017-01-31 00:57:56 -08002216 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002217 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002218 return;
2219 }
Steve Anton8a006912017-12-04 15:25:56 -08002220
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002222 PostSetSessionDescriptionFailure(
2223 observer,
2224 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 return;
2226 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002227
Steve Anton80dd7b52018-02-16 17:08:42 -08002228 // If a session error has occurred the PeerConnection is in a possibly
2229 // inconsistent state so fail right away.
2230 if (session_error() != SessionError::kNone) {
2231 std::string error_message = GetSessionErrorMsg();
2232 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002233 PostSetSessionDescriptionFailure(
2234 observer,
2235 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002236 return;
2237 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002238
Steve Anton80dd7b52018-02-16 17:08:42 -08002239 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2240 if (!error.ok()) {
2241 std::string error_message = GetSetDescriptionErrorMessage(
2242 cricket::CS_LOCAL, desc->GetType(), error);
2243 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002244 PostSetSessionDescriptionFailure(
2245 observer,
2246 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002247 return;
2248 }
2249
2250 // Grab the description type before moving ownership to ApplyLocalDescription,
2251 // which may destroy it before returning.
2252 const SdpType type = desc->GetType();
2253
2254 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002255 // |desc| may be destroyed at this point.
2256
2257 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002258 // If ApplyLocalDescription fails, the PeerConnection could be in an
2259 // inconsistent state, so act conservatively here and set the session error
2260 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2261 SetSessionError(SessionError::kContent, error.message());
2262 std::string error_message =
2263 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2264 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002265 PostSetSessionDescriptionFailure(
2266 observer,
2267 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002268 return;
2269 }
Steve Anton8a006912017-12-04 15:25:56 -08002270 RTC_DCHECK(local_description());
2271
2272 PostSetSessionDescriptionSuccess(observer);
2273
Steve Antonad182762018-09-05 20:22:40 +00002274 // MaybeStartGathering needs to be called after posting
2275 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2276 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002277 transport_controller_->MaybeStartGathering();
2278
Steve Antona3a92c22017-12-07 10:27:41 -08002279 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002280 // TODO(deadbeef): We already had to hop to the network thread for
2281 // MaybeStartGathering...
2282 network_thread()->Invoke<void>(
2283 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2284 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002285 // Make UMA notes about what was agreed to.
2286 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002287 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002288
2289 if (IsUnifiedPlan()) {
2290 bool was_negotiation_needed = is_negotiation_needed_;
2291 UpdateNegotiationNeeded();
2292 if (signaling_state() == kStable && was_negotiation_needed &&
2293 is_negotiation_needed_) {
2294 Observer()->OnRenegotiationNeeded();
2295 }
2296 }
2297
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002298 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002299}
2300
2301RTCError PeerConnection::ApplyLocalDescription(
2302 std::unique_ptr<SessionDescriptionInterface> desc) {
2303 RTC_DCHECK_RUN_ON(signaling_thread());
2304 RTC_DCHECK(desc);
2305
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306 // Update stats here so that we have the most recent stats for tracks and
2307 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002308 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002309
Steve Antondcc3c022017-12-22 16:02:54 -08002310 // Take a reference to the old local description since it's used below to
2311 // compare against the new local description. When setting the new local
2312 // description, grab ownership of the replaced session description in case it
2313 // is the same as |old_local_description|, to keep it alive for the duration
2314 // of the method.
2315 const SessionDescriptionInterface* old_local_description =
2316 local_description();
2317 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002318 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002319 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002320 replaced_local_description = pending_local_description_
2321 ? std::move(pending_local_description_)
2322 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002323 current_local_description_ = std::move(desc);
2324 pending_local_description_ = nullptr;
2325 current_remote_description_ = std::move(pending_remote_description_);
2326 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002327 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002328 pending_local_description_ = std::move(desc);
2329 }
2330 // The session description to apply now must be accessed by
2331 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002332 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002333
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002334 // Report statistics about any use of simulcast.
2335 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2336 *local_description()->description());
2337
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002338 if (!is_caller_) {
2339 if (remote_description()) {
2340 // Remote description was applied first, so this PC is the callee.
2341 is_caller_ = false;
2342 } else {
2343 // Local description is applied first, so this PC is the caller.
2344 is_caller_ = true;
2345 }
2346 }
2347
Zhi Huange830e682018-03-30 10:48:35 -07002348 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2349 if (!error.ok()) {
2350 return error;
2351 }
2352
Steve Antondcc3c022017-12-22 16:02:54 -08002353 if (IsUnifiedPlan()) {
2354 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002355 cricket::CS_LOCAL, *local_description(), old_local_description,
2356 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002357 if (!error.ok()) {
2358 return error;
2359 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002360 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2361 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002362 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002363 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2364 // Note that code paths that don't set MID won't be able to use
2365 // information about DTLS transports.
2366 if (transceiver->mid()) {
2367 auto dtls_transport =
2368 LookupDtlsTransportByMidInternal(*transceiver->mid());
2369 transceiver->internal()->sender_internal()->set_transport(
2370 dtls_transport);
2371 transceiver->internal()->receiver_internal()->set_transport(
2372 dtls_transport);
2373 }
2374
Steve Antondcc3c022017-12-22 16:02:54 -08002375 const ContentInfo* content =
2376 FindMediaSectionForTransceiver(transceiver, local_description());
2377 if (!content) {
2378 continue;
2379 }
2380 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002381 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2382 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002383 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002384 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2385 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2386 // "recvonly", process the removal of a remote track for the media
2387 // description, given transceiver, removeList, and muteTracks.
2388 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2389 (transceiver->internal()->fired_direction() &&
2390 RtpTransceiverDirectionHasRecv(
2391 *transceiver->internal()->fired_direction()))) {
2392 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2393 &removed_streams);
2394 }
2395 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2396 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002397 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002398 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002399 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002400 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002401 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002402 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002403 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002404 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002405 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002406 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002407 }
2408 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002409 // Media channels will be created only when offer is set. These may use new
2410 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002411 if (type == SdpType::kOffer) {
2412 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2413 // description is applied. Restore back to old description.
2414 RTCError error = CreateChannels(*local_description()->description());
2415 if (!error.ok()) {
2416 return error;
2417 }
2418 }
Steve Antondcc3c022017-12-22 16:02:54 -08002419 // Remove unused channels if MediaContentDescription is rejected.
2420 RemoveUnusedChannels(local_description()->description());
2421 }
Steve Anton8a006912017-12-04 15:25:56 -08002422
Zhi Huange830e682018-03-30 10:48:35 -07002423 error = UpdateSessionState(type, cricket::CS_LOCAL,
2424 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002425 if (!error.ok()) {
2426 return error;
2427 }
Steve Antondcc3c022017-12-22 16:02:54 -08002428
Steve Anton8a006912017-12-04 15:25:56 -08002429 if (remote_description()) {
2430 // Now that we have a local description, we can push down remote candidates.
2431 UseCandidatesInSessionDescription(remote_description());
2432 }
2433
2434 pending_ice_restarts_.clear();
2435 if (session_error() != SessionError::kNone) {
2436 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2437 }
2438
deadbeefab9b2d12015-10-14 11:33:11 -07002439 // If setting the description decided our SSL role, allocate any necessary
2440 // SCTP sids.
2441 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002442 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002443 AllocateSctpSids(role);
2444 }
2445
Steve Antond3679212018-01-17 17:41:02 -08002446 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002447 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002448 const ContentInfo* content =
2449 FindMediaSectionForTransceiver(transceiver, local_description());
2450 if (!content) {
2451 continue;
2452 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002453 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2454 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002455 // 0 is a special value meaning "this sender has no associated send
2456 // stream". Need to call this so the sender won't attempt to configure
2457 // a no longer existing stream and run into DCHECKs in the lower
2458 // layers.
2459 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002460 } else {
2461 // Get the StreamParams from the channel which could generate SSRCs.
2462 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002463 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002464 streams[0].stream_ids());
2465 transceiver->internal()->sender_internal()->SetSsrc(
2466 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002467 }
2468 }
2469 } else {
2470 // Plan B semantics.
2471
Steve Antondcc3c022017-12-22 16:02:54 -08002472 // Update state and SSRC of local MediaStreams and DataChannels based on the
2473 // local session description.
2474 const cricket::ContentInfo* audio_content =
2475 GetFirstAudioContent(local_description()->description());
2476 if (audio_content) {
2477 if (audio_content->rejected) {
2478 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2479 } else {
2480 const cricket::AudioContentDescription* audio_desc =
2481 audio_content->media_description()->as_audio();
2482 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2483 }
deadbeeffaac4972015-11-12 15:33:07 -08002484 }
deadbeefab9b2d12015-10-14 11:33:11 -07002485
Steve Antondcc3c022017-12-22 16:02:54 -08002486 const cricket::ContentInfo* video_content =
2487 GetFirstVideoContent(local_description()->description());
2488 if (video_content) {
2489 if (video_content->rejected) {
2490 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2491 } else {
2492 const cricket::VideoContentDescription* video_desc =
2493 video_content->media_description()->as_video();
2494 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2495 }
deadbeeffaac4972015-11-12 15:33:07 -08002496 }
deadbeefab9b2d12015-10-14 11:33:11 -07002497 }
2498
2499 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002500 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002501 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002502 const cricket::RtpDataContentDescription* rtp_data_desc =
2503 data_content->media_description()->as_rtp_data();
2504 // rtp_data_desc will be null if this is an SCTP description.
2505 if (rtp_data_desc) {
2506 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002507 }
2508 }
2509
Henrik Boström79b69802019-07-18 11:16:56 +02002510 if (type == SdpType::kAnswer &&
2511 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2512 *current_local_description_)) {
2513 local_ice_credentials_to_replace_->ClearIceCredentials();
2514 }
2515
Steve Anton8a006912017-12-04 15:25:56 -08002516 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002517}
2518
Steve Anton06817cd2018-12-18 15:55:30 -08002519// The SDP parser used to populate these values by default for the 'content
2520// name' if an a=mid line was absent.
2521static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2522 switch (media_type) {
2523 case cricket::MEDIA_TYPE_AUDIO:
2524 return cricket::CN_AUDIO;
2525 case cricket::MEDIA_TYPE_VIDEO:
2526 return cricket::CN_VIDEO;
2527 case cricket::MEDIA_TYPE_DATA:
2528 return cricket::CN_DATA;
2529 }
2530 RTC_NOTREACHED();
2531 return "";
2532}
2533
2534void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002535 cricket::SessionDescription* new_remote_description) {
2536 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002537 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002538 const cricket::ContentInfos& local_contents =
2539 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002540 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002541 const cricket::ContentInfos& remote_contents =
2542 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002543 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002544 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2545 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002546 if (!content.name.empty()) {
2547 continue;
2548 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002549 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002550 absl::string_view source_explanation;
2551 if (IsUnifiedPlan()) {
2552 if (i < local_contents.size()) {
2553 new_mid = local_contents[i].name;
2554 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002555 } else if (i < remote_contents.size()) {
2556 new_mid = remote_contents[i].name;
2557 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002558 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002559 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002560 source_explanation = "generated just now";
2561 }
2562 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002563 new_mid = std::string(
2564 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002565 source_explanation = "to match pre-existing behavior";
2566 }
Steve Antond7180cc2019-02-07 10:44:53 -08002567 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002568 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002569 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002570 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2571 << " is missing an a=mid line. Filling in the value '"
2572 << new_mid << "' " << source_explanation << ".";
2573 }
2574}
2575
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002577 SetSessionDescriptionObserver* observer,
2578 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002579 SetRemoteDescription(
2580 std::unique_ptr<SessionDescriptionInterface>(desc),
2581 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2582 new SetRemoteDescriptionObserverAdapter(this, observer)));
2583}
2584
2585void PeerConnection::SetRemoteDescription(
2586 std::unique_ptr<SessionDescriptionInterface> desc,
2587 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002588 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002589 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002590
nisse7ce109a2017-01-31 00:57:56 -08002591 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002592 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 return;
2594 }
Steve Anton8a006912017-12-04 15:25:56 -08002595
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002596 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002597 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002598 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002599 return;
2600 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002601
Steve Anton80dd7b52018-02-16 17:08:42 -08002602 // If a session error has occurred the PeerConnection is in a possibly
2603 // inconsistent state so fail right away.
2604 if (session_error() != SessionError::kNone) {
2605 std::string error_message = GetSessionErrorMsg();
2606 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2607 observer->OnSetRemoteDescriptionComplete(
2608 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2609 return;
2610 }
Steve Anton71439a62018-02-15 11:53:06 -08002611
Steve Antonba42e992018-04-09 14:10:01 -07002612 if (desc->GetType() == SdpType::kOffer) {
2613 // Report to UMA the format of the received offer.
2614 ReportSdpFormatReceived(*desc);
2615 }
2616
Steve Anton06817cd2018-12-18 15:55:30 -08002617 // Handle remote descriptions missing a=mid lines for interop with legacy end
2618 // points.
2619 FillInMissingRemoteMids(desc->description());
2620
Steve Anton80dd7b52018-02-16 17:08:42 -08002621 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002622 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002623 std::string error_message = GetSetDescriptionErrorMessage(
2624 cricket::CS_REMOTE, desc->GetType(), error);
2625 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002626 observer->OnSetRemoteDescriptionComplete(
2627 RTCError(error.type(), std::move(error_message)));
2628 return;
2629 }
Steve Anton71439a62018-02-15 11:53:06 -08002630
Steve Anton80dd7b52018-02-16 17:08:42 -08002631 // Grab the description type before moving ownership to
2632 // ApplyRemoteDescription, which may destroy it before returning.
2633 const SdpType type = desc->GetType();
2634
2635 error = ApplyRemoteDescription(std::move(desc));
2636 // |desc| may be destroyed at this point.
2637
2638 if (!error.ok()) {
2639 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2640 // inconsistent state, so act conservatively here and set the session error
2641 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2642 SetSessionError(SessionError::kContent, error.message());
2643 std::string error_message =
2644 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2645 RTC_LOG(LS_ERROR) << error_message;
2646 observer->OnSetRemoteDescriptionComplete(
2647 RTCError(error.type(), std::move(error_message)));
2648 return;
2649 }
2650 RTC_DCHECK(remote_description());
2651
2652 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002653 // TODO(deadbeef): We already had to hop to the network thread for
2654 // MaybeStartGathering...
2655 network_thread()->Invoke<void>(
2656 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2657 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002658 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002659 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002660 }
2661
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002662 if (IsUnifiedPlan()) {
2663 bool was_negotiation_needed = is_negotiation_needed_;
2664 UpdateNegotiationNeeded();
2665 if (signaling_state() == kStable && was_negotiation_needed &&
2666 is_negotiation_needed_) {
2667 Observer()->OnRenegotiationNeeded();
2668 }
2669 }
2670
Steve Anton8a006912017-12-04 15:25:56 -08002671 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07002672 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
Steve Anton8a006912017-12-04 15:25:56 -08002673}
2674
2675RTCError PeerConnection::ApplyRemoteDescription(
2676 std::unique_ptr<SessionDescriptionInterface> desc) {
2677 RTC_DCHECK_RUN_ON(signaling_thread());
2678 RTC_DCHECK(desc);
2679
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002680 // Update stats here so that we have the most recent stats for tracks and
2681 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002682 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002683
Steve Antondcc3c022017-12-22 16:02:54 -08002684 // Take a reference to the old remote description since it's used below to
2685 // compare against the new remote description. When setting the new remote
2686 // description, grab ownership of the replaced session description in case it
2687 // is the same as |old_remote_description|, to keep it alive for the duration
2688 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002689 const SessionDescriptionInterface* old_remote_description =
2690 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002691 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002692 SdpType type = desc->GetType();
2693 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002694 replaced_remote_description = pending_remote_description_
2695 ? std::move(pending_remote_description_)
2696 : std::move(current_remote_description_);
2697 current_remote_description_ = std::move(desc);
2698 pending_remote_description_ = nullptr;
2699 current_local_description_ = std::move(pending_local_description_);
2700 } else {
2701 replaced_remote_description = std::move(pending_remote_description_);
2702 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002703 }
Steve Anton8a006912017-12-04 15:25:56 -08002704 // The session description to apply now must be accessed by
2705 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002706 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002707
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002708 // Report statistics about any use of simulcast.
2709 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2710 *remote_description()->description());
2711
Zhi Huange830e682018-03-30 10:48:35 -07002712 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2713 if (!error.ok()) {
2714 return error;
2715 }
Steve Anton8a006912017-12-04 15:25:56 -08002716 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002717 if (IsUnifiedPlan()) {
2718 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002719 cricket::CS_REMOTE, *remote_description(), local_description(),
2720 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002721 if (!error.ok()) {
2722 return error;
2723 }
Steve Antondcc3c022017-12-22 16:02:54 -08002724 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002725 // Media channels will be created only when offer is set. These may use new
2726 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002727 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002728 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002729 // description is applied. Restore back to old description.
2730 RTCError error = CreateChannels(*remote_description()->description());
2731 if (!error.ok()) {
2732 return error;
2733 }
2734 }
Steve Antondcc3c022017-12-22 16:02:54 -08002735 // Remove unused channels if MediaContentDescription is rejected.
2736 RemoveUnusedChannels(remote_description()->description());
2737 }
Steve Anton8a006912017-12-04 15:25:56 -08002738
Zhi Huange830e682018-03-30 10:48:35 -07002739 // NOTE: Candidates allocation will be initiated only when
2740 // SetLocalDescription is called.
2741 error = UpdateSessionState(type, cricket::CS_REMOTE,
2742 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002743 if (!error.ok()) {
2744 return error;
2745 }
2746
2747 if (local_description() &&
2748 !UseCandidatesInSessionDescription(remote_description())) {
2749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2750 }
2751
2752 if (old_remote_description) {
2753 for (const cricket::ContentInfo& content :
2754 old_remote_description->description()->contents()) {
2755 // Check if this new SessionDescription contains new ICE ufrag and
2756 // password that indicates the remote peer requests an ICE restart.
2757 // TODO(deadbeef): When we start storing both the current and pending
2758 // remote description, this should reset pending_ice_restarts and compare
2759 // against the current description.
2760 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2761 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002762 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002763 pending_ice_restarts_.insert(content.name);
2764 }
2765 } else {
2766 // We retain all received candidates only if ICE is not restarted.
2767 // When ICE is restarted, all previous candidates belong to an old
2768 // generation and should not be kept.
2769 // TODO(deadbeef): This goes against the W3C spec which says the remote
2770 // description should only contain candidates from the last set remote
2771 // description plus any candidates added since then. We should remove
2772 // this once we're sure it won't break anything.
2773 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2774 old_remote_description, content.name, mutable_remote_description());
2775 }
2776 }
2777 }
2778
2779 if (session_error() != SessionError::kNone) {
2780 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2781 }
2782
2783 // Set the the ICE connection state to connecting since the connection may
2784 // become writable with peer reflexive candidates before any remote candidate
2785 // is signaled.
2786 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2787 // is to have a new signal the indicates a change in checking state from the
2788 // transport and expose a new checking() member from transport that can be
2789 // read to determine the current checking state. The existing SignalConnecting
2790 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002791 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002792 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002793 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2794 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2795 }
2796
deadbeefab9b2d12015-10-14 11:33:11 -07002797 // If setting the description decided our SSL role, allocate any necessary
2798 // SCTP sids.
2799 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002800 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002801 AllocateSctpSids(role);
2802 }
2803
Steve Antondcc3c022017-12-22 16:02:54 -08002804 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002805 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002806 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002807 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002808 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002809 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002810 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002811 const ContentInfo* content =
2812 FindMediaSectionForTransceiver(transceiver, remote_description());
2813 if (!content) {
2814 continue;
2815 }
2816 const MediaContentDescription* media_desc = content->media_description();
2817 RtpTransceiverDirection local_direction =
2818 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002819 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2820 // RTCSessionDescription: Set the associated remote streams given
2821 // transceiver.[[Receiver]], msids, addList, and removeList".
2822 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2823 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2824 std::vector<std::string> stream_ids;
2825 if (!media_desc->streams().empty()) {
2826 // The remote description has signaled the stream IDs.
2827 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002828 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002829 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2830 << " (" << GetStreamIdsString(stream_ids) << ").";
2831 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2832 stream_ids, &added_streams,
2833 &removed_streams);
2834 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2835 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2836 // and transceiver's current direction is neither sendrecv nor recvonly,
2837 // process the addition of a remote track for the media description.
2838 if (!transceiver->fired_direction() ||
2839 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2840 RTC_LOG(LS_INFO)
2841 << "Processing the addition of a remote track for MID="
2842 << content->name << ".";
2843 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002844 }
Steve Antondcc3c022017-12-22 16:02:54 -08002845 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002846 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002847 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2848 // removal of a remote track for the media description, given transceiver,
2849 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002850 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002851 (transceiver->fired_direction() &&
2852 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2853 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2854 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002855 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002856 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002857 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002858 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002859 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002860 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002861 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002862 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002863 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002864 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2865 if (transceiver->mid()) {
2866 auto dtls_transport =
2867 LookupDtlsTransportByMidInternal(*transceiver->mid());
2868 transceiver->internal()->sender_internal()->set_transport(
2869 dtls_transport);
2870 transceiver->internal()->receiver_internal()->set_transport(
2871 dtls_transport);
2872 }
Steve Antondcc3c022017-12-22 16:02:54 -08002873 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002874 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002875 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002876 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002877 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2878 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002879 transceiver->Stop();
2880 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002881 if (!content->rejected &&
2882 RtpTransceiverDirectionHasRecv(local_direction)) {
2883 // Set ssrc to 0 in the case of an unsignalled ssrc.
2884 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002885 if (!media_desc->streams().empty() &&
2886 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002887 ssrc = media_desc->streams()[0].first_ssrc();
2888 }
2889 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002890 }
Steve Antondcc3c022017-12-22 16:02:54 -08002891 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002892 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002893 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002894 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002895 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002896 observer->OnTrack(transceiver);
2897 observer->OnAddTrack(transceiver->receiver(),
2898 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002899 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002900 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002901 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002902 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002903 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002904 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002905 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002906 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002907 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002908 }
Steve Antondcc3c022017-12-22 16:02:54 -08002909 }
2910
Henrik Boströmfdb92012017-11-09 19:55:44 +01002911 const cricket::ContentInfo* audio_content =
2912 GetFirstAudioContent(remote_description()->description());
2913 const cricket::ContentInfo* video_content =
2914 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002915 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002916 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002917 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002918 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002919 const cricket::RtpDataContentDescription* rtp_data_desc =
2920 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002921
2922 // Check if the descriptions include streams, just in case the peer supports
2923 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002924 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002925 (audio_desc && !audio_desc->streams().empty()) ||
2926 (video_desc && !video_desc->streams().empty())) {
2927 remote_peer_supports_msid_ = true;
2928 }
deadbeefab9b2d12015-10-14 11:33:11 -07002929
2930 // We wait to signal new streams until we finish processing the description,
2931 // since only at that point will new streams have all their tracks.
2932 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2933
Steve Antondcc3c022017-12-22 16:02:54 -08002934 if (!IsUnifiedPlan()) {
2935 // TODO(steveanton): When removing RTP senders/receivers in response to a
2936 // rejected media section, there is some cleanup logic that expects the
2937 // voice/ video channel to still be set. But in this method the voice/video
2938 // channel would have been destroyed by the SetRemoteDescription caller
2939 // above so the cleanup that relies on them fails to run. The RemoveSenders
2940 // calls should be moved to right before the DestroyChannel calls to fix
2941 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002942
Steve Antondcc3c022017-12-22 16:02:54 -08002943 // Find all audio rtp streams and create corresponding remote AudioTracks
2944 // and MediaStreams.
2945 if (audio_content) {
2946 if (audio_content->rejected) {
2947 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2948 } else {
2949 bool default_audio_track_needed =
2950 !remote_peer_supports_msid_ &&
2951 RtpTransceiverDirectionHasSend(audio_desc->direction());
2952 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2953 default_audio_track_needed, audio_desc->type(),
2954 new_streams);
2955 }
deadbeeffaac4972015-11-12 15:33:07 -08002956 }
deadbeefab9b2d12015-10-14 11:33:11 -07002957
Steve Antondcc3c022017-12-22 16:02:54 -08002958 // Find all video rtp streams and create corresponding remote VideoTracks
2959 // and MediaStreams.
2960 if (video_content) {
2961 if (video_content->rejected) {
2962 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2963 } else {
2964 bool default_video_track_needed =
2965 !remote_peer_supports_msid_ &&
2966 RtpTransceiverDirectionHasSend(video_desc->direction());
2967 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2968 default_video_track_needed, video_desc->type(),
2969 new_streams);
2970 }
deadbeeffaac4972015-11-12 15:33:07 -08002971 }
deadbeefab9b2d12015-10-14 11:33:11 -07002972
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002973 // If this is an RTP data transport, update the DataChannels with the
2974 // information from the remote peer.
2975 if (rtp_data_desc) {
2976 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002977 }
deadbeefab9b2d12015-10-14 11:33:11 -07002978
Steve Antondcc3c022017-12-22 16:02:54 -08002979 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002980 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002981 for (size_t i = 0; i < new_streams->count(); ++i) {
2982 MediaStreamInterface* new_stream = new_streams->at(i);
2983 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002984 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002985 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2986 }
deadbeefab9b2d12015-10-14 11:33:11 -07002987
Steve Antondcc3c022017-12-22 16:02:54 -08002988 UpdateEndedRemoteMediaStreams();
2989 }
deadbeefab9b2d12015-10-14 11:33:11 -07002990
Henrik Boström79b69802019-07-18 11:16:56 +02002991 if (type == SdpType::kAnswer &&
2992 local_ice_credentials_to_replace_->SatisfiesIceRestart(
2993 *current_local_description_)) {
2994 local_ice_credentials_to_replace_->ClearIceCredentials();
2995 }
2996
Steve Anton8a006912017-12-04 15:25:56 -08002997 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002998}
2999
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003000void PeerConnection::SetAssociatedRemoteStreams(
3001 rtc::scoped_refptr<RtpReceiverInternal> receiver,
3002 const std::vector<std::string>& stream_ids,
3003 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
3004 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3005 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
3006 for (const std::string& stream_id : stream_ids) {
3007 rtc::scoped_refptr<MediaStreamInterface> stream =
3008 remote_streams_->find(stream_id);
3009 if (!stream) {
3010 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3011 MediaStream::Create(stream_id));
3012 remote_streams_->AddStream(stream);
3013 added_streams->push_back(stream);
3014 }
3015 media_streams.push_back(stream);
3016 }
3017 // Special case: "a=msid" missing, use random stream ID.
3018 if (media_streams.empty() &&
3019 !(remote_description()->description()->msid_signaling() &
3020 cricket::kMsidSignalingMediaSection)) {
3021 if (!missing_msid_default_stream_) {
3022 missing_msid_default_stream_ = MediaStreamProxy::Create(
3023 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
3024 added_streams->push_back(missing_msid_default_stream_);
3025 }
3026 media_streams.push_back(missing_msid_default_stream_);
3027 }
3028 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
3029 receiver->streams();
3030 // SetStreams() will add/remove the receiver's track to/from the streams. This
3031 // differs from the spec - the spec uses an "addList" and "removeList" to
3032 // update the stream-track relationships in a later step. We do this earlier,
3033 // changing the order of things, but the end-result is the same.
3034 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
3035 // instead. https://crbug.com/webrtc/9480
3036 receiver->SetStreams(media_streams);
3037 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3038}
3039
Steve Anton0f5400a2018-07-17 14:25:36 -07003040void PeerConnection::ProcessRemovalOfRemoteTrack(
3041 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3042 transceiver,
3043 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
3044 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3045 RTC_DCHECK(transceiver->mid());
3046 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
3047 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003048 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07003049 transceiver->internal()->receiver_internal()->streams();
3050 // This will remove the remote track from the streams.
3051 transceiver->internal()->receiver_internal()->set_stream_ids({});
3052 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003053 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
3054}
3055
3056void PeerConnection::RemoveRemoteStreamsIfEmpty(
3057 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
3058 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
3059 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
3060 // streams, see if the stream was removed by checking if this was the last
3061 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01003062 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01003063 if (remote_stream->GetAudioTracks().empty() &&
3064 remote_stream->GetVideoTracks().empty()) {
3065 remote_streams_->RemoveStream(remote_stream);
3066 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07003067 }
3068 }
3069}
3070
Steve Antondcc3c022017-12-22 16:02:54 -08003071RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3072 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003073 const SessionDescriptionInterface& new_session,
3074 const SessionDescriptionInterface* old_local_description,
3075 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003076 RTC_DCHECK(IsUnifiedPlan());
3077
Steve Anton7464fca2018-01-19 11:10:37 -08003078 const cricket::ContentGroup* bundle_group = nullptr;
3079 if (new_session.GetType() == SdpType::kOffer) {
3080 auto bundle_group_or_error =
3081 GetEarlyBundleGroup(*new_session.description());
3082 if (!bundle_group_or_error.ok()) {
3083 return bundle_group_or_error.MoveError();
3084 }
3085 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003086 }
Steve Antondcc3c022017-12-22 16:02:54 -08003087
Steve Antondcc3c022017-12-22 16:02:54 -08003088 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003089 for (size_t i = 0; i < new_contents.size(); ++i) {
3090 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003091 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003092 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003093 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3094 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003095 const cricket::ContentInfo* old_local_content = nullptr;
3096 if (old_local_description &&
3097 i < old_local_description->description()->contents().size()) {
3098 old_local_content =
3099 &old_local_description->description()->contents()[i];
3100 }
3101 const cricket::ContentInfo* old_remote_content = nullptr;
3102 if (old_remote_description &&
3103 i < old_remote_description->description()->contents().size()) {
3104 old_remote_content =
3105 &old_remote_description->description()->contents()[i];
3106 }
Steve Antondcc3c022017-12-22 16:02:54 -08003107 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003108 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3109 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003110 if (!transceiver_or_error.ok()) {
3111 return transceiver_or_error.MoveError();
3112 }
3113 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003114 RTCError error =
3115 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3116 if (!error.ok()) {
3117 return error;
3118 }
3119 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003120 if (GetDataMid() && new_content.name != *GetDataMid()) {
3121 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003122 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3123 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003124 continue;
3125 }
3126 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3127 if (!error.ok()) {
3128 return error;
3129 }
Steve Antondcc3c022017-12-22 16:02:54 -08003130 } else {
3131 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3132 "Unknown section type.");
3133 }
3134 }
3135
3136 return RTCError::OK();
3137}
3138
3139RTCError PeerConnection::UpdateTransceiverChannel(
3140 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3141 transceiver,
3142 const cricket::ContentInfo& content,
3143 const cricket::ContentGroup* bundle_group) {
3144 RTC_DCHECK(IsUnifiedPlan());
3145 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003146 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003147 if (content.rejected) {
3148 if (channel) {
3149 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003150 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003151 }
3152 } else {
3153 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003154 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003155 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003156 } else {
Steve Anton69470252018-02-09 11:43:08 -08003157 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003158 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003159 }
3160 if (!channel) {
3161 LOG_AND_RETURN_ERROR(
3162 RTCErrorType::INTERNAL_ERROR,
3163 "Failed to create channel for mid=" + content.name);
3164 }
3165 transceiver->internal()->SetChannel(channel);
3166 }
3167 }
3168 return RTCError::OK();
3169}
3170
Steve Antonfa2260d2017-12-28 16:38:23 -08003171RTCError PeerConnection::UpdateDataChannel(
3172 cricket::ContentSource source,
3173 const cricket::ContentInfo& content,
3174 const cricket::ContentGroup* bundle_group) {
3175 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003176 // If data channels are disabled, ignore this media section. CreateAnswer
3177 // will take care of rejecting it.
3178 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003179 }
3180 if (content.rejected) {
3181 DestroyDataChannel();
3182 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003183 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003184 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003185 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3186 "Failed to create data channel.");
3187 }
3188 }
3189 if (source == cricket::CS_REMOTE) {
3190 const MediaContentDescription* data_desc = content.media_description();
3191 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3192 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3193 }
3194 }
3195 }
3196 return RTCError::OK();
3197}
3198
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003199// This method will extract any send encodings that were sent by the remote
3200// connection. This is currently only relevant for Simulcast scenario (where
3201// the number of layers may be communicated by the server).
3202static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3203 const MediaContentDescription& desc) {
3204 if (!desc.HasSimulcast()) {
3205 return {};
3206 }
3207 std::vector<RtpEncodingParameters> result;
3208 const SimulcastDescription& simulcast = desc.simulcast_description();
3209
3210 // This is a remote description, the parameters we are after should appear
3211 // as receive streams.
3212 for (const auto& alternatives : simulcast.receive_layers()) {
3213 RTC_DCHECK(!alternatives.empty());
3214 // There is currently no way to specify or choose from alternatives.
3215 // We will always use the first alternative, which is the most preferred.
3216 const SimulcastLayer& layer = alternatives[0];
3217 RtpEncodingParameters parameters;
3218 parameters.rid = layer.rid;
3219 parameters.active = !layer.is_paused;
3220 result.push_back(parameters);
3221 }
3222
3223 return result;
3224}
3225
3226static RTCError UpdateSimulcastLayerStatusInSender(
3227 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003228 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003229 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003230 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003231 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003232
3233 // The simulcast envelope cannot be changed, only the status of the streams.
3234 // So we will iterate over the send encodings rather than the layers.
3235 for (RtpEncodingParameters& encoding : parameters.encodings) {
3236 auto iter = std::find_if(layers.begin(), layers.end(),
3237 [&encoding](const SimulcastLayer& layer) {
3238 return layer.rid == encoding.rid;
3239 });
3240 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003241 if (iter == layers.end()) {
3242 disabled_layers.push_back(encoding.rid);
3243 continue;
3244 }
3245
3246 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003247 }
3248
Amit Hilbuch619b2942019-02-26 15:55:19 -08003249 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003250 if (result.ok()) {
3251 result = sender->DisableEncodingLayers(disabled_layers);
3252 }
3253
3254 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003255}
3256
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003257static bool SimulcastIsRejected(
3258 const ContentInfo* local_content,
3259 const MediaContentDescription& answer_media_desc) {
3260 bool simulcast_offered = local_content &&
3261 local_content->media_description() &&
3262 local_content->media_description()->HasSimulcast();
3263 bool simulcast_answered = answer_media_desc.HasSimulcast();
3264 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3265 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3266 return simulcast_offered && (!simulcast_answered || !rids_supported);
3267}
3268
Amit Hilbuch2297d332019-02-19 12:49:22 -08003269static RTCError DisableSimulcastInSender(
3270 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003271 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003272 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003273 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003274 return RTCError::OK();
3275 }
3276
Amit Hilbuch2297d332019-02-19 12:49:22 -08003277 std::vector<std::string> disabled_layers;
3278 std::transform(
3279 parameters.encodings.begin() + 1, parameters.encodings.end(),
3280 std::back_inserter(disabled_layers),
3281 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3282 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003283}
3284
Steve Antondcc3c022017-12-22 16:02:54 -08003285RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3286PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003287 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003288 size_t mline_index,
3289 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003290 const ContentInfo* old_local_content,
3291 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003292 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003293 // If this is an offer then the m= section might be recycled. If the m=
3294 // section is being recycled (defined as: rejected in the current local or
3295 // remote description and not rejected in new description), dissociate the
3296 // currently associated RtpTransceiver by setting its mid property to null,
3297 // and discard the mapping between the transceiver and its m= section index.
3298 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3299 old_remote_content)) {
3300 // We want to dissociate the transceiver that has the rejected mid.
3301 const std::string& old_mid =
3302 (old_local_content && old_local_content->rejected)
3303 ? old_local_content->name
3304 : old_remote_content->name;
3305 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003306 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003307 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3308 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003309 old_transceiver->internal()->set_mid(absl::nullopt);
3310 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003311 }
3312 }
3313 const MediaContentDescription* media_desc = content.media_description();
3314 auto transceiver = GetAssociatedTransceiver(content.name);
3315 if (source == cricket::CS_LOCAL) {
3316 // Find the RtpTransceiver that corresponds to this m= section, using the
3317 // mapping between transceivers and m= section indices established when
3318 // creating the offer.
3319 if (!transceiver) {
3320 transceiver = GetTransceiverByMLineIndex(mline_index);
3321 }
3322 if (!transceiver) {
3323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3324 "Unknown transceiver");
3325 }
3326 } else {
3327 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3328 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3329 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003330 // When simulcast is requested, a transceiver cannot be associated because
3331 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003332 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003333 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3334 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003335 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3336 }
3337 // If no RtpTransceiver was found in the previous step, create one with a
3338 // recvonly direction.
3339 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003340 RTC_LOG(LS_INFO) << "Adding "
3341 << cricket::MediaTypeToString(media_desc->type())
3342 << " transceiver for MID=" << content.name
3343 << " at i=" << mline_index
3344 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003345 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003346 std::vector<RtpEncodingParameters> send_encodings =
3347 GetSendEncodingsFromRemoteDescription(*media_desc);
3348 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3349 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003350 std::string receiver_id;
3351 if (!media_desc->streams().empty()) {
3352 receiver_id = media_desc->streams()[0].id;
3353 } else {
3354 receiver_id = rtc::CreateRandomUuid();
3355 }
3356 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003357 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003358 transceiver->internal()->set_direction(
3359 RtpTransceiverDirection::kRecvOnly);
3360 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003361
3362 // Check if the offer indicated simulcast but the answer rejected it.
3363 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003364 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003365 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003366 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003367 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003368 if (!error.ok()) {
3369 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3370 return std::move(error);
3371 }
3372 }
Steve Antondcc3c022017-12-22 16:02:54 -08003373 }
3374 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003375 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003376 LOG_AND_RETURN_ERROR(
3377 RTCErrorType::INVALID_PARAMETER,
3378 "Transceiver type does not match media description type.");
3379 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003380 if (media_desc->HasSimulcast()) {
3381 std::vector<SimulcastLayer> layers =
3382 source == cricket::CS_LOCAL
3383 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3384 : media_desc->simulcast_description()
3385 .receive_layers()
3386 .GetAllLayers();
3387 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003388 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003389 if (!error.ok()) {
3390 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3391 return std::move(error);
3392 }
3393 }
Steve Antondcc3c022017-12-22 16:02:54 -08003394 // Associate the found or created RtpTransceiver with the m= section by
3395 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3396 // section, and establish a mapping between the transceiver and the index of
3397 // the m= section.
3398 transceiver->internal()->set_mid(content.name);
3399 transceiver->internal()->set_mline_index(mline_index);
3400 return std::move(transceiver);
3401}
3402
3403rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3404PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3405 RTC_DCHECK(IsUnifiedPlan());
3406 for (auto transceiver : transceivers_) {
3407 if (transceiver->mid() == mid) {
3408 return transceiver;
3409 }
3410 }
3411 return nullptr;
3412}
3413
3414rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3415PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3416 RTC_DCHECK(IsUnifiedPlan());
3417 for (auto transceiver : transceivers_) {
3418 if (transceiver->internal()->mline_index() == mline_index) {
3419 return transceiver;
3420 }
3421 }
3422 return nullptr;
3423}
3424
3425rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3426PeerConnection::FindAvailableTransceiverToReceive(
3427 cricket::MediaType media_type) const {
3428 RTC_DCHECK(IsUnifiedPlan());
3429 // From JSEP section 5.10 (Applying a Remote Description):
3430 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3431 // the same type that were added to the PeerConnection by addTrack and are not
3432 // associated with any m= section and are not stopped, find the first such
3433 // RtpTransceiver.
3434 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003435 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003436 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3437 !transceiver->stopped()) {
3438 return transceiver;
3439 }
3440 }
3441 return nullptr;
3442}
3443
Steve Antoned10bd92017-12-05 10:52:59 -08003444const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3445 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3446 transceiver,
3447 const SessionDescriptionInterface* sdesc) const {
3448 RTC_DCHECK(transceiver);
3449 RTC_DCHECK(sdesc);
3450 if (IsUnifiedPlan()) {
3451 if (!transceiver->internal()->mid()) {
3452 // This transceiver is not associated with a media section yet.
3453 return nullptr;
3454 }
3455 return sdesc->description()->GetContentByName(
3456 *transceiver->internal()->mid());
3457 } else {
3458 // Plan B only allows at most one audio and one video section, so use the
3459 // first media section of that type.
3460 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003461 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003462 }
3463}
3464
deadbeef46c73892016-11-16 19:42:04 -08003465PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003466 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003467 return configuration_;
3468}
3469
deadbeef293e9262017-01-11 12:28:30 -08003470bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3471 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003472 RTC_DCHECK_RUN_ON(signaling_thread());
3473 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003474 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003475 if (IsClosed()) {
3476 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3477 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3478 }
3479
Qingsi Wanga2d60672018-04-11 16:57:45 -07003480 // According to JSEP, after setLocalDescription, changing the candidate pool
3481 // size is not allowed, and changing the set of ICE servers will not result
3482 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003483 if (local_description() && configuration.ice_candidate_pool_size !=
3484 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003485 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3486 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003487 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003488 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003489
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003490 if (local_description() &&
3491 configuration.use_media_transport != configuration_.use_media_transport) {
3492 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3493 "SetLocalDescription.";
3494 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3495 }
3496
3497 if (remote_description() &&
3498 configuration.use_media_transport != configuration_.use_media_transport) {
3499 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3500 "SetRemoteDescription.";
3501 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3502 }
3503
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003504 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003505 configuration.use_media_transport_for_data_channels !=
3506 configuration_.use_media_transport_for_data_channels) {
3507 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3508 "after calling SetLocalDescription.";
3509 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3510 }
3511
3512 if (remote_description() &&
3513 configuration.use_media_transport_for_data_channels !=
3514 configuration_.use_media_transport_for_data_channels) {
3515 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3516 "after calling SetRemoteDescription.";
3517 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3518 }
3519
3520 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003521 configuration.crypto_options != configuration_.crypto_options) {
3522 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3523 "SetLocalDescription.";
3524 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3525 }
3526
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003527 if (local_description() && configuration.use_datagram_transport !=
3528 configuration_.use_datagram_transport) {
3529 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3530 "after calling SetLocalDescription.";
3531 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3532 }
3533
3534 if (remote_description() && configuration.use_datagram_transport !=
3535 configuration_.use_datagram_transport) {
3536 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3537 "after calling SetRemoteDescription.";
3538 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3539 }
3540
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003541 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003542 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003543 (configuration.use_datagram_transport &&
3544 *configuration.use_datagram_transport)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003545 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3546 << "Media transport requires MaxBundle policy.";
3547 }
3548
deadbeef293e9262017-01-11 12:28:30 -08003549 // The simplest (and most future-compatible) way to tell if the config was
3550 // modified in an invalid way is to copy each property we do support
3551 // modifying, then use operator==. There are far more properties we don't
3552 // support modifying than those we do, and more could be added.
3553 RTCConfiguration modified_config = configuration_;
3554 modified_config.servers = configuration.servers;
3555 modified_config.type = configuration.type;
3556 modified_config.ice_candidate_pool_size =
3557 configuration.ice_candidate_pool_size;
3558 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003559 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3560 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003561 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003562 modified_config.ice_check_interval_strong_connectivity =
3563 configuration.ice_check_interval_strong_connectivity;
3564 modified_config.ice_check_interval_weak_connectivity =
3565 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003566 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3567 modified_config.ice_unwritable_min_checks =
3568 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003569 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003570 modified_config.stun_candidate_keepalive_interval =
3571 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003572 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003573 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003574 modified_config.active_reset_srtp_params =
3575 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003576 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003577 modified_config.use_media_transport_for_data_channels =
3578 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003579 modified_config.use_datagram_transport = configuration.use_datagram_transport;
deadbeef293e9262017-01-11 12:28:30 -08003580 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003581 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003582 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3583 }
3584
Steve Anton038834f2017-07-14 15:59:59 -07003585 // Validate the modified configuration.
3586 RTCError validate_error = ValidateConfiguration(modified_config);
3587 if (!validate_error.ok()) {
3588 return SafeSetError(std::move(validate_error), error);
3589 }
3590
deadbeef293e9262017-01-11 12:28:30 -08003591 // Note that this isn't possible through chromium, since it's an unsigned
3592 // short in WebIDL.
3593 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003594 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003595 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3596 }
3597
3598 // Parse ICE servers before hopping to network thread.
3599 cricket::ServerAddresses stun_servers;
3600 std::vector<cricket::RelayServerConfig> turn_servers;
3601 RTCErrorType parse_error =
3602 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3603 if (parse_error != RTCErrorType::NONE) {
3604 return SafeSetError(parse_error, error);
3605 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003606 // Note if STUN or TURN servers were supplied.
3607 if (!stun_servers.empty()) {
3608 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3609 }
3610 if (!turn_servers.empty()) {
3611 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3612 }
deadbeef293e9262017-01-11 12:28:30 -08003613
3614 // In theory this shouldn't fail.
3615 if (!network_thread()->Invoke<bool>(
3616 RTC_FROM_HERE,
3617 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3618 stun_servers, turn_servers, modified_config.type,
3619 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003620 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003621 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003622 modified_config.stun_candidate_keepalive_interval,
3623 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003624 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003625 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3626 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003627
deadbeefd1a38b52016-12-10 13:15:33 -08003628 // As described in JSEP, calling setConfiguration with new ICE servers or
3629 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3630 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003631 if (modified_config.servers != configuration_.servers ||
3632 modified_config.type != configuration_.type ||
3633 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003634 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003635 }
skvladd1f5fda2017-02-03 16:54:05 -08003636
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003637 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003638
3639 use_datagram_transport_ = datagram_transport_config_.enabled &&
3640 modified_config.use_datagram_transport.value_or(
3641 datagram_transport_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003642 transport_controller_->SetMediaTransportSettings(
3643 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003644 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003645 use_datagram_transport_);
skvladd1f5fda2017-02-03 16:54:05 -08003646
Zhi Huangb57e1692018-06-12 11:41:11 -07003647 if (configuration_.active_reset_srtp_params !=
3648 modified_config.active_reset_srtp_params) {
3649 transport_controller_->SetActiveResetSrtpParams(
3650 modified_config.active_reset_srtp_params);
3651 }
3652
deadbeef293e9262017-01-11 12:28:30 -08003653 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003654 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003655 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003656}
3657
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003658bool PeerConnection::AddIceCandidate(
3659 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003660 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003661 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003662 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003663 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003664 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003665 return false;
3666 }
Steve Antond25da372017-11-06 14:50:29 -08003667
3668 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003669 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003670 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003671 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003672 return false;
3673 }
3674
3675 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003676 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003677 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003678 return false;
3679 }
3680
3681 bool valid = false;
3682 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3683 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003684 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003685 return false;
3686 }
3687
3688 // Add this candidate to the remote session description.
3689 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003690 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003691 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003692 return false;
3693 }
3694
3695 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003696 bool result = UseCandidate(ice_candidate);
3697 if (result) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07003698 NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
Harald Alvestrand76829d72018-07-18 23:24:36 +02003699 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3700 } else {
3701 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3702 }
3703 return result;
Steve Antond25da372017-11-06 14:50:29 -08003704 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003705 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003706 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003707 return true;
3708 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003709}
3710
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003711bool PeerConnection::RemoveIceCandidates(
3712 const std::vector<cricket::Candidate>& candidates) {
3713 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003714 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003715 if (IsClosed()) {
3716 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3717 return false;
3718 }
3719
Steve Antond25da372017-11-06 14:50:29 -08003720 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003721 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3722 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003723 return false;
3724 }
3725
3726 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003727 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003728 return false;
3729 }
3730
3731 size_t number_removed =
3732 mutable_remote_description()->RemoveCandidates(candidates);
3733 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003734 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003735 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003736 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003737 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003738 }
3739
3740 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003741 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3742 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003743 RTC_LOG(LS_ERROR)
3744 << "RemoveIceCandidates: Error when removing remote candidates: "
3745 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003746 }
3747 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003748}
3749
Niels Möller0c4f7be2018-05-07 14:01:37 +02003750RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003751 if (!worker_thread()->IsCurrent()) {
3752 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003753 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003754 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003755 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003756
Niels Möller0c4f7be2018-05-07 14:01:37 +02003757 const bool has_min = bitrate.min_bitrate_bps.has_value();
3758 const bool has_start = bitrate.start_bitrate_bps.has_value();
3759 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003760 if (has_min && *bitrate.min_bitrate_bps < 0) {
3761 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3762 "min_bitrate_bps <= 0");
3763 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003764 if (has_start) {
3765 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003766 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003767 "start_bitrate_bps < min_bitrate_bps");
3768 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003769 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3770 "curent_bitrate_bps < 0");
3771 }
3772 }
3773 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003774 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003775 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003776 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003777 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3778 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3779 "max_bitrate_bps < min_bitrate_bps");
3780 } else if (*bitrate.max_bitrate_bps < 0) {
3781 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3782 "max_bitrate_bps < 0");
3783 }
3784 }
3785
zstein4b979802017-06-02 14:37:37 -07003786 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003787 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003788
3789 return RTCError::OK();
3790}
3791
henrika5f6bf242017-11-01 11:06:56 +01003792void PeerConnection::SetAudioPlayout(bool playout) {
3793 if (!worker_thread()->IsCurrent()) {
3794 worker_thread()->Invoke<void>(
3795 RTC_FROM_HERE,
3796 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3797 return;
3798 }
3799 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003800 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003801 audio_state->SetPlayout(playout);
3802}
3803
3804void PeerConnection::SetAudioRecording(bool recording) {
3805 if (!worker_thread()->IsCurrent()) {
3806 worker_thread()->Invoke<void>(
3807 RTC_FROM_HERE,
3808 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3809 return;
3810 }
3811 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003812 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003813 audio_state->SetRecording(recording);
3814}
3815
Steve Anton8c0f7a72017-10-03 10:03:10 -07003816std::unique_ptr<rtc::SSLCertificate>
3817PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003818 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3819 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003820 return nullptr;
3821 }
Steve Antonf25303e2018-10-16 15:23:31 -07003822 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003823}
3824
Zhi Huang70b820f2018-01-27 14:16:15 -08003825std::unique_ptr<rtc::SSLCertChain>
3826PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003827 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003828 auto audio_transceiver = GetFirstAudioTransceiver();
3829 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003830 return nullptr;
3831 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003832 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003833 audio_transceiver->internal()->channel()->transport_name());
3834}
3835
3836rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3837PeerConnection::GetFirstAudioTransceiver() const {
3838 for (auto transceiver : transceivers_) {
3839 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3840 return transceiver;
3841 }
3842 }
3843 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003844}
3845
Bjorn Tereliusde939432017-11-20 17:38:14 +01003846bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3847 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003848 // TODO(eladalon): In C++14, this can be done with a lambda.
3849 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003850 bool operator()() {
3851 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3852 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003853 PeerConnection* const pc;
3854 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003855 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003856 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003857 return worker_thread()->Invoke<bool>(
3858 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003859}
3860
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003861bool PeerConnection::StartRtcEventLog(
3862 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003863 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3864 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3865 output_period_ms = 5000;
3866 }
3867 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003868}
3869
ivoc14d5dbe2016-07-04 07:06:55 -07003870void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003871 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003872 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3873}
3874
Harald Alvestrandad88c882018-11-28 16:47:46 +01003875rtc::scoped_refptr<DtlsTransportInterface>
3876PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003877 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003878 return transport_controller_->LookupDtlsTransportByMid(mid);
3879}
3880
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003881rtc::scoped_refptr<DtlsTransport>
3882PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003883 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003884 return transport_controller_->LookupDtlsTransportByMid(mid);
3885}
3886
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003887rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3888 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003889 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003890 return sctp_transport_;
3891}
3892
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003893const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003894 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003895 return pending_local_description_ ? pending_local_description_.get()
3896 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003897}
3898
3899const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003900 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003901 return pending_remote_description_ ? pending_remote_description_.get()
3902 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003903}
3904
deadbeeffe4a8a42016-12-20 17:56:17 -08003905const SessionDescriptionInterface* PeerConnection::current_local_description()
3906 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003907 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003908 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003909}
3910
3911const SessionDescriptionInterface* PeerConnection::current_remote_description()
3912 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003913 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003914 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003915}
3916
3917const SessionDescriptionInterface* PeerConnection::pending_local_description()
3918 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003919 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003920 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003921}
3922
3923const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3924 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003925 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003926 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003927}
3928
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003929void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003930 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003931 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003932 // Update stats here so that we have the most recent stats for tracks and
3933 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003934 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003935
Steve Anton75737c02017-11-06 10:37:17 -08003936 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003937 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003938
Mirko Bonadei739baf02019-01-27 17:29:42 +01003939 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003940 transceiver->Stop();
3941 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003942
3943 // Ensure that all asynchronous stats requests are completed before destroying
3944 // the transport controller below.
3945 if (stats_collector_) {
3946 stats_collector_->WaitForPendingRequest();
3947 }
3948
3949 // Don't destroy BaseChannels until after stats has been cleaned up so that
3950 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003951 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003952
Qingsi Wang93a84392018-01-30 17:13:09 -08003953 // The event log is used in the transport controller, which must be outlived
3954 // by the former. CreateOffer by the peer connection is implemented
3955 // asynchronously and if the peer connection is closed without resetting the
3956 // WebRTC session description factory, the session description factory would
3957 // call the transport controller.
3958 webrtc_session_desc_factory_.reset();
3959 transport_controller_.reset();
3960
deadbeef42a42632017-03-10 15:18:00 -08003961 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003962 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3963 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003964
Steve Anton978b8762017-09-29 12:15:02 -07003965 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003966 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003967 call_.reset();
3968 // The event log must outlive call (and any other object that uses it).
3969 event_log_.reset();
3970 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003971 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003972 // The .h file says that observer can be discarded after close() returns.
3973 // Make sure this is true.
3974 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003975}
3976
Steve Antonad182762018-09-05 20:22:40 +00003977void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003978 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003979 switch (msg->message_id) {
3980 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3981 SetSessionDescriptionMsg* param =
3982 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3983 param->observer->OnSuccess();
3984 delete param;
3985 break;
3986 }
3987 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3988 SetSessionDescriptionMsg* param =
3989 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3990 param->observer->OnFailure(std::move(param->error));
3991 delete param;
3992 break;
3993 }
3994 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3995 CreateSessionDescriptionMsg* param =
3996 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3997 param->observer->OnFailure(std::move(param->error));
3998 delete param;
3999 break;
4000 }
4001 case MSG_GETSTATS: {
4002 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
4003 StatsReports reports;
4004 stats_->GetStats(param->track, &reports);
4005 param->observer->OnComplete(reports);
4006 delete param;
4007 break;
4008 }
4009 case MSG_FREE_DATACHANNELS: {
4010 sctp_data_channels_to_free_.clear();
4011 break;
4012 }
4013 case MSG_REPORT_USAGE_PATTERN: {
4014 ReportUsagePattern();
4015 break;
4016 }
4017 default:
4018 RTC_NOTREACHED() << "Not implemented";
4019 break;
4020 }
4021}
4022
Steve Antonafb0bb72018-02-20 11:35:37 -08004023cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
4024 RTC_DCHECK(!IsUnifiedPlan());
4025 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
4026 GetAudioTransceiver()->internal()->channel());
4027 if (voice_channel) {
4028 return voice_channel->media_channel();
4029 } else {
4030 return nullptr;
4031 }
4032}
4033
4034cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
4035 RTC_DCHECK(!IsUnifiedPlan());
4036 auto* video_channel = static_cast<cricket::VideoChannel*>(
4037 GetVideoTransceiver()->internal()->channel());
4038 if (video_channel) {
4039 return video_channel->media_channel();
4040 } else {
4041 return nullptr;
4042 }
4043}
4044
Steve Anton4171afb2017-11-20 10:20:22 -08004045void PeerConnection::CreateAudioReceiver(
4046 MediaStreamInterface* stream,
4047 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004048 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4049 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004050 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4051 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004052 auto* audio_receiver = new AudioRtpReceiver(
4053 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004054 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004055 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4056 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4057 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004058 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004059 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004060 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004061}
4062
Steve Anton4171afb2017-11-20 10:20:22 -08004063void PeerConnection::CreateVideoReceiver(
4064 MediaStreamInterface* stream,
4065 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004066 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4067 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004068 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4069 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004070 auto* video_receiver = new VideoRtpReceiver(
4071 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004072 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004073 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4074 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4075 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004076 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004077 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004078 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004079}
4080
deadbeef70ab1a12015-09-28 16:53:55 -07004081// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4082// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004083rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004084 const RtpSenderInfo& remote_sender_info) {
4085 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4086 if (!receiver) {
4087 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4088 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004089 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004090 }
Steve Anton4171afb2017-11-20 10:20:22 -08004091 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4092 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4093 } else {
4094 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4095 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004096 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004097}
4098
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004099void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4100 MediaStreamInterface* stream) {
4101 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004102 RTC_DCHECK(track);
4103 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004104 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004105 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004106 // We already have a sender for this track, so just change the stream_id
4107 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004108 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004109 return;
4110 }
4111
4112 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004113 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004114 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004115 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004116 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004117 // If the sender has already been configured in SDP, we call SetSsrc,
4118 // which will connect the sender to the underlying transport. This can
4119 // occur if a local session description that contains the ID of the sender
4120 // is set before AddStream is called. It can also occur if the local
4121 // session description is not changed and RemoveStream is called, and
4122 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004123 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004124 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004125 if (sender_info) {
4126 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004127 }
4128}
4129
4130// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4131// indefinitely, when we have unified plan SDP.
4132void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4133 MediaStreamInterface* stream) {
4134 RTC_DCHECK(!IsClosed());
4135 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004136 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004137 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4138 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004139 return;
4140 }
Steve Anton4171afb2017-11-20 10:20:22 -08004141 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004142}
4143
4144void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4145 MediaStreamInterface* stream) {
4146 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004147 RTC_DCHECK(track);
4148 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004149 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004150 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004151 // We already have a sender for this track, so just change the stream_id
4152 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004153 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004154 return;
4155 }
4156
4157 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004158 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004159 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004160 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004161 GetVideoTransceiver()->internal()->AddSender(new_sender);
4162 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004163 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004164 if (sender_info) {
4165 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004166 }
4167}
4168
4169void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4170 MediaStreamInterface* stream) {
4171 RTC_DCHECK(!IsClosed());
4172 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004173 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004174 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4175 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004176 return;
4177 }
Steve Anton4171afb2017-11-20 10:20:22 -08004178 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004179}
4180
Steve Antonba818672017-11-06 10:21:57 -08004181void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004182 if (ice_connection_state_ == new_state) {
4183 return;
4184 }
4185
deadbeefcbecd352015-09-23 11:50:27 -07004186 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004187 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004188 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004189 return;
4190 }
Steve Antonba818672017-11-06 10:21:57 -08004191
Mirko Bonadei675513b2017-11-09 11:09:25 +01004192 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4193 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004194 RTC_DCHECK(ice_connection_state_ !=
4195 PeerConnectionInterface::kIceConnectionClosed);
4196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004197 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004198 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004199}
4200
Alex Loiko9289eda2018-11-23 16:18:59 +00004201void PeerConnection::SetStandardizedIceConnectionState(
4202 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004203 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004204 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004205 }
4206
4207 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004208 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004209 }
4210
4211 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4212 << standardized_ice_connection_state_ << " => " << new_state;
4213
Alex Loiko9289eda2018-11-23 16:18:59 +00004214 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004215 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004216}
4217
Jonas Olsson635474e2018-10-18 15:58:17 +02004218void PeerConnection::SetConnectionState(
4219 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004220 if (connection_state_ == new_state)
4221 return;
4222 if (IsClosed())
4223 return;
4224 connection_state_ = new_state;
4225 Observer()->OnConnectionChange(new_state);
4226}
4227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004228void PeerConnection::OnIceGatheringChange(
4229 PeerConnectionInterface::IceGatheringState new_state) {
4230 if (IsClosed()) {
4231 return;
4232 }
4233 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004234 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004235}
4236
jbauch81bf7b02017-03-25 08:31:12 -07004237void PeerConnection::OnIceCandidate(
4238 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004239 if (IsClosed()) {
4240 return;
4241 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004242 ReportIceCandidateCollected(candidate->candidate());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004243 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004244}
4245
Eldar Relloda13ea22019-06-01 12:23:43 +03004246void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4247 const std::string& url,
4248 int error_code,
4249 const std::string& error_text) {
4250 if (IsClosed()) {
4251 return;
4252 }
4253 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4254}
4255
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004256void PeerConnection::OnIceCandidatesRemoved(
4257 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004258 if (IsClosed()) {
4259 return;
4260 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004261 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004262}
4263
Alex Drake00c7ecf2019-08-06 10:54:47 -07004264void PeerConnection::OnSelectedCandidatePairChanged(
4265 const cricket::CandidatePairChangeEvent& event) {
4266 if (IsClosed()) {
4267 return;
4268 }
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07004269
Alex Drake00c7ecf2019-08-06 10:54:47 -07004270 Observer()->OnIceSelectedCandidatePairChanged(event);
4271}
4272
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004273void PeerConnection::ChangeSignalingState(
4274 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004275 if (signaling_state_ == signaling_state) {
4276 return;
4277 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004278 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4279 << GetSignalingStateString(signaling_state_)
4280 << " New state: "
4281 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004282 signaling_state_ = signaling_state;
4283 if (signaling_state == kClosed) {
4284 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004285 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004286 standardized_ice_connection_state_ =
4287 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004288 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4289 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004290 if (ice_gathering_state_ != kIceGatheringComplete) {
4291 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004292 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004293 }
4294 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004295 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004296}
4297
deadbeefeb459812015-12-15 19:24:43 -08004298void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4299 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004300 if (IsClosed()) {
4301 return;
4302 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004303 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004304 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004305}
4306
deadbeefeb459812015-12-15 19:24:43 -08004307void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4308 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004309 if (IsClosed()) {
4310 return;
4311 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004312 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004313 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004314}
4315
4316void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4317 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004318 if (IsClosed()) {
4319 return;
4320 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004321 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004322 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004323}
4324
4325void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4326 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004327 if (IsClosed()) {
4328 return;
4329 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004330 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004331 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004332}
4333
Henrik Boström31638672017-11-23 17:48:32 +01004334void PeerConnection::PostSetSessionDescriptionSuccess(
4335 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004336 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4337 signaling_thread()->Post(RTC_FROM_HERE, this,
4338 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004339}
4340
deadbeefab9b2d12015-10-14 11:33:11 -07004341void PeerConnection::PostSetSessionDescriptionFailure(
4342 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004343 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004344 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004345 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4346 msg->error = std::move(error);
4347 signaling_thread()->Post(RTC_FROM_HERE, this,
4348 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004349}
4350
4351void PeerConnection::PostCreateSessionDescriptionFailure(
4352 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004353 RTCError error) {
4354 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004355 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4356 msg->error = std::move(error);
4357 signaling_thread()->Post(RTC_FROM_HERE, this,
4358 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004359}
4360
zhihuang1c378ed2017-08-17 14:10:50 -07004361void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004362 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004363 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004364 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004365
Steve Antondcc3c022017-12-22 16:02:54 -08004366 if (IsUnifiedPlan()) {
4367 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4368 } else {
4369 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4370 }
4371
Steve Antonfa2260d2017-12-28 16:38:23 -08004372 // Intentionally unset the data channel type for RTP data channel with the
4373 // second condition. Otherwise the RTP data channels would be successfully
4374 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4375 // when building with chromium. We want to leave RTP data channels broken, so
4376 // people won't try to use them.
4377 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4378 session_options->data_channel_type = data_channel_type();
4379 }
4380
Steve Antondcc3c022017-12-22 16:02:54 -08004381 // Apply ICE restart flag and renomination flag.
Henrik Boström79b69802019-07-18 11:16:56 +02004382 bool ice_restart = offer_answer_options.ice_restart ||
4383 local_ice_credentials_to_replace_->HasIceCredentials();
Steve Antondcc3c022017-12-22 16:02:54 -08004384 for (auto& options : session_options->media_description_options) {
Henrik Boström79b69802019-07-18 11:16:56 +02004385 options.transport_options.ice_restart = ice_restart;
Steve Antondcc3c022017-12-22 16:02:54 -08004386 options.transport_options.enable_ice_renomination =
4387 configuration_.enable_ice_renomination;
4388 }
4389
4390 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004391 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004392 session_options->pooled_ice_credentials =
4393 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4394 RTC_FROM_HERE,
4395 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4396 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004397 session_options->offer_extmap_allow_mixed =
4398 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004399
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004400 if (configuration_.use_media_transport ||
4401 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004402 session_options->media_transport_settings =
4403 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4404 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004405
4406 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004407 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004408 for (auto& options : session_options->media_description_options) {
4409 options.transport_options.opaque_parameters =
4410 transport_controller_->GetTransportParameters(options.mid);
4411 }
4412 }
4413
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004414 // Allow fallback for using obsolete SCTP syntax.
4415 // Note that the default in |session_options| is true, while
4416 // the default in |options| is false.
4417 session_options->use_obsolete_sctp_sdp =
4418 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004419}
4420
4421void PeerConnection::GetOptionsForPlanBOffer(
4422 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4423 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004424 // Figure out transceiver directional preferences.
4425 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4426 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4427
4428 // By default, generate sendrecv/recvonly m= sections.
4429 bool recv_audio = true;
4430 bool recv_video = true;
4431
4432 // By default, only offer a new m= section if we have media to send with it.
4433 bool offer_new_audio_description = send_audio;
4434 bool offer_new_video_description = send_video;
4435 bool offer_new_data_description = HasDataChannels();
4436
4437 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004438 if (offer_answer_options.offer_to_receive_audio !=
4439 RTCOfferAnswerOptions::kUndefined) {
4440 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004441 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004442 offer_new_audio_description ||
4443 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004444 }
Steve Antondcc3c022017-12-22 16:02:54 -08004445 if (offer_answer_options.offer_to_receive_video !=
4446 RTCOfferAnswerOptions::kUndefined) {
4447 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004448 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004449 offer_new_video_description ||
4450 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004451 }
4452
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004453 absl::optional<size_t> audio_index;
4454 absl::optional<size_t> video_index;
4455 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004456 // If a current description exists, generate m= sections in the same order,
4457 // using the first audio/video/data section that appears and rejecting
4458 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004459 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004460 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004461 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004462 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4463 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4464 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004465 }
4466
zhihuang1c378ed2017-08-17 14:10:50 -07004467 // Add audio/video/data m= sections to the end if needed.
4468 if (!audio_index && offer_new_audio_description) {
4469 session_options->media_description_options.push_back(
4470 cricket::MediaDescriptionOptions(
4471 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004472 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4473 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004474 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004475 }
zhihuang1c378ed2017-08-17 14:10:50 -07004476 if (!video_index && offer_new_video_description) {
4477 session_options->media_description_options.push_back(
4478 cricket::MediaDescriptionOptions(
4479 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004480 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4481 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004482 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004483 }
zhihuang1c378ed2017-08-17 14:10:50 -07004484 if (!data_index && offer_new_data_description) {
4485 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004486 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004487 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004488 }
4489
4490 cricket::MediaDescriptionOptions* audio_media_description_options =
4491 !audio_index ? nullptr
4492 : &session_options->media_description_options[*audio_index];
4493 cricket::MediaDescriptionOptions* video_media_description_options =
4494 !video_index ? nullptr
4495 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004496
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004497 AddPlanBRtpSenderOptions(GetSendersInternal(),
4498 audio_media_description_options,
4499 video_media_description_options,
4500 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004501}
4502
Steve Antondcc3c022017-12-22 16:02:54 -08004503static cricket::MediaDescriptionOptions
4504GetMediaDescriptionOptionsForTransceiver(
4505 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4506 transceiver,
4507 const std::string& mid) {
4508 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004509 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004510 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004511 media_description_options.codec_preferences =
4512 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004513 // This behavior is specified in JSEP. The gist is that:
4514 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4515 // sendrecv.
4516 // 2. If the MSID is included, then it must be included in any subsequent
4517 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004518 if (transceiver->stopped() ||
4519 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4520 !transceiver->internal()->has_ever_been_used_to_send())) {
4521 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004522 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004523
4524 cricket::SenderOptions sender_options;
4525 sender_options.track_id = transceiver->sender()->id();
4526 sender_options.stream_ids = transceiver->sender()->stream_ids();
4527
4528 // The following sets up RIDs and Simulcast.
4529 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004530 RtpParameters send_parameters =
4531 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004532 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4533 send_parameters.encodings.end(),
4534 [](const RtpEncodingParameters& encoding) {
4535 return !encoding.rid.empty();
4536 });
4537
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004538 std::vector<RidDescription> send_rids;
4539 SimulcastLayerList send_layers;
4540 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4541 if (encoding.rid.empty()) {
4542 continue;
4543 }
4544 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4545 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4546 }
4547
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004548 if (has_rids) {
4549 sender_options.rids = send_rids;
4550 }
4551
4552 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004553 // When RIDs are configured, we must set num_sim_layers to 0 to.
4554 // Otherwise, num_sim_layers must be 1 because either there is no
4555 // simulcast, or simulcast is acheived by munging the SDP.
4556 sender_options.num_sim_layers = has_rids ? 0 : 1;
4557 media_description_options.sender_options.push_back(sender_options);
4558
Steve Antondcc3c022017-12-22 16:02:54 -08004559 return media_description_options;
4560}
4561
Steve Anton5c72e712018-12-10 14:25:30 -08004562// Returns the ContentInfo at mline index |i|, or null if none exists.
4563static const ContentInfo* GetContentByIndex(
4564 const SessionDescriptionInterface* sdesc,
4565 size_t i) {
4566 if (!sdesc) {
4567 return nullptr;
4568 }
4569 const ContentInfos& contents = sdesc->description()->contents();
4570 return (i < contents.size() ? &contents[i] : nullptr);
4571}
4572
Steve Antondcc3c022017-12-22 16:02:54 -08004573void PeerConnection::GetOptionsForUnifiedPlanOffer(
4574 const RTCOfferAnswerOptions& offer_answer_options,
4575 cricket::MediaSessionOptions* session_options) {
4576 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4577 // Offers) and 5.2.2 (Subsequent Offers).
4578 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004579 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004580 const ContentInfos& local_contents =
4581 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004582 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004583 const ContentInfos& remote_contents =
4584 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004585 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004586 // The mline indices that can be recycled. New transceivers should reuse these
4587 // slots first.
4588 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004589 // First, go through each media section that exists in either the local or
4590 // remote description and generate a media section in this offer for the
4591 // associated transceiver. If a media section can be recycled, generate a
4592 // default, rejected media section here that can be later overwritten.
4593 for (size_t i = 0;
4594 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4595 // Either |local_content| or |remote_content| is non-null.
4596 const ContentInfo* local_content =
4597 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004598 const ContentInfo* current_local_content =
4599 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004600 const ContentInfo* remote_content =
4601 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004602 const ContentInfo* current_remote_content =
4603 GetContentByIndex(current_remote_description(), i);
4604 bool had_been_rejected =
4605 (current_local_content && current_local_content->rejected) ||
4606 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004607 const std::string& mid =
4608 (local_content ? local_content->name : remote_content->name);
4609 cricket::MediaType media_type =
4610 (local_content ? local_content->media_description()->type()
4611 : remote_content->media_description()->type());
4612 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4613 media_type == cricket::MEDIA_TYPE_VIDEO) {
4614 auto transceiver = GetAssociatedTransceiver(mid);
4615 RTC_CHECK(transceiver);
4616 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004617 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004618 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004619 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004620 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4621 RtpTransceiverDirection::kInactive,
4622 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004623 recycleable_mline_indices.push(i);
4624 } else {
4625 session_options->media_description_options.push_back(
4626 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4627 // CreateOffer shouldn't really cause any state changes in
4628 // PeerConnection, but we need a way to match new transceivers to new
4629 // media sections in SetLocalDescription and JSEP specifies this is done
4630 // by recording the index of the media section generated for the
4631 // transceiver in the offer.
4632 transceiver->internal()->set_mline_index(i);
4633 }
4634 } else {
4635 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004636 RTC_CHECK(GetDataMid());
4637 if (had_been_rejected || mid != *GetDataMid()) {
4638 session_options->media_description_options.push_back(
4639 GetMediaDescriptionOptionsForRejectedData(mid));
4640 } else {
4641 session_options->media_description_options.push_back(
4642 GetMediaDescriptionOptionsForActiveData(mid));
4643 }
Steve Antondcc3c022017-12-22 16:02:54 -08004644 }
4645 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004646
Steve Antondcc3c022017-12-22 16:02:54 -08004647 // Next, look for transceivers that are newly added (that is, are not stopped
4648 // and not associated). Reuse media sections marked as recyclable first,
4649 // otherwise append to the end of the offer. New media sections should be
4650 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004651 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004652 if (transceiver->mid() || transceiver->stopped()) {
4653 continue;
4654 }
4655 size_t mline_index;
4656 if (!recycleable_mline_indices.empty()) {
4657 mline_index = recycleable_mline_indices.front();
4658 recycleable_mline_indices.pop();
4659 session_options->media_description_options[mline_index] =
4660 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004661 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004662 } else {
4663 mline_index = session_options->media_description_options.size();
4664 session_options->media_description_options.push_back(
4665 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004666 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004667 }
4668 // See comment above for why CreateOffer changes the transceiver's state.
4669 transceiver->internal()->set_mline_index(mline_index);
4670 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004671 // Lastly, add a m-section if we have local data channels and an m section
4672 // does not already exist.
4673 if (!GetDataMid() && HasDataChannels()) {
4674 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004675 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004676 }
Steve Antondcc3c022017-12-22 16:02:54 -08004677}
4678
4679void PeerConnection::GetOptionsForAnswer(
4680 const RTCOfferAnswerOptions& offer_answer_options,
4681 cricket::MediaSessionOptions* session_options) {
4682 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4683
4684 if (IsUnifiedPlan()) {
4685 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4686 } else {
4687 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4688 }
4689
Steve Antonfa2260d2017-12-28 16:38:23 -08004690 // Intentionally unset the data channel type for RTP data channel. Otherwise
4691 // the RTP data channels would be successfully negotiated by default and the
4692 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4693 // We want to leave RTP data channels broken, so people won't try to use them.
4694 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4695 session_options->data_channel_type = data_channel_type();
4696 }
4697
Steve Antondcc3c022017-12-22 16:02:54 -08004698 // Apply ICE renomination flag.
4699 for (auto& options : session_options->media_description_options) {
4700 options.transport_options.enable_ice_renomination =
4701 configuration_.enable_ice_renomination;
4702 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004703
4704 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004705 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004706 session_options->pooled_ice_credentials =
4707 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4708 RTC_FROM_HERE,
4709 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4710 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004711
4712 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004713 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004714 for (auto& options : session_options->media_description_options) {
4715 options.transport_options.opaque_parameters =
4716 transport_controller_->GetTransportParameters(options.mid);
4717 }
4718 }
deadbeefab9b2d12015-10-14 11:33:11 -07004719}
4720
Steve Antondcc3c022017-12-22 16:02:54 -08004721void PeerConnection::GetOptionsForPlanBAnswer(
4722 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004723 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004724 // Figure out transceiver directional preferences.
4725 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4726 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4727
4728 // By default, generate sendrecv/recvonly m= sections. The direction is also
4729 // restricted by the direction in the offer.
4730 bool recv_audio = true;
4731 bool recv_video = true;
4732
4733 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004734 if (offer_answer_options.offer_to_receive_audio !=
4735 RTCOfferAnswerOptions::kUndefined) {
4736 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004737 }
Steve Antondcc3c022017-12-22 16:02:54 -08004738 if (offer_answer_options.offer_to_receive_video !=
4739 RTCOfferAnswerOptions::kUndefined) {
4740 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004741 }
4742
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004743 absl::optional<size_t> audio_index;
4744 absl::optional<size_t> video_index;
4745 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004746
4747 // Generate m= sections that match those in the offer.
4748 // Note that mediasession.cc will handle intersection our preferred
4749 // direction with the offered direction.
4750 GenerateMediaDescriptionOptions(
4751 remote_description(),
4752 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4753 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4754 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004755
4756 cricket::MediaDescriptionOptions* audio_media_description_options =
4757 !audio_index ? nullptr
4758 : &session_options->media_description_options[*audio_index];
4759 cricket::MediaDescriptionOptions* video_media_description_options =
4760 !video_index ? nullptr
4761 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004762
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004763 AddPlanBRtpSenderOptions(GetSendersInternal(),
4764 audio_media_description_options,
4765 video_media_description_options,
4766 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004767}
zhihuangaf388472016-11-02 16:49:48 -07004768
Steve Antondcc3c022017-12-22 16:02:54 -08004769void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4770 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4771 cricket::MediaSessionOptions* session_options) {
4772 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4773 // Answers) and 5.3.2 (Subsequent Answers).
4774 RTC_DCHECK(remote_description());
4775 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4776 for (const ContentInfo& content :
4777 remote_description()->description()->contents()) {
4778 cricket::MediaType media_type = content.media_description()->type();
4779 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4780 media_type == cricket::MEDIA_TYPE_VIDEO) {
4781 auto transceiver = GetAssociatedTransceiver(content.name);
4782 RTC_CHECK(transceiver);
4783 session_options->media_description_options.push_back(
4784 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4785 } else {
4786 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004787 // Reject all data sections if data channels are disabled.
4788 // Reject a data section if it has already been rejected.
4789 // Reject all data sections except for the first one.
4790 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4791 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004792 session_options->media_description_options.push_back(
4793 GetMediaDescriptionOptionsForRejectedData(content.name));
4794 } else {
4795 session_options->media_description_options.push_back(
4796 GetMediaDescriptionOptionsForActiveData(content.name));
4797 }
Steve Antondcc3c022017-12-22 16:02:54 -08004798 }
4799 }
htaa2a49d92016-03-04 02:51:39 -08004800}
4801
zhihuang1c378ed2017-08-17 14:10:50 -07004802void PeerConnection::GenerateMediaDescriptionOptions(
4803 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004804 RtpTransceiverDirection audio_direction,
4805 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004806 absl::optional<size_t>* audio_index,
4807 absl::optional<size_t>* video_index,
4808 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004809 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004810 for (const cricket::ContentInfo& content :
4811 session_desc->description()->contents()) {
4812 if (IsAudioContent(&content)) {
4813 // If we already have an audio m= section, reject this extra one.
4814 if (*audio_index) {
4815 session_options->media_description_options.push_back(
4816 cricket::MediaDescriptionOptions(
4817 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004818 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004819 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004820 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004821 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004822 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4823 content.name, audio_direction,
4824 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004825 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004826 }
4827 } else if (IsVideoContent(&content)) {
4828 // If we already have an video m= section, reject this extra one.
4829 if (*video_index) {
4830 session_options->media_description_options.push_back(
4831 cricket::MediaDescriptionOptions(
4832 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004833 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004834 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004835 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004836 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004837 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4838 content.name, video_direction,
4839 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004840 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004841 }
4842 } else {
4843 RTC_DCHECK(IsDataContent(&content));
4844 // If we already have an data m= section, reject this extra one.
4845 if (*data_index) {
4846 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004847 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004848 } else {
4849 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004850 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004851 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004852 }
4853 }
htaa2a49d92016-03-04 02:51:39 -08004854 }
deadbeefab9b2d12015-10-14 11:33:11 -07004855}
4856
Steve Antonfa2260d2017-12-28 16:38:23 -08004857cricket::MediaDescriptionOptions
4858PeerConnection::GetMediaDescriptionOptionsForActiveData(
4859 const std::string& mid) const {
4860 // Direction for data sections is meaningless, but legacy endpoints might
4861 // expect sendrecv.
4862 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4863 RtpTransceiverDirection::kSendRecv,
4864 /*stopped=*/false);
4865 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4866 return options;
4867}
4868
4869cricket::MediaDescriptionOptions
4870PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4871 const std::string& mid) const {
4872 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4873 RtpTransceiverDirection::kInactive,
4874 /*stopped=*/true);
4875 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4876 return options;
4877}
4878
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004879absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004880 switch (data_channel_type_) {
4881 case cricket::DCT_RTP:
4882 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004883 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004884 }
4885 return rtp_data_channel_->content_name();
4886 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004887 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004888 case cricket::DCT_MEDIA_TRANSPORT:
4889 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004890 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004891 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004892 }
4893}
4894
Steve Anton4171afb2017-11-20 10:20:22 -08004895void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4896 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4897 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004898 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004899}
4900
Steve Anton4171afb2017-11-20 10:20:22 -08004901void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004902 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004903 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004904 cricket::MediaType media_type,
4905 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004906 RTC_DCHECK(!IsUnifiedPlan());
4907
Steve Anton4171afb2017-11-20 10:20:22 -08004908 std::vector<RtpSenderInfo>* current_senders =
4909 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004910
Steve Anton4171afb2017-11-20 10:20:22 -08004911 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004912 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004913 for (auto sender_it = current_senders->begin();
4914 sender_it != current_senders->end();
4915 /* incremented manually */) {
4916 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004917 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004918 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004919 std::string params_stream_id;
4920 if (params) {
4921 params_stream_id =
4922 (!params->first_stream_id().empty() ? params->first_stream_id()
4923 : kDefaultStreamId);
4924 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004925 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004926 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004927 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004928 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004929 sender_exists) {
4930 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004931 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004932 OnRemoteSenderRemoved(info, media_type);
4933 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004934 }
4935 }
4936
Steve Anton4171afb2017-11-20 10:20:22 -08004937 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004938 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004939 if (!params.has_ssrcs()) {
4940 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4941 // sender, this means it is coming from a Unified Plan endpoint,so we just
4942 // create a default.
4943 default_sender_needed = true;
4944 break;
4945 }
4946
Seth Hampson845e8782018-03-02 11:34:10 -08004947 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004948 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004949 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4950 // not supported in Plan B, we just take the first here and create the
4951 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004952 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004953 (!params.first_stream_id().empty() ? params.first_stream_id()
4954 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004955 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004956 uint32_t ssrc = params.first_ssrc();
4957
4958 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004959 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004960 if (!stream) {
4961 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004962 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004963 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004964 remote_streams_->AddStream(stream);
4965 new_streams->AddStream(stream);
4966 }
4967
Steve Anton4171afb2017-11-20 10:20:22 -08004968 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004969 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004970 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004971 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004972 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004973 }
4974 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004975
Steve Anton4171afb2017-11-20 10:20:22 -08004976 // Add default sender if necessary.
4977 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004978 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004979 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004980 if (!default_stream) {
4981 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004982 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004983 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004984 remote_streams_->AddStream(default_stream);
4985 new_streams->AddStream(default_stream);
4986 }
Steve Anton4171afb2017-11-20 10:20:22 -08004987 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4988 ? kDefaultAudioSenderId
4989 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004990 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004991 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004992 if (!default_sender_info) {
4993 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004994 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004995 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004996 }
4997 }
deadbeefab9b2d12015-10-14 11:33:11 -07004998}
4999
Steve Anton4171afb2017-11-20 10:20:22 -08005000void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
5001 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07005002 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
5003 << " receiver for track_id=" << sender_info.sender_id
5004 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07005005
Steve Anton3d954a62018-04-02 11:27:23 -07005006 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005007 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005008 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005009 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005010 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005011 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08005012 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005013 }
5014}
5015
Steve Anton4171afb2017-11-20 10:20:22 -08005016void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
5017 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07005018 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
5019 << " receiver for track_id=" << sender_info.sender_id
5020 << " and stream_id=" << sender_info.stream_id;
5021
Seth Hampson845e8782018-03-02 11:34:10 -08005022 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005023
Henrik Boström933d8b02017-10-10 10:05:16 -07005024 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07005025 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07005026 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
5027 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005028 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005029 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005030 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005031 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07005032 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005033 }
5034 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07005035 // Stopping or destroying a VideoRtpReceiver will end the
5036 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08005037 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07005038 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08005039 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07005040 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07005041 // There's no guarantee the track is still available, e.g. the track may
5042 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07005043 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07005044 }
5045 } else {
nisseede5da42017-01-12 05:15:36 -08005046 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005047 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005048 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005049 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005050 }
deadbeefab9b2d12015-10-14 11:33:11 -07005051}
5052
5053void PeerConnection::UpdateEndedRemoteMediaStreams() {
5054 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5055 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5056 MediaStreamInterface* stream = remote_streams_->at(i);
5057 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5058 streams_to_remove.push_back(stream);
5059 }
5060 }
5061
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005062 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005063 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005064 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005065 }
5066}
5067
Steve Anton4171afb2017-11-20 10:20:22 -08005068void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005069 const std::vector<cricket::StreamParams>& streams,
5070 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005071 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005072
Seth Hampson845e8782018-03-02 11:34:10 -08005073 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005074 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005075 for (auto sender_it = current_senders->begin();
5076 sender_it != current_senders->end();
5077 /* incremented manually */) {
5078 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005079 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005080 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5081 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005082 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005083 OnLocalSenderRemoved(info, media_type);
5084 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005085 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005086 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005087 }
5088 }
5089
Steve Anton4171afb2017-11-20 10:20:22 -08005090 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005091 for (const cricket::StreamParams& params : streams) {
5092 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005093 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005094 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005095 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005096 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005097 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005098 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005099 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005100 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005101 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005102 }
5103 }
5104}
5105
Steve Anton4171afb2017-11-20 10:20:22 -08005106void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5107 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005108 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005109 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005110 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005111 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5112 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005113 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005114 return;
5115 }
5116
deadbeeffac06552015-11-25 11:26:01 -08005117 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005118 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005119 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005120 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005121 }
deadbeeffac06552015-11-25 11:26:01 -08005122
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005123 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005124 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005125}
5126
Steve Anton4171afb2017-11-20 10:20:22 -08005127void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5128 cricket::MediaType media_type) {
5129 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005130 if (!sender) {
5131 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005132 // SessionDescriptions has been renegotiated.
5133 return;
5134 }
deadbeeffac06552015-11-25 11:26:01 -08005135
5136 // A sender has been removed from the SessionDescription but it's still
5137 // associated with the PeerConnection. This only occurs if the SDP doesn't
5138 // match with the calls to CreateSender, AddStream and RemoveStream.
5139 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005140 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005141 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005142 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005143 }
deadbeeffac06552015-11-25 11:26:01 -08005144
Steve Anton4171afb2017-11-20 10:20:22 -08005145 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005146}
5147
5148void PeerConnection::UpdateLocalRtpDataChannels(
5149 const cricket::StreamParamsVec& streams) {
5150 std::vector<std::string> existing_channels;
5151
5152 // Find new and active data channels.
5153 for (const cricket::StreamParams& params : streams) {
5154 // |it->sync_label| is actually the data channel label. The reason is that
5155 // we use the same naming of data channels as we do for
5156 // MediaStreams and Tracks.
5157 // For MediaStreams, the sync_label is the MediaStream label and the
5158 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005159 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005160 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005161 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005162 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005163 continue;
5164 }
5165 // Set the SSRC the data channel should use for sending.
5166 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5167 existing_channels.push_back(data_channel_it->first);
5168 }
5169
5170 UpdateClosingRtpDataChannels(existing_channels, true);
5171}
5172
5173void PeerConnection::UpdateRemoteRtpDataChannels(
5174 const cricket::StreamParamsVec& streams) {
5175 std::vector<std::string> existing_channels;
5176
5177 // Find new and active data channels.
5178 for (const cricket::StreamParams& params : streams) {
5179 // The data channel label is either the mslabel or the SSRC if the mslabel
5180 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005181 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005182 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005183 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005184 auto data_channel_it = rtp_data_channels_.find(label);
5185 if (data_channel_it == rtp_data_channels_.end()) {
5186 // This is a new data channel.
5187 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5188 } else {
5189 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5190 }
5191 existing_channels.push_back(label);
5192 }
5193
5194 UpdateClosingRtpDataChannels(existing_channels, false);
5195}
5196
5197void PeerConnection::UpdateClosingRtpDataChannels(
5198 const std::vector<std::string>& active_channels,
5199 bool is_local_update) {
5200 auto it = rtp_data_channels_.begin();
5201 while (it != rtp_data_channels_.end()) {
5202 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005203 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005204 ++it;
5205 continue;
5206 }
5207
5208 if (is_local_update) {
5209 data_channel->SetSendSsrc(0);
5210 } else {
5211 data_channel->RemotePeerRequestClose();
5212 }
5213
5214 if (data_channel->state() == DataChannel::kClosed) {
5215 rtp_data_channels_.erase(it);
5216 it = rtp_data_channels_.begin();
5217 } else {
5218 ++it;
5219 }
5220 }
5221}
5222
5223void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5224 uint32_t remote_ssrc) {
5225 rtc::scoped_refptr<DataChannel> channel(
5226 InternalCreateDataChannel(label, nullptr));
5227 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005228 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005229 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005230 return;
5231 }
5232 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005233 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5234 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005235 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005236}
5237
5238rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5239 const std::string& label,
5240 const InternalDataChannelInit* config) {
5241 if (IsClosed()) {
5242 return nullptr;
5243 }
Steve Anton75737c02017-11-06 10:37:17 -08005244 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005245 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005246 << "InternalCreateDataChannel: Data is not supported in this call.";
5247 return nullptr;
5248 }
5249 InternalDataChannelInit new_config =
5250 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005251 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005252 if (new_config.id < 0) {
5253 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005254 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005255 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005256 RTC_LOG(LS_ERROR)
5257 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005258 return nullptr;
5259 }
5260 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005261 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005262 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005263 return nullptr;
5264 }
5265 }
5266
Steve Anton75737c02017-11-06 10:37:17 -08005267 rtc::scoped_refptr<DataChannel> channel(
5268 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005269 if (!channel) {
5270 sid_allocator_.ReleaseSid(new_config.id);
5271 return nullptr;
5272 }
5273
5274 if (channel->data_channel_type() == cricket::DCT_RTP) {
5275 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005276 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5277 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005278 return nullptr;
5279 }
5280 rtp_data_channels_[channel->label()] = channel;
5281 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005282 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005283 sctp_data_channels_.push_back(channel);
5284 channel->SignalClosed.connect(this,
5285 &PeerConnection::OnSctpDataChannelClosed);
5286 }
5287
Steve Anton2d8609c2018-01-23 16:38:46 -08005288 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005289 return channel;
5290}
5291
5292bool PeerConnection::HasDataChannels() const {
5293 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5294}
5295
5296void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005297 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005298 for (const auto& channel : sctp_data_channels_) {
5299 if (channel->id() < 0) {
5300 int sid;
5301 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005302 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5303 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005304 continue;
5305 }
5306 channel->SetSctpSid(sid);
5307 }
5308 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005309 // Since closing modifies the list of channels, we have to do the actual
5310 // closing outside the loop.
5311 for (const auto& channel : channels_to_close) {
5312 channel->CloseAbruptly();
5313 }
deadbeefab9b2d12015-10-14 11:33:11 -07005314}
5315
5316void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005317 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005318 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5319 ++it) {
5320 if (it->get() == channel) {
5321 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005322 // After the closing procedure is done, it's safe to use this ID for
5323 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005324 sid_allocator_.ReleaseSid(channel->id());
5325 }
deadbeefbd292462015-12-14 18:15:29 -08005326 // Since this method is triggered by a signal from the DataChannel,
5327 // we can't free it directly here; we need to free it asynchronously.
5328 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005329 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005330 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5331 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005332 return;
5333 }
5334 }
5335}
5336
deadbeefab9b2d12015-10-14 11:33:11 -07005337void PeerConnection::OnDataChannelDestroyed() {
5338 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5339 // DataChannel may callback to us and try to modify the list.
5340 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5341 temp_rtp_dcs.swap(rtp_data_channels_);
5342 for (const auto& kv : temp_rtp_dcs) {
5343 kv.second->OnTransportChannelDestroyed();
5344 }
5345
5346 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5347 temp_sctp_dcs.swap(sctp_data_channels_);
5348 for (const auto& channel : temp_sctp_dcs) {
5349 channel->OnTransportChannelDestroyed();
5350 }
5351}
5352
5353void PeerConnection::OnDataChannelOpenMessage(
5354 const std::string& label,
5355 const InternalDataChannelInit& config) {
5356 rtc::scoped_refptr<DataChannel> channel(
5357 InternalCreateDataChannel(label, &config));
5358 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005359 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005360 return;
5361 }
5362
deadbeefa601f5c2016-06-06 14:27:39 -07005363 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5364 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005365 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005366 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005367}
5368
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005369bool PeerConnection::HandleOpenMessage_s(
5370 const cricket::ReceiveDataParams& params,
5371 const rtc::CopyOnWriteBuffer& buffer) {
5372 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5373 // Received OPEN message; parse and signal that a new data channel should
5374 // be created.
5375 std::string label;
5376 InternalDataChannelInit config;
5377 config.id = params.ssrc;
5378 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5379 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5380 << params.ssrc;
5381 return true;
5382 }
5383 config.open_handshake_role = InternalDataChannelInit::kAcker;
5384 OnDataChannelOpenMessage(label, config);
5385 return true;
5386 }
5387 return false;
5388}
5389
Steve Anton4171afb2017-11-20 10:20:22 -08005390rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5391PeerConnection::GetAudioTransceiver() const {
5392 // This method only works with Plan B SDP, where there is a single
5393 // audio/video transceiver.
5394 RTC_DCHECK(!IsUnifiedPlan());
5395 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005396 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005397 return transceiver;
5398 }
5399 }
5400 RTC_NOTREACHED();
5401 return nullptr;
5402}
5403
5404rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5405PeerConnection::GetVideoTransceiver() const {
5406 // This method only works with Plan B SDP, where there is a single
5407 // audio/video transceiver.
5408 RTC_DCHECK(!IsUnifiedPlan());
5409 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005410 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005411 return transceiver;
5412 }
5413 }
5414 RTC_NOTREACHED();
5415 return nullptr;
5416}
5417
5418// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5419// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005420bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005421 switch (type) {
5422 case cricket::MEDIA_TYPE_AUDIO:
5423 return !GetAudioTransceiver()->internal()->senders().empty();
5424 case cricket::MEDIA_TYPE_VIDEO:
5425 return !GetVideoTransceiver()->internal()->senders().empty();
5426 case cricket::MEDIA_TYPE_DATA:
5427 return false;
5428 }
5429 RTC_NOTREACHED();
5430 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005431}
5432
Steve Anton4171afb2017-11-20 10:20:22 -08005433rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5434PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005435 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005436 for (auto sender : transceiver->internal()->senders()) {
5437 if (sender->track() == track) {
5438 return sender;
5439 }
5440 }
5441 }
5442 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005443}
5444
Steve Anton4171afb2017-11-20 10:20:22 -08005445rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5446PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005447 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005448 for (auto sender : transceiver->internal()->senders()) {
5449 if (sender->id() == sender_id) {
5450 return sender;
5451 }
5452 }
5453 }
5454 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005455}
5456
Steve Anton4171afb2017-11-20 10:20:22 -08005457rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5458PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005459 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005460 for (auto receiver : transceiver->internal()->receivers()) {
5461 if (receiver->id() == receiver_id) {
5462 return receiver;
5463 }
5464 }
5465 }
5466 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005467}
5468
Steve Anton4171afb2017-11-20 10:20:22 -08005469std::vector<PeerConnection::RtpSenderInfo>*
5470PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5471 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5472 media_type == cricket::MEDIA_TYPE_VIDEO);
5473 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5474 ? &remote_audio_sender_infos_
5475 : &remote_video_sender_infos_;
5476}
5477
5478std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005479 cricket::MediaType media_type) {
5480 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5481 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005482 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5483 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005484}
5485
Steve Anton4171afb2017-11-20 10:20:22 -08005486const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5487 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005488 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005489 const std::string sender_id) const {
5490 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005491 if (sender_info.stream_id == stream_id &&
5492 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005493 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005494 }
5495 }
5496 return nullptr;
5497}
5498
5499DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5500 for (const auto& channel : sctp_data_channels_) {
5501 if (channel->id() == sid) {
5502 return channel;
5503 }
5504 }
5505 return nullptr;
5506}
5507
Karl Wibergfb3be392019-03-22 14:13:22 +01005508PeerConnection::InitializePortAllocatorResult
5509PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005510 const cricket::ServerAddresses& stun_servers,
5511 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005512 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005513 RTC_DCHECK_RUN_ON(network_thread());
5514
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005515 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005516 // To handle both internal and externally created port allocator, we will
5517 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005518 int port_allocator_flags = port_allocator_->flags();
5519 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5520 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5521 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005522 // If the disable-IPv6 flag was specified, we'll not override it
5523 // by experiment.
5524 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005525 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005526 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5527 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005528 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005529 }
5530
zhihuangb09b3f92017-03-07 14:40:51 -08005531 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005532 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005533 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005534 }
5535
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005536 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005537 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005538 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005539 }
5540
honghaiz60347052016-05-31 18:29:12 -07005541 if (configuration.candidate_network_policy ==
5542 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005543 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005544 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005545 }
5546
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005547 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005548 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005549 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5550 }
5551
Karl Wibergfb3be392019-03-22 14:13:22 +01005552 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005553 // No step delay is used while allocating ports.
5554 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005555 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005556 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005557 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005558
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005559 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005560 for (auto& turn_server : turn_servers_copy) {
5561 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005562 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005563 // Call this last since it may create pooled allocator sessions using the
5564 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005565 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005566 stun_servers, std::move(turn_servers_copy),
5567 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5568 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005569 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005570
5571 InitializePortAllocatorResult res;
5572 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5573 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005574}
5575
deadbeef91dd5672016-05-18 16:55:30 -07005576bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005577 const cricket::ServerAddresses& stun_servers,
5578 const std::vector<cricket::RelayServerConfig>& turn_servers,
5579 IceTransportsType type,
5580 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005581 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005582 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005583 absl::optional<int> stun_candidate_keepalive_interval,
5584 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005585 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005586 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005587 // According to JSEP, after setLocalDescription, changing the candidate pool
5588 // size is not allowed, and changing the set of ICE servers will not result
5589 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005590 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005591 port_allocator_->FreezeCandidatePool();
5592 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005593 // Add the custom tls turn servers if they exist.
5594 auto turn_servers_copy = turn_servers;
5595 for (auto& turn_server : turn_servers_copy) {
5596 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5597 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005598 // Call this last since it may create pooled allocator sessions using the
5599 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005600 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005601 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5602 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005603}
5604
Steve Antonba818672017-11-06 10:21:57 -08005605cricket::ChannelManager* PeerConnection::channel_manager() const {
5606 return factory_->channel_manager();
5607}
5608
Elad Alon99c3fe52017-10-13 16:29:40 +02005609bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005610 std::unique_ptr<RtcEventLogOutput> output,
5611 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005612 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005613 if (!event_log_) {
5614 return false;
5615 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005616 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005617}
5618
5619void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005620 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005621 if (event_log_) {
5622 event_log_->StopLogging();
5623 }
ivoc14d5dbe2016-07-04 07:06:55 -07005624}
nisseeaabdf62017-05-05 02:23:02 -07005625
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005626cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005627 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005628 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005629 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005630 if (channel && channel->content_name() == content_name) {
5631 return channel;
5632 }
Steve Anton75737c02017-11-06 10:37:17 -08005633 }
5634 if (rtp_data_channel() &&
5635 rtp_data_channel()->content_name() == content_name) {
5636 return rtp_data_channel();
5637 }
5638 return nullptr;
5639}
5640
5641bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005642 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005643 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005644 RTC_LOG(LS_INFO)
5645 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005646 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005647 return false;
5648 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005649 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005650 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005651 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005652 return false;
5653 }
5654
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005655 absl::optional<rtc::SSLRole> dtls_role;
5656 if (sctp_mid_) {
5657 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5658 } else if (is_caller_) {
5659 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5660 }
Zhi Huange830e682018-03-30 10:48:35 -07005661 if (dtls_role) {
5662 *role = *dtls_role;
5663 return true;
5664 }
5665 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005666}
5667
5668bool PeerConnection::GetSslRole(const std::string& content_name,
5669 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005670 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005671 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005672 RTC_LOG(LS_INFO)
5673 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005674 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005675 return false;
5676 }
5677
Zhi Huange830e682018-03-30 10:48:35 -07005678 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5679 if (dtls_role) {
5680 *role = *dtls_role;
5681 return true;
5682 }
5683 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005684}
5685
Steve Antonf8470812017-12-04 10:46:21 -08005686void PeerConnection::SetSessionError(SessionError error,
5687 const std::string& error_desc) {
5688 RTC_DCHECK_RUN_ON(signaling_thread());
5689 if (error != session_error_) {
5690 session_error_ = error;
5691 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005692 }
5693}
5694
Zhi Huange830e682018-03-30 10:48:35 -07005695RTCError PeerConnection::UpdateSessionState(
5696 SdpType type,
5697 cricket::ContentSource source,
5698 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005699 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005700
5701 // If there's already a pending error then no state transition should happen.
5702 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005703 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005704
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005705 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005706 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005707 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005708 }
5709
5710 // Update the signaling state according to the specified state machine (see
5711 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005712 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005713 ChangeSignalingState(source == cricket::CS_LOCAL
5714 ? PeerConnectionInterface::kHaveLocalOffer
5715 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005716 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005717 ChangeSignalingState(source == cricket::CS_LOCAL
5718 ? PeerConnectionInterface::kHaveLocalPrAnswer
5719 : PeerConnectionInterface::kHaveRemotePrAnswer);
5720 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005721 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005722 ChangeSignalingState(PeerConnectionInterface::kStable);
5723 }
5724
5725 // Update internal objects according to the session description's media
5726 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005727 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005728 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005729 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005730 }
5731
Steve Anton8a006912017-12-04 15:25:56 -08005732 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005733}
5734
Steve Anton8a006912017-12-04 15:25:56 -08005735RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005736 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005737 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005738 const SessionDescriptionInterface* sdesc =
5739 (source == cricket::CS_LOCAL ? local_description()
5740 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005741 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005742
5743 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005744 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005745 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005746 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005747 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005748 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005749 continue;
5750 }
5751 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005752 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005753 if (!content_desc) {
5754 continue;
5755 }
5756 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005757 bool success = (source == cricket::CS_LOCAL)
5758 ? channel->SetLocalContent(content_desc, type, &error)
5759 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005760 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005761 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005762 }
5763 }
5764
5765 // If using the RtpDataChannel, push down the new SDP section for it too.
5766 if (rtp_data_channel_) {
5767 const ContentInfo* data_content =
5768 cricket::GetFirstDataContent(sdesc->description());
5769 if (data_content && !data_content->rejected) {
5770 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005771 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005772 if (data_desc) {
5773 std::string error;
5774 bool success =
5775 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005776 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005777 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005778 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005779 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005780 }
Steve Anton75737c02017-11-06 10:37:17 -08005781 }
5782 }
5783 }
Steve Antoned10bd92017-12-05 10:52:59 -08005784
Steve Anton75737c02017-11-06 10:37:17 -08005785 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5786 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005787 if (sctp_transport_ && local_description() && remote_description()) {
5788 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5789 local_description()->description());
5790 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5791 remote_description()->description());
5792 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005793 int max_message_size;
5794 // A remote max message size of zero means "any size supported".
5795 // We configure the connection with our own max message size.
5796 if (remote_sctp_description->max_message_size() == 0) {
5797 max_message_size = local_sctp_description->max_message_size();
5798 } else {
5799 max_message_size =
5800 std::min(local_sctp_description->max_message_size(),
5801 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005802 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005803 sctp_transport_->Start(local_sctp_description->port(),
5804 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005805 }
Steve Anton75737c02017-11-06 10:37:17 -08005806 }
Steve Antoned10bd92017-12-05 10:52:59 -08005807
Steve Anton8a006912017-12-04 15:25:56 -08005808 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005809}
5810
Steve Anton8a006912017-12-04 15:25:56 -08005811RTCError PeerConnection::PushdownTransportDescription(
5812 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005813 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005814 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005815
Zhi Huange830e682018-03-30 10:48:35 -07005816 if (source == cricket::CS_LOCAL) {
5817 const SessionDescriptionInterface* sdesc = local_description();
5818 RTC_DCHECK(sdesc);
5819 return transport_controller_->SetLocalDescription(type,
5820 sdesc->description());
5821 } else {
5822 const SessionDescriptionInterface* sdesc = remote_description();
5823 RTC_DCHECK(sdesc);
5824 return transport_controller_->SetRemoteDescription(type,
5825 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005826 }
Steve Anton75737c02017-11-06 10:37:17 -08005827}
5828
5829bool PeerConnection::GetTransportDescription(
5830 const SessionDescription* description,
5831 const std::string& content_name,
5832 cricket::TransportDescription* tdesc) {
5833 if (!description || !tdesc) {
5834 return false;
5835 }
5836 const TransportInfo* transport_info =
5837 description->GetTransportInfoByName(content_name);
5838 if (!transport_info) {
5839 return false;
5840 }
5841 *tdesc = transport_info->description;
5842 return true;
5843}
5844
Steve Anton75737c02017-11-06 10:37:17 -08005845cricket::IceConfig PeerConnection::ParseIceConfig(
5846 const PeerConnectionInterface::RTCConfiguration& config) const {
5847 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005848 switch (config.continual_gathering_policy) {
5849 case PeerConnectionInterface::GATHER_ONCE:
5850 gathering_policy = cricket::GATHER_ONCE;
5851 break;
5852 case PeerConnectionInterface::GATHER_CONTINUALLY:
5853 gathering_policy = cricket::GATHER_CONTINUALLY;
5854 break;
5855 default:
5856 RTC_NOTREACHED();
5857 gathering_policy = cricket::GATHER_ONCE;
5858 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005859
Steve Anton75737c02017-11-06 10:37:17 -08005860 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005861 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5862 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005863 ice_config.prioritize_most_likely_candidate_pairs =
5864 config.prioritize_most_likely_ice_candidate_pairs;
5865 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005866 RTCConfigurationToIceConfigOptionalInt(
5867 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005868 ice_config.continual_gathering_policy = gathering_policy;
5869 ice_config.presume_writable_when_fully_relayed =
5870 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005871 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5872 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005873 ice_config.ice_check_interval_strong_connectivity =
5874 config.ice_check_interval_strong_connectivity;
5875 ice_config.ice_check_interval_weak_connectivity =
5876 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005877 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005878 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5879 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005880 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005881 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005882 ice_config.regather_all_networks_interval_range =
5883 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005884 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005885 return ice_config;
5886}
5887
Steve Anton75737c02017-11-06 10:37:17 -08005888bool PeerConnection::SendData(const cricket::SendDataParams& params,
5889 const rtc::CopyOnWriteBuffer& payload,
5890 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005891 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005892 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5893 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5894 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005895 return false;
5896 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005897 if (media_transport_) {
5898 SendDataParams send_params;
5899 send_params.type = ToWebrtcDataMessageType(params.type);
5900 send_params.ordered = params.ordered;
5901 if (params.max_rtx_count >= 0) {
5902 send_params.max_rtx_count = params.max_rtx_count;
5903 } else if (params.max_rtx_ms >= 0) {
5904 send_params.max_rtx_ms = params.max_rtx_ms;
5905 }
5906 return media_transport_->SendData(params.sid, send_params, payload).ok();
5907 }
Steve Anton75737c02017-11-06 10:37:17 -08005908 return rtp_data_channel_
5909 ? rtp_data_channel_->SendData(params, payload, result)
5910 : network_thread()->Invoke<bool>(
5911 RTC_FROM_HERE,
5912 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005913 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005914}
5915
5916bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005917 RTC_DCHECK_RUN_ON(signaling_thread());
5918 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005919 // Don't log an error here, because DataChannels are expected to call
5920 // ConnectDataChannel in this state. It's the only way to initially tell
5921 // whether or not the underlying transport is ready.
5922 return false;
5923 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005924 if (media_transport_) {
5925 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5926 &DataChannel::OnChannelReady);
5927 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5928 &DataChannel::OnDataReceived);
5929 SignalMediaTransportChannelClosing_s.connect(
5930 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5931 SignalMediaTransportChannelClosed_s.connect(
5932 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5933 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005934 rtp_data_channel_->SignalReadyToSendData.connect(
5935 webrtc_data_channel, &DataChannel::OnChannelReady);
5936 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5937 &DataChannel::OnDataReceived);
5938 } else {
5939 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5940 &DataChannel::OnChannelReady);
5941 SignalSctpDataReceived.connect(webrtc_data_channel,
5942 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005943 SignalSctpClosingProcedureStartedRemotely.connect(
5944 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5945 SignalSctpClosingProcedureComplete.connect(
5946 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005947 }
5948 return true;
5949}
5950
5951void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005952 RTC_DCHECK_RUN_ON(signaling_thread());
5953 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005954 RTC_LOG(LS_ERROR)
5955 << "DisconnectDataChannel called when rtp_data_channel_ and "
5956 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005957 return;
5958 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005959 if (media_transport_) {
5960 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5961 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5962 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5963 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5964 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005965 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5966 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5967 } else {
5968 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5969 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005970 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5971 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005972 }
5973}
5974
5975void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005976 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005977 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005978 return;
5979 }
Steve Anton75737c02017-11-06 10:37:17 -08005980 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005981 RTC_LOG(LS_ERROR)
5982 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005983 return;
5984 }
5985 network_thread()->Invoke<void>(
5986 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005987 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005988}
5989
5990void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005991 if (media_transport_) {
5992 media_transport_->CloseChannel(sid);
5993 return;
5994 }
Steve Anton75737c02017-11-06 10:37:17 -08005995 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005996 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005997 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005998 return;
5999 }
6000 network_thread()->Invoke<void>(
6001 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006002 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08006003}
6004
6005bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006006 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006007 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006008 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08006009 sctp_ready_to_send_data_;
6010}
6011
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006012void PeerConnection::OnDataReceived(int channel_id,
6013 DataMessageType type,
6014 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006015 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006016 cricket::ReceiveDataParams params;
6017 params.sid = channel_id;
6018 params.type = ToCricketDataMessageType(type);
6019 media_transport_invoker_->AsyncInvoke<void>(
6020 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
6021 RTC_DCHECK_RUN_ON(signaling_thread());
6022 if (!HandleOpenMessage_s(params, buffer)) {
6023 SignalMediaTransportReceivedData_s(params, buffer);
6024 }
6025 });
6026}
6027
6028void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006029 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006030 media_transport_invoker_->AsyncInvoke<void>(
6031 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6032 RTC_DCHECK_RUN_ON(signaling_thread());
6033 SignalMediaTransportChannelClosing_s(channel_id);
6034 });
6035}
6036
6037void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02006038 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006039 media_transport_invoker_->AsyncInvoke<void>(
6040 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
6041 RTC_DCHECK_RUN_ON(signaling_thread());
6042 SignalMediaTransportChannelClosed_s(channel_id);
6043 });
6044}
6045
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006046absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006047 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006048 if (sctp_mid_ && transport_controller_) {
6049 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6050 if (dtls_transport) {
6051 return dtls_transport->transport_name();
6052 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006053 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006054 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006055 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006056}
6057
Qingsi Wang72a43a12018-02-20 16:03:18 -08006058cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6059 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006060 network_thread()->Invoke<void>(
6061 RTC_FROM_HERE,
6062 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6063 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006064 return candidate_states_list;
6065}
6066
Steve Anton5dfde182018-02-06 10:34:40 -08006067std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6068 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006069 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006070 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006071 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006072 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006073 if (channel) {
6074 transport_names_by_mid[channel->content_name()] =
6075 channel->transport_name();
6076 }
Steve Anton75737c02017-11-06 10:37:17 -08006077 }
Steve Anton5dfde182018-02-06 10:34:40 -08006078 if (rtp_data_channel_) {
6079 transport_names_by_mid[rtp_data_channel_->content_name()] =
6080 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006081 }
6082 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006083 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006084 RTC_DCHECK(transport_name);
6085 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006086 }
Steve Anton5dfde182018-02-06 10:34:40 -08006087 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006088}
6089
Steve Anton5dfde182018-02-06 10:34:40 -08006090std::map<std::string, cricket::TransportStats>
6091PeerConnection::GetTransportStatsByNames(
6092 const std::set<std::string>& transport_names) {
6093 if (!network_thread()->IsCurrent()) {
6094 return network_thread()
6095 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6096 RTC_FROM_HERE,
6097 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006098 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006099 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006100 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6101 for (const std::string& transport_name : transport_names) {
6102 cricket::TransportStats transport_stats;
6103 bool success =
6104 transport_controller_->GetStats(transport_name, &transport_stats);
6105 if (success) {
6106 transport_stats_by_name[transport_name] = std::move(transport_stats);
6107 } else {
6108 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6109 << transport_name;
6110 }
6111 }
6112 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006113}
6114
6115bool PeerConnection::GetLocalCertificate(
6116 const std::string& transport_name,
6117 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006118 if (!certificate) {
6119 return false;
6120 }
6121 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6122 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006123}
6124
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006125std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006126 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006127 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006128}
6129
6130cricket::DataChannelType PeerConnection::data_channel_type() const {
6131 return data_channel_type_;
6132}
6133
6134bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006135 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006136 return pending_ice_restarts_.find(content_name) !=
6137 pending_ice_restarts_.end();
6138}
6139
Steve Anton75737c02017-11-06 10:37:17 -08006140bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6141 return transport_controller_->NeedsIceRestart(content_name);
6142}
6143
6144void PeerConnection::OnCertificateReady(
6145 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6146 transport_controller_->SetLocalCertificate(certificate);
6147}
6148
6149void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006150 SetSessionError(SessionError::kTransport,
6151 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006152}
6153
Alex Loiko9289eda2018-11-23 16:18:59 +00006154void PeerConnection::OnTransportControllerConnectionState(
6155 cricket::IceConnectionState state) {
6156 switch (state) {
6157 case cricket::kIceConnectionConnecting:
6158 // If the current state is Connected or Completed, then there were
6159 // writable channels but now there are not, so the next state must
6160 // be Disconnected.
6161 // kIceConnectionConnecting is currently used as the default,
6162 // un-connected state by the TransportController, so its only use is
6163 // detecting disconnections.
6164 if (ice_connection_state_ ==
6165 PeerConnectionInterface::kIceConnectionConnected ||
6166 ice_connection_state_ ==
6167 PeerConnectionInterface::kIceConnectionCompleted) {
6168 SetIceConnectionState(
6169 PeerConnectionInterface::kIceConnectionDisconnected);
6170 }
6171 break;
6172 case cricket::kIceConnectionFailed:
6173 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6174 break;
6175 case cricket::kIceConnectionConnected:
6176 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6177 "all transports are writable.";
6178 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6179 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6180 break;
6181 case cricket::kIceConnectionCompleted:
6182 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6183 "all transports are complete.";
6184 if (ice_connection_state_ !=
6185 PeerConnectionInterface::kIceConnectionConnected) {
6186 // If jumping directly from "checking" to "connected",
6187 // signal "connected" first.
6188 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6189 }
6190 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6191 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6192 ReportTransportStats();
6193 break;
6194 default:
6195 RTC_NOTREACHED();
6196 }
6197}
6198
Steve Anton75737c02017-11-06 10:37:17 -08006199void PeerConnection::OnTransportControllerCandidatesGathered(
6200 const std::string& transport_name,
6201 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006202 int sdp_mline_index;
6203 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006204 RTC_LOG(LS_ERROR)
6205 << "OnTransportControllerCandidatesGathered: content name "
6206 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006207 return;
6208 }
6209
6210 for (cricket::Candidates::const_iterator citer = candidates.begin();
6211 citer != candidates.end(); ++citer) {
6212 // Use transport_name as the candidate media id.
6213 std::unique_ptr<JsepIceCandidate> candidate(
6214 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6215 if (local_description()) {
6216 mutable_local_description()->AddCandidate(candidate.get());
6217 }
6218 OnIceCandidate(std::move(candidate));
6219 }
6220}
6221
Eldar Relloda13ea22019-06-01 12:23:43 +03006222void PeerConnection::OnTransportControllerCandidateError(
6223 const cricket::IceCandidateErrorEvent& event) {
6224 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6225 event.error_text);
6226}
6227
Steve Anton75737c02017-11-06 10:37:17 -08006228void PeerConnection::OnTransportControllerCandidatesRemoved(
6229 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006230 // Sanity check.
6231 for (const cricket::Candidate& candidate : candidates) {
6232 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006233 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006234 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006235 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006236 return;
6237 }
6238 }
6239
6240 if (local_description()) {
6241 mutable_local_description()->RemoveCandidates(candidates);
6242 }
6243 OnIceCandidatesRemoved(candidates);
6244}
6245
Alex Drake00c7ecf2019-08-06 10:54:47 -07006246void PeerConnection::OnTransportControllerCandidateChanged(
6247 const cricket::CandidatePairChangeEvent& event) {
6248 OnSelectedCandidatePairChanged(event);
6249}
6250
Steve Anton75737c02017-11-06 10:37:17 -08006251void PeerConnection::OnTransportControllerDtlsHandshakeError(
6252 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006253 RTC_HISTOGRAM_ENUMERATION(
6254 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6255 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006256}
6257
Steve Antoned10bd92017-12-05 10:52:59 -08006258void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006259 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006260 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006261 if (channel && !channel->enabled()) {
6262 channel->Enable(true);
6263 }
Steve Anton75737c02017-11-06 10:37:17 -08006264 }
6265
Steve Anton4171afb2017-11-20 10:20:22 -08006266 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006267 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006268 }
Steve Anton75737c02017-11-06 10:37:17 -08006269}
6270
6271// Returns the media index for a local ice candidate given the content name.
6272bool PeerConnection::GetLocalCandidateMediaIndex(
6273 const std::string& content_name,
6274 int* sdp_mline_index) {
6275 if (!local_description() || !sdp_mline_index) {
6276 return false;
6277 }
6278
6279 bool content_found = false;
6280 const ContentInfos& contents = local_description()->description()->contents();
6281 for (size_t index = 0; index < contents.size(); ++index) {
6282 if (contents[index].name == content_name) {
6283 *sdp_mline_index = static_cast<int>(index);
6284 content_found = true;
6285 break;
6286 }
6287 }
6288 return content_found;
6289}
6290
6291bool PeerConnection::UseCandidatesInSessionDescription(
6292 const SessionDescriptionInterface* remote_desc) {
6293 if (!remote_desc) {
6294 return true;
6295 }
6296 bool ret = true;
6297
6298 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6299 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6300 for (size_t n = 0; n < candidates->count(); ++n) {
6301 const IceCandidateInterface* candidate = candidates->at(n);
6302 bool valid = false;
6303 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6304 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006305 RTC_LOG(LS_INFO)
6306 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006307 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006308 }
6309 continue;
6310 }
6311 ret = UseCandidate(candidate);
6312 if (!ret) {
6313 break;
6314 }
6315 }
6316 }
6317 return ret;
6318}
6319
6320bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006321 RTCErrorOr<const cricket::ContentInfo*> result =
6322 FindContentInfo(remote_description(), candidate);
6323 if (!result.ok()) {
6324 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6325 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006326 return false;
6327 }
Steve Anton75737c02017-11-06 10:37:17 -08006328 std::vector<cricket::Candidate> candidates;
6329 candidates.push_back(candidate->candidate());
6330 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006331 RTCError error = transport_controller_->AddRemoteCandidates(
6332 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006333 if (error.ok()) {
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006334 ReportRemoteIceCandidateAdded(candidate->candidate());
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006335 // Candidates successfully submitted for checking.
6336 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6337 ice_connection_state_ ==
6338 PeerConnectionInterface::kIceConnectionDisconnected) {
6339 // If state is New, then the session has just gotten its first remote ICE
6340 // candidates, so go to Checking.
6341 // If state is Disconnected, the session is re-using old candidates or
6342 // receiving additional ones, so go to Checking.
6343 // If state is Connected, stay Connected.
6344 // TODO(bemasc): If state is Connected, and the new candidates are for a
6345 // newly added transport, then the state actually _should_ move to
6346 // checking. Add a way to distinguish that case.
6347 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6348 }
6349 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006350 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006351 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006352 }
6353 return true;
6354}
6355
Guido Urdaneta41633172019-05-23 20:12:29 +02006356RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6357 const SessionDescriptionInterface* description,
6358 const IceCandidateInterface* candidate) {
6359 if (candidate->sdp_mline_index() >= 0) {
6360 size_t mediacontent_index =
6361 static_cast<size_t>(candidate->sdp_mline_index());
6362 size_t content_size = description->description()->contents().size();
6363 if (mediacontent_index < content_size) {
6364 return &description->description()->contents()[mediacontent_index];
6365 } else {
6366 return RTCError(RTCErrorType::INVALID_RANGE,
6367 "Media line index (" +
6368 rtc::ToString(candidate->sdp_mline_index()) +
6369 ") out of range (number of mlines: " +
6370 rtc::ToString(content_size) + ").");
6371 }
6372 } else if (!candidate->sdp_mid().empty()) {
6373 auto& contents = description->description()->contents();
6374 auto it = absl::c_find_if(
6375 contents, [candidate](const cricket::ContentInfo& content_info) {
6376 return content_info.mid() == candidate->sdp_mid();
6377 });
6378 if (it == contents.end()) {
6379 return RTCError(
6380 RTCErrorType::INVALID_PARAMETER,
6381 "Mid " + candidate->sdp_mid() +
6382 " specified but no media section with that mid found.");
6383 } else {
6384 return &*it;
6385 }
6386 }
6387
6388 return RTCError(RTCErrorType::INVALID_PARAMETER,
6389 "Neither sdp_mline_index nor sdp_mid specified.");
6390}
6391
Steve Anton75737c02017-11-06 10:37:17 -08006392void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006393 // Destroy video channel first since it may have a pointer to the
6394 // voice channel.
6395 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006396 if (!video_info || video_info->rejected) {
6397 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006398 }
6399
Steve Anton6fec8802017-12-04 10:37:29 -08006400 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6401 if (!audio_info || audio_info->rejected) {
6402 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006403 }
6404
6405 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6406 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006407 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006408 }
6409}
6410
Steve Antondcc3c022017-12-22 16:02:54 -08006411RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6412 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006413 const cricket::ContentGroup* bundle_group = nullptr;
6414 if (configuration_.bundle_policy ==
6415 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006416 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006417 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6419 "max-bundle configured but session description "
6420 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006421 }
6422 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006423 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006424}
6425
6426RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006427 // Creating the media channels. Transports should already have been created
6428 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006429 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006430 if (voice && !voice->rejected &&
6431 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006432 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006433 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006434 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6435 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006436 }
6437 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6438 }
6439
Steve Antondcc3c022017-12-22 16:02:54 -08006440 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006441 if (video && !video->rejected &&
6442 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006443 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006444 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006445 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6446 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006447 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006448 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006449 }
6450
Steve Antondcc3c022017-12-22 16:02:54 -08006451 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006452 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006453 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006454 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006455 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6456 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006457 }
6458 }
6459
Steve Anton8a006912017-12-04 15:25:56 -08006460 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006461}
6462
Steve Anton4171afb2017-11-20 10:20:22 -08006463// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006464cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006465 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006466 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006467 MediaTransportConfig media_transport_config =
6468 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006469
Steve Anton75737c02017-11-06 10:37:17 -08006470 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006471 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006472 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6473 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006474 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006475 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006476 }
Steve Anton75737c02017-11-06 10:37:17 -08006477 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6478 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006479 voice_channel->SignalSentPacket.connect(this,
6480 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006481 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006482
Steve Antoneda6ccd2017-12-04 10:21:55 -08006483 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006484}
6485
Steve Anton4171afb2017-11-20 10:20:22 -08006486// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006487cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006488 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006489 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006490 MediaTransportConfig media_transport_config =
6491 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006492
Steve Anton75737c02017-11-06 10:37:17 -08006493 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006494 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006495 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6496 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006497 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006498 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006499 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006500 }
Steve Anton75737c02017-11-06 10:37:17 -08006501 video_channel->SignalDtlsSrtpSetupFailure.connect(
6502 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006503 video_channel->SignalSentPacket.connect(this,
6504 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006505 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006506
Steve Antoneda6ccd2017-12-04 10:21:55 -08006507 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006508}
6509
Zhi Huange830e682018-03-30 10:48:35 -07006510bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006511 switch (data_channel_type_) {
6512 case cricket::DCT_MEDIA_TRANSPORT:
6513 if (network_thread()->Invoke<bool>(
6514 RTC_FROM_HERE,
6515 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6516 this, mid))) {
6517 for (const auto& channel : sctp_data_channels_) {
6518 channel->OnTransportChannelCreated();
6519 }
6520 return true;
6521 }
Steve Anton75737c02017-11-06 10:37:17 -08006522 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006523 case cricket::DCT_SCTP:
6524 if (!sctp_factory_) {
6525 RTC_LOG(LS_ERROR)
6526 << "Trying to create SCTP transport, but didn't compile with "
6527 "SCTP support (HAVE_SCTP)";
6528 return false;
6529 }
6530 if (!network_thread()->Invoke<bool>(
6531 RTC_FROM_HERE,
6532 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6533 return false;
6534 }
6535 for (const auto& channel : sctp_data_channels_) {
6536 channel->OnTransportChannelCreated();
6537 }
6538 return true;
6539 case cricket::DCT_RTP:
6540 default:
6541 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6542 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6543 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006544 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006545 if (!rtp_data_channel_) {
6546 return false;
6547 }
6548 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6549 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6550 rtp_data_channel_->SignalSentPacket.connect(
6551 this, &PeerConnection::OnSentPacket_w);
6552 rtp_data_channel_->SetRtpTransport(rtp_transport);
6553 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006554 }
6555
Steve Anton75737c02017-11-06 10:37:17 -08006556 return true;
6557}
6558
6559Call::Stats PeerConnection::GetCallStats() {
6560 if (!worker_thread()->IsCurrent()) {
6561 return worker_thread()->Invoke<Call::Stats>(
6562 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6563 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006564 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006565 if (call_) {
6566 return call_->GetStats();
6567 } else {
6568 return Call::Stats();
6569 }
6570}
6571
Zhi Huange830e682018-03-30 10:48:35 -07006572bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006573 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006574 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006575 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6576 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006577 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006578 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006579 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006580 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6581 sctp_factory_->CreateSctpTransport(dtls_transport);
6582 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006583 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006584 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006585 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006586 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006587 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006588 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6589 // another thread. Would be nice if there was a helper class similar to
6590 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6591 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006592 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006593 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006594 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006595 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006596 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006597 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6598 std::move(cricket_sctp_transport));
6599 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006600 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006601}
6602
6603void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006604 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006605 sctp_transport_->Clear();
6606 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006607 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006608 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006609}
6610
6611void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006612 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006613 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006614 // Note: Cannot use rtc::Bind here because it will grab a reference to
6615 // PeerConnection and potentially cause PeerConnection to live longer than
6616 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6617 // be destroyed before PeerConnection is destroyed, and at that point all
6618 // pending tasks will be cleared.
6619 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6620 OnSctpTransportReadyToSendData_s(true);
6621 });
6622}
6623
6624void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006625 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006626 sctp_ready_to_send_data_ = ready;
6627 SignalSctpReadyToSendData(ready);
6628}
6629
6630void PeerConnection::OnSctpTransportDataReceived_n(
6631 const cricket::ReceiveDataParams& params,
6632 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006633 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006634 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006635 // Note: Cannot use rtc::Bind here because it will grab a reference to
6636 // PeerConnection and potentially cause PeerConnection to live longer than
6637 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6638 // be destroyed before PeerConnection is destroyed, and at that point all
6639 // pending tasks will be cleared.
6640 sctp_invoker_->AsyncInvoke<void>(
6641 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6642 OnSctpTransportDataReceived_s(params, payload);
6643 });
6644}
6645
6646void PeerConnection::OnSctpTransportDataReceived_s(
6647 const cricket::ReceiveDataParams& params,
6648 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006649 RTC_DCHECK_RUN_ON(signaling_thread());
6650 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006651 SignalSctpDataReceived(params, payload);
6652 }
6653}
6654
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006655void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006656 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006657 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006658 sctp_invoker_->AsyncInvoke<void>(
6659 RTC_FROM_HERE, signaling_thread(),
6660 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006661 &SignalSctpClosingProcedureStartedRemotely, sid));
6662}
6663
6664void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006665 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006666 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006667 sctp_invoker_->AsyncInvoke<void>(
6668 RTC_FROM_HERE, signaling_thread(),
6669 rtc::Bind(&sigslot::signal1<int>::operator(),
6670 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006671}
6672
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006673bool PeerConnection::SetupMediaTransportForDataChannels_n(
6674 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006675 media_transport_ =
6676 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006677 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006678 RTC_LOG(LS_ERROR)
6679 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006680 return false;
6681 }
6682
6683 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6684 media_transport_->SetDataSink(this);
6685 media_transport_data_mid_ = mid;
6686 transport_controller_->SignalMediaTransportStateChanged.connect(
6687 this, &PeerConnection::OnMediaTransportStateChanged_n);
6688 // Check the initial state right away, in case transport is already writable.
6689 OnMediaTransportStateChanged_n();
6690 return true;
6691}
6692
6693void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6694 if (!media_transport_) {
6695 return;
6696 }
6697 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6698 media_transport_data_mid_.reset();
6699 media_transport_->SetDataSink(nullptr);
6700 media_transport_invoker_ = nullptr;
6701 media_transport_ = nullptr;
6702}
6703
6704void PeerConnection::OnMediaTransportStateChanged_n() {
6705 if (!media_transport_data_mid_ ||
6706 transport_controller_->GetMediaTransportState(
6707 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6708 return;
6709 }
6710 media_transport_invoker_->AsyncInvoke<void>(
6711 RTC_FROM_HERE, signaling_thread(), [this] {
6712 RTC_DCHECK_RUN_ON(signaling_thread());
6713 media_transport_ready_to_send_data_ = true;
6714 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6715 });
6716}
6717
Steve Anton75737c02017-11-06 10:37:17 -08006718// Returns false if bundle is enabled and rtcp_mux is disabled.
6719bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6720 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6721 if (!bundle_enabled)
6722 return true;
6723
6724 const cricket::ContentGroup* bundle_group =
6725 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6726 RTC_DCHECK(bundle_group != NULL);
6727
6728 const cricket::ContentInfos& contents = desc->contents();
6729 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6730 citer != contents.end(); ++citer) {
6731 const cricket::ContentInfo* content = (&*citer);
6732 RTC_DCHECK(content != NULL);
6733 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006734 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006735 if (!HasRtcpMuxEnabled(content))
6736 return false;
6737 }
6738 }
6739 // RTCP-MUX is enabled in all the contents.
6740 return true;
6741}
6742
6743bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006744 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006745}
6746
Steve Anton06817cd2018-12-18 15:55:30 -08006747static RTCError ValidateMids(const cricket::SessionDescription& description) {
6748 std::set<std::string> mids;
6749 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006750 if (content.name.empty()) {
6751 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6752 "A media section is missing a MID attribute.");
6753 }
Steve Anton06817cd2018-12-18 15:55:30 -08006754 if (!mids.insert(content.name).second) {
6755 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6756 "Duplicate a=mid value '" + content.name + "'.");
6757 }
6758 }
6759 return RTCError::OK();
6760}
6761
Steve Anton8a006912017-12-04 15:25:56 -08006762RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006763 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006764 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006765 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006766 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006767 }
6768
6769 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006771 }
6772
Steve Anton3828c062017-12-06 10:34:51 -08006773 SdpType type = sdesc->GetType();
6774 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6775 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006776 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006777 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006778 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006779 }
6780
Steve Anton06817cd2018-12-18 15:55:30 -08006781 RTCError error = ValidateMids(*sdesc->description());
6782 if (!error.ok()) {
6783 return error;
6784 }
6785
Steve Anton75737c02017-11-06 10:37:17 -08006786 // Verify crypto settings.
6787 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006788 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6789 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006790 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006791 if (!crypto_error.ok()) {
6792 return crypto_error;
6793 }
Steve Anton75737c02017-11-06 10:37:17 -08006794 }
6795
6796 // Verify ice-ufrag and ice-pwd.
6797 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006798 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6799 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006800 }
6801
6802 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006803 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6804 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006805 }
6806
6807 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6808 // m-lines that do not rtcp-mux enabled.
6809
6810 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006811 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006812 // With an answer we want to compare the new answer session description with
6813 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006814 const cricket::SessionDescription* offer_desc =
6815 (source == cricket::CS_LOCAL) ? remote_description()->description()
6816 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006817 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6818 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6819 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006820 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6821 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006822 }
6823 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006824 // The re-offers should respect the order of m= sections in current
6825 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006826 // With a re-offer, either the current local or current remote descriptions
6827 // could be the most up to date, so we would like to check against both of
6828 // them if they exist. It could be the case that one of them has a 0 port
6829 // for a media section, but the other does not. This is important to check
6830 // against in the case that we are recycling an m= section.
6831 const cricket::SessionDescription* current_desc = nullptr;
6832 const cricket::SessionDescription* secondary_current_desc = nullptr;
6833 if (local_description()) {
6834 current_desc = local_description()->description();
6835 if (remote_description()) {
6836 secondary_current_desc = remote_description()->description();
6837 }
6838 } else if (remote_description()) {
6839 current_desc = remote_description()->description();
6840 }
Steve Anton75737c02017-11-06 10:37:17 -08006841 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006842 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6843 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006844 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6845 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006846 }
6847 }
6848
Steve Antonba42e992018-04-09 14:10:01 -07006849 if (IsUnifiedPlan()) {
6850 // Ensure that each audio and video media section has at most one
6851 // "StreamParams". This will return an error if receiving a session
6852 // description from a "Plan B" endpoint which adds multiple tracks of the
6853 // same type. With Unified Plan, there can only be at most one track per
6854 // media section.
6855 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006856 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006857 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6858 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6859 desc.streams().size() > 1u) {
6860 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6861 "Media section has more than one track specified "
6862 "with a=ssrc lines which is not supported with "
6863 "Unified Plan.");
6864 }
6865 }
6866 }
6867
Steve Anton8a006912017-12-04 15:25:56 -08006868 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006869}
6870
Steve Anton3828c062017-12-06 10:34:51 -08006871bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006872 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006873 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006874 return (state == PeerConnectionInterface::kStable) ||
6875 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006876 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006877 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006878 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6879 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6880 }
6881}
6882
Steve Anton3828c062017-12-06 10:34:51 -08006883bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006884 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006885 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006886 return (state == PeerConnectionInterface::kStable) ||
6887 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006888 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006889 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006890 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6891 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6892 }
6893}
6894
Steve Antonf8470812017-12-04 10:46:21 -08006895const char* PeerConnection::SessionErrorToString(SessionError error) const {
6896 switch (error) {
6897 case SessionError::kNone:
6898 return "ERROR_NONE";
6899 case SessionError::kContent:
6900 return "ERROR_CONTENT";
6901 case SessionError::kTransport:
6902 return "ERROR_TRANSPORT";
6903 }
6904 RTC_NOTREACHED();
6905 return "";
6906}
6907
Steve Anton75737c02017-11-06 10:37:17 -08006908std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006909 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006910 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6911 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006912 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006913}
6914
Steve Anton8e20f172018-03-06 10:55:04 -08006915void PeerConnection::ReportSdpFormatReceived(
6916 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006917 int num_audio_mlines = 0;
6918 int num_video_mlines = 0;
6919 int num_audio_tracks = 0;
6920 int num_video_tracks = 0;
6921 for (const ContentInfo& content : remote_offer.description()->contents()) {
6922 cricket::MediaType media_type = content.media_description()->type();
6923 int num_tracks = std::max(
6924 1, static_cast<int>(content.media_description()->streams().size()));
6925 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6926 num_audio_mlines += 1;
6927 num_audio_tracks += num_tracks;
6928 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6929 num_video_mlines += 1;
6930 num_video_tracks += num_tracks;
6931 }
6932 }
6933 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6934 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6935 format = kSdpFormatReceivedComplexUnifiedPlan;
6936 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6937 format = kSdpFormatReceivedComplexPlanB;
6938 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6939 format = kSdpFormatReceivedSimple;
6940 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006941 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6942 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006943}
6944
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006945void PeerConnection::ReportIceCandidateCollected(
6946 const cricket::Candidate& candidate) {
6947 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
6948 if (candidate.address().IsPrivateIP()) {
6949 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
6950 }
6951 if (candidate.address().IsUnresolvedIP()) {
6952 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
6953 }
6954 if (candidate.address().family() == AF_INET6) {
6955 NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
6956 }
6957}
6958
6959void PeerConnection::ReportRemoteIceCandidateAdded(
6960 const cricket::Candidate& candidate) {
6961 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
6962 if (candidate.address().IsPrivateIP()) {
6963 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
6964 }
6965 if (candidate.address().IsUnresolvedIP()) {
6966 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
6967 }
6968 if (candidate.address().family() == AF_INET6) {
6969 NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
6970 }
6971}
6972
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006973void PeerConnection::NoteUsageEvent(UsageEvent event) {
6974 RTC_DCHECK_RUN_ON(signaling_thread());
6975 usage_event_accumulator_ |= static_cast<int>(event);
6976}
6977
6978void PeerConnection::ReportUsagePattern() const {
6979 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006980 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6981 usage_event_accumulator_,
6982 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006983 const int bad_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006984 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006985 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6986 const int good_bits =
Qingsi Wang1ba5dec2019-08-19 11:57:17 -07006987 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006988 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6989 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6990 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6991 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006992 // If called after close(), we can't report, because observer may have
6993 // been deallocated, and therefore pointer is null. Write to log instead.
6994 if (observer_) {
6995 Observer()->OnInterestingUsage(usage_event_accumulator_);
6996 } else {
6997 RTC_LOG(LS_INFO) << "Interesting usage signature "
6998 << usage_event_accumulator_
6999 << " observed after observer shutdown";
7000 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02007001 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02007002}
7003
Steve Anton0ffaaa22018-02-23 10:31:30 -08007004void PeerConnection::ReportNegotiatedSdpSemantics(
7005 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007006 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007007 switch (answer.description()->msid_signaling()) {
7008 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007009 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007010 break;
7011 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007012 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007013 break;
7014 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007015 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007016 break;
7017 case cricket::kMsidSignalingMediaSection |
7018 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007019 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08007020 break;
7021 default:
7022 RTC_NOTREACHED();
7023 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007024 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
7025 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08007026}
7027
Steve Anton75737c02017-11-06 10:37:17 -08007028// We need to check the local/remote description for the Transport instead of
7029// the session, because a new Transport added during renegotiation may have
7030// them unset while the session has them set from the previous negotiation.
7031// Not doing so may trigger the auto generation of transport description and
7032// mess up DTLS identity information, ICE credential, etc.
7033bool PeerConnection::ReadyToUseRemoteCandidate(
7034 const IceCandidateInterface* candidate,
7035 const SessionDescriptionInterface* remote_desc,
7036 bool* valid) {
7037 *valid = true;
7038
7039 const SessionDescriptionInterface* current_remote_desc =
7040 remote_desc ? remote_desc : remote_description();
7041
7042 if (!current_remote_desc) {
7043 return false;
7044 }
7045
Guido Urdaneta41633172019-05-23 20:12:29 +02007046 RTCErrorOr<const cricket::ContentInfo*> result =
7047 FindContentInfo(current_remote_desc, candidate);
7048 if (!result.ok()) {
7049 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
7050 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08007051
7052 *valid = false;
7053 return false;
7054 }
7055
Guido Urdaneta41633172019-05-23 20:12:29 +02007056 std::string transport_name = GetTransportName(result.value()->name);
7057 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08007058}
7059
7060bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07007061 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07007062 (dtls_enabled_ ||
7063 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08007064}
7065
7066void PeerConnection::OnTransportControllerGatheringState(
7067 cricket::IceGatheringState state) {
7068 RTC_DCHECK(signaling_thread()->IsCurrent());
7069 if (state == cricket::kIceGatheringGathering) {
7070 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
7071 } else if (state == cricket::kIceGatheringComplete) {
7072 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
7073 }
7074}
7075
7076void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08007077 std::map<std::string, std::set<cricket::MediaType>>
7078 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007079 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007080 if (transceiver->internal()->channel()) {
7081 const std::string& transport_name =
7082 transceiver->internal()->channel()->transport_name();
7083 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007084 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007085 }
Steve Anton75737c02017-11-06 10:37:17 -08007086 }
7087 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007088 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7089 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007090 }
Zhi Huange830e682018-03-30 10:48:35 -07007091
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007092 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007093 if (transport_name) {
7094 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007095 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007096 }
Zhi Huange830e682018-03-30 10:48:35 -07007097
Steve Antonc7b964c2018-02-01 14:39:45 -08007098 for (const auto& entry : media_types_by_transport_name) {
7099 const std::string& transport_name = entry.first;
7100 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007101 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007102 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007103 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007104 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007105 }
7106 }
7107}
7108// Walk through the ConnectionInfos to gather best connection usage
7109// for IPv4 and IPv6.
7110void PeerConnection::ReportBestConnectionState(
7111 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007112 for (const cricket::TransportChannelStats& channel_stats :
7113 stats.channel_stats) {
7114 for (const cricket::ConnectionInfo& connection_info :
7115 channel_stats.connection_infos) {
7116 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007117 continue;
7118 }
7119
Steve Antonc7b964c2018-02-01 14:39:45 -08007120 const cricket::Candidate& local = connection_info.local_candidate;
7121 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007122
7123 // Increment the counter for IceCandidatePairType.
7124 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7125 (local.type() == RELAY_PORT_TYPE &&
7126 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007127 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7128 GetIceCandidatePairCounter(local, remote),
7129 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007130 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007131 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7132 GetIceCandidatePairCounter(local, remote),
7133 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007134 } else {
7135 RTC_CHECK(0);
7136 }
Steve Anton75737c02017-11-06 10:37:17 -08007137
7138 // Increment the counter for IP type.
7139 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007140 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7141 kBestConnections_IPv4,
7142 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007143 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007144 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7145 kBestConnections_IPv6,
7146 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007147 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007148 RTC_CHECK(!local.address().hostname().empty() &&
7149 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007150 }
7151
7152 return;
7153 }
7154 }
7155}
7156
7157void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007158 const cricket::TransportStats& stats,
7159 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007160 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7161 return;
7162 }
7163
7164 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7165 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7166 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7167 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7168 return;
7169 }
7170
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007171 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7172 for (cricket::MediaType media_type : media_types) {
7173 switch (media_type) {
7174 case cricket::MEDIA_TYPE_AUDIO:
7175 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7176 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7177 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7178 break;
7179 case cricket::MEDIA_TYPE_VIDEO:
7180 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7181 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7182 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7183 break;
7184 case cricket::MEDIA_TYPE_DATA:
7185 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7186 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7187 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7188 break;
7189 default:
7190 RTC_NOTREACHED();
7191 continue;
7192 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007193 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007194 }
7195
7196 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7197 for (cricket::MediaType media_type : media_types) {
7198 switch (media_type) {
7199 case cricket::MEDIA_TYPE_AUDIO:
7200 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7201 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7202 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7203 break;
7204 case cricket::MEDIA_TYPE_VIDEO:
7205 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7206 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7207 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7208 break;
7209 case cricket::MEDIA_TYPE_DATA:
7210 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7211 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7212 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7213 break;
7214 default:
7215 RTC_NOTREACHED();
7216 continue;
7217 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007218 }
Steve Anton75737c02017-11-06 10:37:17 -08007219 }
7220}
7221
7222void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007223 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007224 RTC_DCHECK(call_);
7225 call_->OnSentPacket(sent_packet);
7226}
7227
7228const std::string PeerConnection::GetTransportName(
7229 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007230 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007231 if (channel) {
7232 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007233 }
Steve Anton6fec8802017-12-04 10:37:29 -08007234 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007235 RTC_DCHECK(sctp_mid_);
7236 if (content_name == *sctp_mid_) {
7237 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007238 }
7239 }
7240 // Return an empty string if failed to retrieve the transport name.
7241 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007242}
7243
Steve Anton6fec8802017-12-04 10:37:29 -08007244void PeerConnection::DestroyTransceiverChannel(
7245 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7246 transceiver) {
7247 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007248
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007249 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007250 if (channel) {
7251 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007252 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007253 }
7254}
7255
7256void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007257 if (rtp_data_channel_) {
7258 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007259 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007260 rtp_data_channel_ = nullptr;
7261 }
7262
7263 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7264 // grab a reference to this PeerConnection. If this is called from the
7265 // PeerConnection destructor, the RefCountedObject vtable will have already
7266 // been destroyed (since it is a subclass of PeerConnection) and using
7267 // rtc::Bind will cause "Pure virtual function called" error to appear.
7268
7269 if (sctp_transport_) {
7270 OnDataChannelDestroyed();
7271 network_thread()->Invoke<void>(RTC_FROM_HERE,
7272 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007273 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007274 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007275
7276 if (media_transport_) {
7277 OnDataChannelDestroyed();
7278 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7279 RTC_DCHECK_RUN_ON(network_thread());
7280 TeardownMediaTransportForDataChannels_n();
7281 });
7282 }
Steve Anton6fec8802017-12-04 10:37:29 -08007283}
7284
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007285void PeerConnection::DestroyChannelInterface(
7286 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007287 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007288 switch (channel->media_type()) {
7289 case cricket::MEDIA_TYPE_AUDIO:
7290 channel_manager()->DestroyVoiceChannel(
7291 static_cast<cricket::VoiceChannel*>(channel));
7292 break;
7293 case cricket::MEDIA_TYPE_VIDEO:
7294 channel_manager()->DestroyVideoChannel(
7295 static_cast<cricket::VideoChannel*>(channel));
7296 break;
7297 case cricket::MEDIA_TYPE_DATA:
7298 channel_manager()->DestroyRtpDataChannel(
7299 static_cast<cricket::RtpDataChannel*>(channel));
7300 break;
7301 default:
7302 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7303 break;
7304 }
Zhi Huange830e682018-03-30 10:48:35 -07007305}
Steve Anton6fec8802017-12-04 10:37:29 -08007306
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007307bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007308 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007309 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007310 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007311 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007312 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007313 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007314 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007315 auto base_channel = GetChannel(mid);
7316 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007317 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007318 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007319 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007320 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007321 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007322
Karl Wiberg5966c502019-02-21 23:55:09 +01007323 if (use_media_transport_) {
Tommi78a71382019-08-08 12:27:53 +02007324 RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007325 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007326
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007327 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007328}
7329
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007330void PeerConnection::OnSetStreams() {
7331 RTC_DCHECK_RUN_ON(signaling_thread());
7332 if (IsUnifiedPlan())
7333 UpdateNegotiationNeeded();
7334}
7335
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007336PeerConnectionObserver* PeerConnection::Observer() const {
7337 // In earlier production code, the pointer was not cleared on close,
7338 // which might have led to undefined behavior if the observer was not
7339 // deallocated, or strange crashes if it was.
7340 // We use CHECK in order to catch such behavior if it exists.
7341 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7342 RTC_CHECK(observer_);
7343 return observer_;
7344}
7345
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007346CryptoOptions PeerConnection::GetCryptoOptions() {
7347 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7348 // after it has been removed.
7349 return configuration_.crypto_options.has_value()
7350 ? *configuration_.crypto_options
7351 : factory_->options().crypto_options;
7352}
7353
Harald Alvestrand89061872018-01-02 14:08:34 +01007354void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007355 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007356 if (stats_collector_) {
7357 stats_collector_->ClearCachedStatsReport();
7358 }
7359}
7360
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007361void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007362 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7363 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007364}
7365
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007366void PeerConnection::UpdateNegotiationNeeded() {
7367 RTC_DCHECK_RUN_ON(signaling_thread());
7368 if (!IsUnifiedPlan()) {
7369 Observer()->OnRenegotiationNeeded();
7370 return;
7371 }
7372
7373 // If connection's [[IsClosed]] slot is true, abort these steps.
7374 if (IsClosed())
7375 return;
7376
7377 // If connection's signaling state is not "stable", abort these steps.
7378 if (signaling_state() != kStable)
7379 return;
7380
7381 // NOTE
7382 // The negotiation-needed flag will be updated once the state transitions to
7383 // "stable", as part of the steps for setting an RTCSessionDescription.
7384
7385 // If the result of checking if negotiation is needed is false, clear the
7386 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7387 // to false, and abort these steps.
7388 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7389 if (!is_negotiation_needed) {
7390 is_negotiation_needed_ = false;
7391 return;
7392 }
7393
7394 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7395 // steps.
7396 if (is_negotiation_needed_)
7397 return;
7398
7399 // Set connection's [[NegotiationNeeded]] slot to true.
7400 is_negotiation_needed_ = true;
7401
7402 // Queue a task that runs the following steps:
7403 // If connection's [[IsClosed]] slot is true, abort these steps.
7404 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7405 // Fire an event named negotiationneeded at connection.
7406 Observer()->OnRenegotiationNeeded();
7407}
7408
7409bool PeerConnection::CheckIfNegotiationIsNeeded() {
7410 RTC_DCHECK_RUN_ON(signaling_thread());
7411 // 1. If any implementation-specific negotiation is required, as described at
7412 // the start of this section, return true.
7413
Henrik Boström79b69802019-07-18 11:16:56 +02007414 // 2. If connection's [[RestartIce]] internal slot is true, return true.
7415 if (local_ice_credentials_to_replace_->HasIceCredentials()) {
7416 return true;
7417 }
7418
7419 // 3. Let description be connection.[[CurrentLocalDescription]].
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007420 const SessionDescriptionInterface* description = current_local_description();
7421 if (!description)
7422 return true;
7423
Henrik Boström79b69802019-07-18 11:16:56 +02007424 // 4. If connection has created any RTCDataChannels, and no m= section in
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007425 // description has been negotiated yet for data, return true.
7426 if (!sctp_data_channels_.empty()) {
7427 if (!cricket::GetFirstDataContent(description->description()->contents()))
7428 return true;
7429 }
7430
Henrik Boström79b69802019-07-18 11:16:56 +02007431 // 5. For each transceiver in connection's set of transceivers, perform the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007432 // following checks:
7433 for (const auto& transceiver : transceivers_) {
7434 const ContentInfo* current_local_msection =
7435 FindTransceiverMSection(transceiver.get(), description);
7436
7437 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7438 transceiver.get(), current_remote_description());
7439
Henrik Boström79b69802019-07-18 11:16:56 +02007440 // 5.3 If transceiver is stopped and is associated with an m= section,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007441 // but the associated m= section is not yet rejected in
7442 // connection.[[CurrentLocalDescription]] or
7443 // connection.[[CurrentRemoteDescription]], return true.
7444 if (transceiver->stopped()) {
7445 if (current_local_msection && !current_local_msection->rejected &&
7446 ((current_remote_msection && !current_remote_msection->rejected) ||
7447 !current_remote_msection)) {
7448 return true;
7449 }
7450 continue;
7451 }
7452
Henrik Boström79b69802019-07-18 11:16:56 +02007453 // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007454 // section in description, return true.
7455 if (!current_local_msection)
7456 return true;
7457
7458 const MediaContentDescription* current_local_media_description =
7459 current_local_msection->media_description();
Henrik Boström79b69802019-07-18 11:16:56 +02007460 // 5.2 If transceiver isn't stopped and is associated with an m= section
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007461 // in description then perform the following checks:
7462
Henrik Boström79b69802019-07-18 11:16:56 +02007463 // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007464 // associated m= section in description either doesn't contain a single
7465 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7466 // m= section, or the MSID values themselves, differ from what is in
7467 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7468 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7469 if (current_local_media_description->streams().size() == 0)
7470 return true;
7471
7472 std::vector<std::string> msection_msids;
7473 for (const auto& stream : current_local_media_description->streams()) {
7474 for (const std::string& msid : stream.stream_ids())
7475 msection_msids.push_back(msid);
7476 }
7477
7478 std::vector<std::string> transceiver_msids =
7479 transceiver->sender()->stream_ids();
7480 if (msection_msids.size() != transceiver_msids.size())
7481 return true;
7482
7483 absl::c_sort(transceiver_msids);
7484 absl::c_sort(msection_msids);
7485 if (transceiver_msids != msection_msids)
7486 return true;
7487 }
7488
Henrik Boström79b69802019-07-18 11:16:56 +02007489 // 5.2.2 If description is of type "offer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007490 // associated m= section in neither connection.[[CurrentLocalDescription]]
7491 // nor connection.[[CurrentRemoteDescription]] matches
7492 // transceiver.[[Direction]], return true.
7493 if (description->GetType() == SdpType::kOffer) {
7494 if (!current_remote_description())
7495 return true;
7496
7497 if (!current_remote_msection)
7498 return true;
7499
7500 RtpTransceiverDirection current_local_direction =
7501 current_local_media_description->direction();
7502 RtpTransceiverDirection current_remote_direction =
7503 current_remote_msection->media_description()->direction();
7504 if (transceiver->direction() != current_local_direction &&
7505 transceiver->direction() !=
7506 RtpTransceiverDirectionReversed(current_remote_direction)) {
7507 return true;
7508 }
7509 }
7510
Henrik Boström79b69802019-07-18 11:16:56 +02007511 // 5.2.3 If description is of type "answer", and the direction of the
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007512 // associated m= section in the description does not match
7513 // transceiver.[[Direction]] intersected with the offered direction (as
7514 // described in [JSEP] (section 5.3.1.)), return true.
7515 if (description->GetType() == SdpType::kAnswer) {
7516 if (!remote_description())
7517 return true;
7518
7519 const ContentInfo* offered_remote_msection =
7520 FindTransceiverMSection(transceiver.get(), remote_description());
7521
7522 RtpTransceiverDirection offered_direction =
7523 offered_remote_msection
7524 ? offered_remote_msection->media_description()->direction()
7525 : RtpTransceiverDirection::kInactive;
7526
7527 if (current_local_media_description->direction() !=
7528 (RtpTransceiverDirectionIntersection(
7529 transceiver->direction(),
7530 RtpTransceiverDirectionReversed(offered_direction)))) {
7531 return true;
7532 }
7533 }
7534 }
7535
7536 // If all the preceding checks were performed and true was not returned,
7537 // nothing remains to be negotiated; return false.
7538 return false;
7539}
7540
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007541} // namespace webrtc