blob: 7ea9f5085285d23bd8bc1d9b26a1b9fa18f19862 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070027#include "api/rtc_error.h"
Niels Möllerd8b9ed72019-05-08 13:53:51 +020028#include "api/rtc_event_log_output_file.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070029#include "api/rtp_parameters.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/uma_metrics.h"
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +020031#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "logging/rtc_event_log/ice_logger.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "logging/rtc_event_log/rtc_event_log.h"
Amit Hilbuchf4770402019-04-08 14:11:57 -070035#include "media/base/rid_description.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010037#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "pc/channel_manager.h"
41#include "pc/dtmf_sender.h"
42#include "pc/media_stream.h"
43#include "pc/media_stream_observer.h"
44#include "pc/remote_audio_source.h"
45#include "pc/rtp_media_utils.h"
46#include "pc/rtp_receiver.h"
47#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010048#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/sctp_utils.h"
50#include "pc/sdp_utils.h"
51#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010052#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080053#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/bind.h"
55#include "rtc_base/checks.h"
56#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080057#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020058#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/trace_event.h"
60#include "system_wrappers/include/clock.h"
61#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070062#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::ContentInfo;
65using cricket::ContentInfos;
66using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080067using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::RidDescription;
69using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::SimulcastDescription;
72using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080073using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080074using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080075using cricket::TransportInfo;
76
77using cricket::LOCAL_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080078using cricket::PRFLX_PORT_TYPE;
Jeroen de Borstaf242c82019-04-24 13:13:48 -070079using cricket::RELAY_PORT_TYPE;
80using cricket::STUN_PORT_TYPE;
Steve Anton75737c02017-11-06 10:37:17 -080081
Steve Antonba818672017-11-06 10:21:57 -080082namespace webrtc {
83
Steve Anton75737c02017-11-06 10:37:17 -080084// Error messages
85const char kBundleWithoutRtcpMux[] =
86 "rtcp-mux must be enabled when BUNDLE "
87 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080088const char kInvalidCandidates[] = "Description contains invalid candidates.";
89const char kInvalidSdp[] = "Invalid session description.";
90const char kMlineMismatchInAnswer[] =
91 "The order of m-lines in answer doesn't match order in offer. Rejecting "
92 "answer.";
93const char kMlineMismatchInSubsequentOffer[] =
94 "The order of m-lines in subsequent offer doesn't match order from "
95 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080096const char kSdpWithoutDtlsFingerprint[] =
97 "Called with SDP without DTLS fingerprint.";
98const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
99const char kSdpWithoutIceUfragPwd[] =
100 "Called with SDP without ice-ufrag and ice-pwd.";
101const char kSessionError[] = "Session error code: ";
102const char kSessionErrorDesc[] = "Session error description: ";
103const char kDtlsSrtpSetupFailureRtp[] =
104 "Couldn't set up DTLS-SRTP on RTP channel.";
105const char kDtlsSrtpSetupFailureRtcp[] =
106 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
Steve Anton75737c02017-11-06 10:37:17 -0800108namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700110// Field trials.
111// Controls datagram transport support.
112const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
113
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800114// UMA metric names.
115const char kSimulcastVersionApplyLocalDescription[] =
116 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
117const char kSimulcastVersionApplyRemoteDescription[] =
118 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
119const char kSimulcastNumberOfEncodings[] =
120 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
121const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
122
Seth Hampson845e8782018-03-02 11:34:10 -0800123static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800124static const char kDefaultAudioSenderId[] = "defaulta0";
125static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700126
zhihuang8f65cdf2016-05-06 18:40:30 -0700127// The length of RTCP CNAMEs.
128static const int kRtcpCnameLength = 16;
129
Steve Antonad182762018-09-05 20:22:40 +0000130enum {
131 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
132 MSG_SET_SESSIONDESCRIPTION_FAILED,
133 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
134 MSG_GETSTATS,
135 MSG_FREE_DATACHANNELS,
136 MSG_REPORT_USAGE_PATTERN,
137};
138
Harald Alvestrand19793842018-06-25 12:03:50 +0200139static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
140
Steve Antonad182762018-09-05 20:22:40 +0000141struct SetSessionDescriptionMsg : public rtc::MessageData {
142 explicit SetSessionDescriptionMsg(
143 webrtc::SetSessionDescriptionObserver* observer)
144 : observer(observer) {}
145
146 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
147 RTCError error;
148};
149
150struct CreateSessionDescriptionMsg : public rtc::MessageData {
151 explicit CreateSessionDescriptionMsg(
152 webrtc::CreateSessionDescriptionObserver* observer)
153 : observer(observer) {}
154
155 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
156 RTCError error;
157};
158
159struct GetStatsMsg : public rtc::MessageData {
160 GetStatsMsg(webrtc::StatsObserver* observer,
161 webrtc::MediaStreamTrackInterface* track)
162 : observer(observer), track(track) {}
163 rtc::scoped_refptr<webrtc::StatsObserver> observer;
164 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
165};
166
deadbeefab9b2d12015-10-14 11:33:11 -0700167// Check if we can send |new_stream| on a PeerConnection.
168bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
169 webrtc::MediaStreamInterface* new_stream) {
170 if (!new_stream || !current_streams) {
171 return false;
172 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700173 if (current_streams->find(new_stream->id()) != nullptr) {
174 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100175 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700176 return false;
177 }
178 return true;
179}
180
deadbeef5e97fb52015-10-15 12:49:08 -0700181// If the direction is "recvonly" or "inactive", treat the description
182// as containing no streams.
183// See: https://code.google.com/p/webrtc/issues/detail?id=5054
184std::vector<cricket::StreamParams> GetActiveStreams(
185 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800186 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700187 ? desc->streams()
188 : std::vector<cricket::StreamParams>();
189}
190
deadbeefab9b2d12015-10-14 11:33:11 -0700191bool IsValidOfferToReceiveMedia(int value) {
192 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
193 return (value >= Options::kUndefined) &&
194 (value <= Options::kMaxOfferToReceiveMedia);
195}
196
zhihuang1c378ed2017-08-17 14:10:50 -0700197// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800198void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700199 const std::vector<rtc::scoped_refptr<
200 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700201 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200202 cricket::MediaDescriptionOptions* video_media_description_options,
203 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700204 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
206 if (audio_media_description_options) {
207 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700208 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700209 }
210 } else {
211 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
212 if (video_media_description_options) {
213 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800214 sender->id(), sender->internal()->stream_ids(), {},
215 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700216 }
217 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700218 }
zhihuang1c378ed2017-08-17 14:10:50 -0700219}
olka3c747662017-08-17 06:50:32 -0700220
zhihuang1c378ed2017-08-17 14:10:50 -0700221// Add options to |session_options| from |rtp_data_channels|.
222void AddRtpDataChannelOptions(
223 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
224 rtp_data_channels,
225 cricket::MediaDescriptionOptions* data_media_description_options) {
226 if (!data_media_description_options) {
227 return;
228 }
deadbeefab9b2d12015-10-14 11:33:11 -0700229 // Check for data channels.
230 for (const auto& kv : rtp_data_channels) {
231 const DataChannel* channel = kv.second;
232 if (channel->state() == DataChannel::kConnecting ||
233 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700234 // Legacy RTP data channels are signaled with the track/stream ID set to
235 // the data channel's label.
236 data_media_description_options->AddRtpDataChannel(channel->label(),
237 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700238 }
239 }
240}
241
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700242uint32_t ConvertIceTransportTypeToCandidateFilter(
243 PeerConnectionInterface::IceTransportsType type) {
244 switch (type) {
245 case PeerConnectionInterface::kNone:
246 return cricket::CF_NONE;
247 case PeerConnectionInterface::kRelay:
248 return cricket::CF_RELAY;
249 case PeerConnectionInterface::kNoHost:
250 return (cricket::CF_ALL & ~cricket::CF_HOST);
251 case PeerConnectionInterface::kAll:
252 return cricket::CF_ALL;
253 default:
nissec80e7412017-01-11 05:56:46 -0800254 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700255 }
256 return cricket::CF_NONE;
257}
258
deadbeef293e9262017-01-11 12:28:30 -0800259// Helper to set an error and return from a method.
260bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
261 if (error) {
262 error->set_type(type);
263 }
264 return type == webrtc::RTCErrorType::NONE;
265}
266
Steve Anton038834f2017-07-14 15:59:59 -0700267bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700268 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700269 if (error_out) {
270 *error_out = std::move(error);
271 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700272 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700273}
274
Steve Antonba818672017-11-06 10:21:57 -0800275std::string GetSignalingStateString(
276 PeerConnectionInterface::SignalingState state) {
277 switch (state) {
278 case PeerConnectionInterface::kStable:
279 return "kStable";
280 case PeerConnectionInterface::kHaveLocalOffer:
281 return "kHaveLocalOffer";
282 case PeerConnectionInterface::kHaveLocalPrAnswer:
283 return "kHavePrAnswer";
284 case PeerConnectionInterface::kHaveRemoteOffer:
285 return "kHaveRemoteOffer";
286 case PeerConnectionInterface::kHaveRemotePrAnswer:
287 return "kHaveRemotePrAnswer";
288 case PeerConnectionInterface::kClosed:
289 return "kClosed";
290 }
291 RTC_NOTREACHED();
292 return "";
293}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700294
Steve Anton75737c02017-11-06 10:37:17 -0800295IceCandidatePairType GetIceCandidatePairCounter(
296 const cricket::Candidate& local,
297 const cricket::Candidate& remote) {
298 const auto& l = local.type();
299 const auto& r = remote.type();
300 const auto& host = LOCAL_PORT_TYPE;
301 const auto& srflx = STUN_PORT_TYPE;
302 const auto& relay = RELAY_PORT_TYPE;
303 const auto& prflx = PRFLX_PORT_TYPE;
304 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800305 bool local_hostname =
306 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
307 bool remote_hostname = !remote.address().hostname().empty() &&
308 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800309 bool local_private = IPIsPrivate(local.address().ipaddr());
310 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800311 if (local_hostname) {
312 if (remote_hostname) {
313 return kIceCandidatePairHostNameHostName;
314 } else if (remote_private) {
315 return kIceCandidatePairHostNameHostPrivate;
316 } else {
317 return kIceCandidatePairHostNameHostPublic;
318 }
319 } else if (local_private) {
320 if (remote_hostname) {
321 return kIceCandidatePairHostPrivateHostName;
322 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800323 return kIceCandidatePairHostPrivateHostPrivate;
324 } else {
325 return kIceCandidatePairHostPrivateHostPublic;
326 }
327 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800328 if (remote_hostname) {
329 return kIceCandidatePairHostPublicHostName;
330 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800331 return kIceCandidatePairHostPublicHostPrivate;
332 } else {
333 return kIceCandidatePairHostPublicHostPublic;
334 }
335 }
336 }
337 if (l == host && r == srflx)
338 return kIceCandidatePairHostSrflx;
339 if (l == host && r == relay)
340 return kIceCandidatePairHostRelay;
341 if (l == host && r == prflx)
342 return kIceCandidatePairHostPrflx;
343 if (l == srflx && r == host)
344 return kIceCandidatePairSrflxHost;
345 if (l == srflx && r == srflx)
346 return kIceCandidatePairSrflxSrflx;
347 if (l == srflx && r == relay)
348 return kIceCandidatePairSrflxRelay;
349 if (l == srflx && r == prflx)
350 return kIceCandidatePairSrflxPrflx;
351 if (l == relay && r == host)
352 return kIceCandidatePairRelayHost;
353 if (l == relay && r == srflx)
354 return kIceCandidatePairRelaySrflx;
355 if (l == relay && r == relay)
356 return kIceCandidatePairRelayRelay;
357 if (l == relay && r == prflx)
358 return kIceCandidatePairRelayPrflx;
359 if (l == prflx && r == host)
360 return kIceCandidatePairPrflxHost;
361 if (l == prflx && r == srflx)
362 return kIceCandidatePairPrflxSrflx;
363 if (l == prflx && r == relay)
364 return kIceCandidatePairPrflxRelay;
365 return kIceCandidatePairMax;
366}
367
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368// Logic to decide if an m= section can be recycled. This means that the new
369// m= section is not rejected, but the old local or remote m= section is
370// rejected. |old_content_one| and |old_content_two| refer to the m= section
371// of the old remote and old local descriptions in no particular order.
372// We need to check both the old local and remote because either
373// could be the most current from the latest negotation.
374bool IsMediaSectionBeingRecycled(SdpType type,
375 const ContentInfo& content,
376 const ContentInfo* old_content_one,
377 const ContentInfo* old_content_two) {
378 return type == SdpType::kOffer && !content.rejected &&
379 ((old_content_one && old_content_one->rejected) ||
380 (old_content_two && old_content_two->rejected));
381}
382
Steve Anton75737c02017-11-06 10:37:17 -0800383// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800384// |current_desc|. The number of m= sections in |new_desc| should be no
385// less than |current_desc|. In the case of checking an answer's
386// |new_desc|, the |current_desc| is the last offer that was set as the
387// local or remote. In the case of checking an offer's |new_desc| we
388// check against the local and remote descriptions stored from the last
389// negotiation, because either of these could be the most up to date for
390// possible rejected m sections. These are the |current_desc| and
391// |secondary_current_desc|.
392bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
393 const SessionDescription* secondary_current_desc,
394 const SessionDescription& new_desc,
395 const SdpType type) {
396 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800400 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
401 const cricket::ContentInfo* secondary_content_info = nullptr;
402 if (secondary_current_desc &&
403 i < secondary_current_desc->contents().size()) {
404 secondary_content_info = &secondary_current_desc->contents()[i];
405 }
406 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
407 &current_desc.contents()[i],
408 secondary_content_info)) {
409 // For new offer descriptions, if the media section can be recycled, it's
410 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800411 continue;
412 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800413 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800414 return false;
415 }
416 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800417 new_desc.contents()[i].media_description();
418 const MediaContentDescription* current_desc_mdesc =
419 current_desc.contents()[i].media_description();
420 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800421 return false;
422 }
423 }
424 return true;
425}
426
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800427bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
428 const SessionDescription& desc2) {
429 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800430}
431
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700432void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
433 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200434 // Array of structs needed to map {KeyExchangeProtocolType,
435 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
436 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
437 static constexpr struct {
438 KeyExchangeProtocolType protocol_type;
439 cricket::MediaType media_type;
440 KeyExchangeProtocolMedia protocol_media;
441 } kEnumCounterKeyProtocolMediaMap[] = {
442 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
443 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
444 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
445 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
446 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
447 kEnumCounterKeyProtocolMediaTypeDtlsData},
448 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
449 kEnumCounterKeyProtocolMediaTypeSdesAudio},
450 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
451 kEnumCounterKeyProtocolMediaTypeSdesVideo},
452 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
453 kEnumCounterKeyProtocolMediaTypeSdesData},
454 };
455
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700456 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
457 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100458
Mirko Bonadeiab499822018-09-11 10:43:20 +0200459 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
460 if (i.protocol_type == protocol_type && i.media_type == media_type) {
461 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
462 i.protocol_media,
463 kEnumCounterKeyProtocolMediaTypeMax);
464 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100465 }
466}
467
Harald Alvestrand76829d72018-07-18 23:24:36 +0200468void NoteAddIceCandidateResult(int result) {
469 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
470 kAddIceCandidateMax);
471}
472
Steve Anton75737c02017-11-06 10:37:17 -0800473// Checks that each non-rejected content has SDES crypto keys or a DTLS
474// fingerprint, unless it's in a BUNDLE group, in which case only the
475// BUNDLE-tag section (first media section/description in the BUNDLE group)
476// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
477// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
478// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700479RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 const cricket::ContentGroup* bundle =
481 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800482 for (const cricket::ContentInfo& content_info : desc->contents()) {
483 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800484 continue;
485 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100486 // Note what media is used with each crypto protocol, for all sections.
487 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
488 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700489 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800490 const std::string& mid = content_info.name;
491 if (bundle && bundle->HasContentName(mid) &&
492 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 // This isn't the first media section in the BUNDLE group, so it's not
494 // required to have crypto attributes, since only the crypto attributes
495 // from the first section actually get used.
496 continue;
497 }
498
499 // If the content isn't rejected or bundled into another m= section, crypto
500 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800501 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800502 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800503 if (!media || !tinfo) {
504 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800506 }
507 if (dtls_enabled) {
508 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_WARNING)
510 << "Session description must have DTLS fingerprint if "
511 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800512 return RTCError(RTCErrorType::INVALID_PARAMETER,
513 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800514 }
515 } else {
516 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100517 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800518 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800519 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800520 }
521 }
522 }
Steve Anton8a006912017-12-04 15:25:56 -0800523 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800524}
525
526// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
527// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
528// media section/description in the BUNDLE group) needs a ufrag and pwd.
529bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
530 const cricket::ContentGroup* bundle =
531 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800532 for (const cricket::ContentInfo& content_info : desc->contents()) {
533 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800534 continue;
535 }
Steve Anton8a006912017-12-04 15:25:56 -0800536 const std::string& mid = content_info.name;
537 if (bundle && bundle->HasContentName(mid) &&
538 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800539 // This isn't the first media section in the BUNDLE group, so it's not
540 // required to have ufrag/password, since only the ufrag/password from
541 // the first section actually get used.
542 continue;
543 }
544
545 // If the content isn't rejected or bundled into another m= section,
546 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800547 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800548 if (!tinfo) {
549 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100550 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800551 return false;
552 }
553 if (tinfo->description.ice_ufrag.empty() ||
554 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100555 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800556 return false;
557 }
558 }
559 return true;
560}
561
Steve Anton75737c02017-11-06 10:37:17 -0800562// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
563bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
564 const SessionDescriptionInterface* new_desc,
565 const std::string& content_name) {
566 if (!old_desc) {
567 return false;
568 }
569 const SessionDescription* new_sd = new_desc->description();
570 const SessionDescription* old_sd = old_desc->description();
571 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
572 if (!cinfo || cinfo->rejected) {
573 return false;
574 }
575 // If the content isn't rejected, check if ufrag and password has changed.
576 const cricket::TransportDescription* new_transport_desc =
577 new_sd->GetTransportDescriptionByName(content_name);
578 const cricket::TransportDescription* old_transport_desc =
579 old_sd->GetTransportDescriptionByName(content_name);
580 if (!new_transport_desc || !old_transport_desc) {
581 // No transport description exists. This is not an ICE restart.
582 return false;
583 }
584 if (cricket::IceCredentialsChanged(
585 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
586 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100587 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
588 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800589 return true;
590 }
591 return false;
592}
593
Steve Anton80dd7b52018-02-16 17:08:42 -0800594// Generates a string error message for SetLocalDescription/SetRemoteDescription
595// from an RTCError.
596std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
597 SdpType type,
598 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200599 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800600 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
601 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200602 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800603}
604
Seth Hampson5b4f0752018-04-02 16:31:36 -0700605std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
606 std::string output = "streams=[";
607 const char* separator = "";
608 for (const auto& stream_id : stream_ids) {
609 output.append(separator).append(stream_id);
610 separator = ", ";
611 }
612 output.append("]");
613 return output;
614}
615
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 int rtc_configuration_parameter) {
618 if (rtc_configuration_parameter ==
619 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200620 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700621 }
622 return rtc_configuration_parameter;
623}
624
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800625cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
626 switch (type) {
627 case DataMessageType::kText:
628 return cricket::DMT_TEXT;
629 case DataMessageType::kBinary:
630 return cricket::DMT_BINARY;
631 case DataMessageType::kControl:
632 return cricket::DMT_CONTROL;
633 default:
634 return cricket::DMT_NONE;
635 }
636 return cricket::DMT_NONE;
637}
638
639DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
640 switch (type) {
641 case cricket::DMT_TEXT:
642 return DataMessageType::kText;
643 case cricket::DMT_BINARY:
644 return DataMessageType::kBinary;
645 case cricket::DMT_CONTROL:
646 return DataMessageType::kControl;
647 case cricket::DMT_NONE:
648 default:
649 RTC_NOTREACHED();
650 }
651 return DataMessageType::kControl;
652}
653
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800654void ReportSimulcastApiVersion(const char* name,
655 const SessionDescription& session) {
656 bool has_legacy = false;
657 bool has_spec_compliant = false;
658 for (const ContentInfo& content : session.contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +0200659 if (!content.media_description()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800660 continue;
661 }
Harald Alvestrand1716d392019-06-03 20:35:45 +0200662 has_spec_compliant |= content.media_description()->HasSimulcast();
663 for (const StreamParams& sp : content.media_description()->streams()) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800664 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
665 }
666 }
667
668 if (has_legacy) {
669 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
670 kSimulcastApiVersionMax);
671 }
672 if (has_spec_compliant) {
673 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
674 kSimulcastApiVersionMax);
675 }
676 if (!has_legacy && !has_spec_compliant) {
677 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
678 kSimulcastApiVersionMax);
679 }
680}
681
Guido Urdaneta70c2db12019-04-16 12:24:14 +0200682const ContentInfo* FindTransceiverMSection(
683 RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
684 const SessionDescriptionInterface* session_description) {
685 return transceiver->mid()
686 ? session_description->description()->GetContentByName(
687 *transceiver->mid())
688 : nullptr;
689}
690
Steve Anton75737c02017-11-06 10:37:17 -0800691} // namespace
692
Henrik Boström31638672017-11-23 17:48:32 +0100693// Upon completion, posts a task to execute the callback of the
694// SetSessionDescriptionObserver asynchronously on the same thread. At this
695// point, the state of the peer connection might no longer reflect the effects
696// of the SetRemoteDescription operation, as the peer connection could have been
697// modified during the post.
698// TODO(hbos): Remove this class once we remove the version of
699// PeerConnectionInterface::SetRemoteDescription() that takes a
700// SetSessionDescriptionObserver as an argument.
701class PeerConnection::SetRemoteDescriptionObserverAdapter
702 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
703 public:
704 SetRemoteDescriptionObserverAdapter(
705 rtc::scoped_refptr<PeerConnection> pc,
706 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
707 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
708
709 // SetRemoteDescriptionObserverInterface implementation.
710 void OnSetRemoteDescriptionComplete(RTCError error) override {
711 if (error.ok())
712 pc_->PostSetSessionDescriptionSuccess(wrapper_);
713 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100714 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100715 }
716
717 private:
718 rtc::scoped_refptr<PeerConnection> pc_;
719 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
720};
721
deadbeef293e9262017-01-11 12:28:30 -0800722bool PeerConnectionInterface::RTCConfiguration::operator==(
723 const PeerConnectionInterface::RTCConfiguration& o) const {
724 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700725 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800726 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000727 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700728 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800729 BundlePolicy bundle_policy;
730 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700731 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
732 int ice_candidate_pool_size;
733 bool disable_ipv6;
734 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700735 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100736 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700737 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200738 absl::optional<int> screencast_min_bitrate;
739 absl::optional<bool> combined_audio_video_bwe;
740 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800741 TcpCandidatePolicy tcp_candidate_policy;
742 CandidateNetworkPolicy candidate_network_policy;
743 int audio_jitter_buffer_max_packets;
744 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100745 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100746 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800747 int ice_connection_receiving_timeout;
748 int ice_backup_candidate_pair_ping_interval;
749 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800750 bool prioritize_most_likely_ice_candidate_pairs;
751 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800752 bool prune_turn_ports;
753 bool presume_writable_when_fully_relayed;
754 bool enable_ice_renomination;
755 bool redetermine_role_on_ice_restart;
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700756 bool surface_ice_candidates_on_ice_transport_type_changed;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200757 absl::optional<int> ice_check_interval_strong_connectivity;
758 absl::optional<int> ice_check_interval_weak_connectivity;
759 absl::optional<int> ice_check_min_interval;
760 absl::optional<int> ice_unwritable_timeout;
761 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800762 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<int> stun_candidate_keepalive_interval;
764 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200765 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800766 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200767 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700768 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700769 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700770 bool use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700771 absl::optional<bool> use_datagram_transport;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700772 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100773 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800774 };
775 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
776 "Did you add something to RTCConfiguration and forget to "
777 "update operator==?");
778 return type == o.type && servers == o.servers &&
779 bundle_policy == o.bundle_policy &&
780 rtcp_mux_policy == o.rtcp_mux_policy &&
781 tcp_candidate_policy == o.tcp_candidate_policy &&
782 candidate_network_policy == o.candidate_network_policy &&
783 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
784 audio_jitter_buffer_fast_accelerate ==
785 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100786 audio_jitter_buffer_min_delay_ms ==
787 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100788 audio_jitter_buffer_enable_rtx_handling ==
789 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800790 ice_connection_receiving_timeout ==
791 o.ice_connection_receiving_timeout &&
792 ice_backup_candidate_pair_ping_interval ==
793 o.ice_backup_candidate_pair_ping_interval &&
794 continual_gathering_policy == o.continual_gathering_policy &&
795 certificates == o.certificates &&
796 prioritize_most_likely_ice_candidate_pairs ==
797 o.prioritize_most_likely_ice_candidate_pairs &&
798 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800799 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700800 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100801 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800802 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800803 screencast_min_bitrate == o.screencast_min_bitrate &&
804 combined_audio_video_bwe == o.combined_audio_video_bwe &&
805 enable_dtls_srtp == o.enable_dtls_srtp &&
806 ice_candidate_pool_size == o.ice_candidate_pool_size &&
807 prune_turn_ports == o.prune_turn_ports &&
808 presume_writable_when_fully_relayed ==
809 o.presume_writable_when_fully_relayed &&
810 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800811 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wang1fe119f2019-05-31 16:55:33 -0700812 surface_ice_candidates_on_ice_transport_type_changed ==
813 o.surface_ice_candidates_on_ice_transport_type_changed &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800814 ice_check_interval_strong_connectivity ==
815 o.ice_check_interval_strong_connectivity &&
816 ice_check_interval_weak_connectivity ==
817 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700818 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700819 ice_unwritable_timeout == o.ice_unwritable_timeout &&
820 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800821 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800822 stun_candidate_keepalive_interval ==
823 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200824 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800825 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800826 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700827 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700828 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700829 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700830 use_media_transport_for_data_channels ==
831 o.use_media_transport_for_data_channels &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -0700832 use_datagram_transport == o.use_datagram_transport &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100833 crypto_options == o.crypto_options &&
834 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800835}
836
837bool PeerConnectionInterface::RTCConfiguration::operator!=(
838 const PeerConnectionInterface::RTCConfiguration& o) const {
839 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800840}
841
zhihuang8f65cdf2016-05-06 18:40:30 -0700842// Generate a RTCP CNAME when a PeerConnection is created.
843std::string GenerateRtcpCname() {
844 std::string cname;
845 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100846 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800847 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700848 }
849 return cname;
850}
851
zhihuang1c378ed2017-08-17 14:10:50 -0700852bool ValidateOfferAnswerOptions(
853 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
854 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
855 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700856}
857
zhihuang1c378ed2017-08-17 14:10:50 -0700858// From |rtc_options|, fill parts of |session_options| shared by all generated
859// m= sections (in other words, nothing that involves a map/array).
860void ExtractSharedMediaSessionOptions(
861 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
862 cricket::MediaSessionOptions* session_options) {
863 session_options->vad_enabled = rtc_options.voice_activity_detection;
864 session_options->bundle_enabled = rtc_options.use_rtp_mux;
Mirta Dvornicic479a3c02019-06-04 15:38:50 +0200865 session_options->raw_packetization_for_video =
866 rtc_options.raw_packetization_for_video;
zhihuang1c378ed2017-08-17 14:10:50 -0700867}
zhihuanga77e6bb2017-08-14 18:17:48 -0700868
zhihuang38ede132017-06-15 12:52:32 -0700869PeerConnection::PeerConnection(PeerConnectionFactory* factory,
870 std::unique_ptr<RtcEventLog> event_log,
871 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700873 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100874 event_log_ptr_(event_log_.get()),
Bjorn A Mellem5985a042019-06-28 14:19:38 -0700875 datagram_transport_config_(
876 field_trial::FindFullName(kDatagramTransportFieldTrial)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700877 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700878 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700879 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100880 call_(std::move(call)),
881 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882
883PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100884 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800885 RTC_DCHECK_RUN_ON(signaling_thread());
886
Steve Anton8af21862017-12-15 11:20:13 -0800887 // Need to stop transceivers before destroying the stats collector because
888 // AudioRtpSender has a reference to the StatsCollector it will update when
889 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100890 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800891 transceiver->Stop();
892 }
Steve Anton4171afb2017-11-20 10:20:22 -0800893
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700894 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800895 if (stats_collector_) {
896 stats_collector_->WaitForPendingRequest();
897 stats_collector_ = nullptr;
898 }
Steve Anton75737c02017-11-06 10:37:17 -0800899
Steve Anton8af21862017-12-15 11:20:13 -0800900 // Don't destroy BaseChannels until after stats has been cleaned up so that
901 // the last stats request can still read from the channels.
902 DestroyAllChannels();
903
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800905
906 webrtc_session_desc_factory_.reset();
907 sctp_invoker_.reset();
908 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800909 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800910 transport_controller_.reset();
911
deadbeef91dd5672016-05-18 16:55:30 -0700912 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100913 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
914 RTC_DCHECK_RUN_ON(network_thread());
915 port_allocator_.reset();
916 });
eladalon248fd4f2017-09-06 05:18:15 -0700917 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700918 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100919 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700920 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800921 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700922 event_log_.reset();
923 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924}
925
Steve Anton8af21862017-12-15 11:20:13 -0800926void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800927 // Destroy video channels first since they may have a pointer to a voice
928 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100929 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800930 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800931 DestroyTransceiverChannel(transceiver);
932 }
933 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100934 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800935 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800936 DestroyTransceiverChannel(transceiver);
937 }
938 }
939 DestroyDataChannel();
940}
941
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000943 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700944 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100945 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100946 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100947 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700948
949 RTCError config_error = ValidateConfiguration(configuration);
950 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100951 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700952 return false;
953 }
954
Benjamin Wrightcab58882018-05-02 15:12:47 -0700955 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100956 RTC_LOG(LS_ERROR)
957 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100958 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800959 return false;
960 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200961
Benjamin Wrightcab58882018-05-02 15:12:47 -0700962 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800963 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100964 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100965 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800966 return false;
967 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700968
Benjamin Wrightcab58882018-05-02 15:12:47 -0700969 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700970 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700971 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700972 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800973
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200974 cricket::ServerAddresses stun_servers;
975 std::vector<cricket::RelayServerConfig> turn_servers;
976
977 RTCErrorType parse_error =
978 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
979 if (parse_error != RTCErrorType::NONE) {
980 return false;
981 }
982
deadbeef91dd5672016-05-18 16:55:30 -0700983 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700984 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100985 const auto pa_result =
986 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200987 RTC_FROM_HERE,
988 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100989 stun_servers, turn_servers, configuration));
990
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200991 // If initialization was successful, note if STUN or TURN servers
992 // were supplied.
993 if (!stun_servers.empty()) {
994 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
995 }
996 if (!turn_servers.empty()) {
997 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
998 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001000 // Send information about IPv4/IPv6 status.
1001 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001002 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001003 address_family = kPeerConnection_IPv6;
1004 } else {
1005 address_family = kPeerConnection_IPv4;
1006 }
1007 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1008 kPeerConnectionAddressFamilyCounter_Max);
1009
Zhi Huange830e682018-03-30 10:48:35 -07001010 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1011
Steve Anton75737c02017-11-06 10:37:17 -08001012 // RFC 3264: The numeric value of the session id and version in the
1013 // o line MUST be representable with a "64 bit signed integer".
1014 // Due to this constraint session id |session_id_| is max limited to
1015 // LLONG_MAX.
1016 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001017 JsepTransportController::Config config;
1018 config.redetermine_role_on_ice_restart =
1019 configuration.redetermine_role_on_ice_restart;
1020 config.ssl_max_version = factory_->options().ssl_max_version;
1021 config.disable_encryption = options.disable_encryption;
1022 config.bundle_policy = configuration.bundle_policy;
1023 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001024 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1025 // stub.
1026 config.crypto_options = configuration.crypto_options.has_value()
1027 ? *configuration.crypto_options
1028 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001029 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001030 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001031#if defined(ENABLE_EXTERNAL_AUTH)
1032 config.enable_external_auth = true;
1033#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001034 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001035
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001036 use_datagram_transport_ = datagram_transport_config_.enabled &&
1037 configuration_.use_datagram_transport.value_or(
1038 datagram_transport_config_.default_value);
1039 if (use_datagram_transport_ || configuration.use_media_transport ||
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001040 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001041 if (!factory_->media_transport_factory()) {
1042 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001043 << "PeerConnecton is initialized with use_media_transport = true or "
1044 << "use_media_transport_for_data_channels = true "
1045 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001046 return false;
1047 }
1048
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001049 if (configuration.use_media_transport ||
1050 configuration.use_media_transport_for_data_channels) {
1051 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1052 // RTP media transport is introduced. But until then, we require SDES to
1053 // be enabled.
1054 if (configuration.enable_dtls_srtp.has_value() &&
1055 configuration.enable_dtls_srtp.value()) {
1056 RTC_LOG(LS_WARNING)
1057 << "When media transport is used, SDES must be enabled. Set "
1058 "configuration.enable_dtls_srtp to false. use_media_transport="
1059 << configuration.use_media_transport
1060 << ", use_media_transport_for_data_channels="
1061 << configuration.use_media_transport_for_data_channels;
1062 return false;
1063 }
1064 }
1065
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001066 config.use_media_transport_for_media = configuration.use_media_transport;
1067 config.use_media_transport_for_data_channels =
1068 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07001069 config.use_datagram_transport = use_datagram_transport_;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001070 config.media_transport_factory = factory_->media_transport_factory();
1071 }
1072
Zhi Huange830e682018-03-30 10:48:35 -07001073 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001074 signaling_thread(), network_thread(), port_allocator_.get(),
1075 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001076 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001077 this, &PeerConnection::OnTransportControllerConnectionState);
1078 transport_controller_->SignalStandardizedIceConnectionState.connect(
1079 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001080 transport_controller_->SignalConnectionState.connect(
1081 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001082 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001083 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001084 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001085 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Eldar Relloda13ea22019-06-01 12:23:43 +03001086 transport_controller_->SignalIceCandidateError.connect(
1087 this, &PeerConnection::OnTransportControllerCandidateError);
Zhi Huange830e682018-03-30 10:48:35 -07001088 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001089 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1090 transport_controller_->SignalDtlsHandshakeError.connect(
1091 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1092
1093 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001094
deadbeefab9b2d12015-10-14 11:33:11 -07001095 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001096 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001097
Steve Antonba818672017-11-06 10:21:57 -08001098 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001099 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001100
Steve Anton75737c02017-11-06 10:37:17 -08001101 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1102 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1103 if (!configuration.certificates.empty()) {
1104 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1105 // just picking the first one. The decision should be made based on the DTLS
1106 // handshake. The DTLS negotiations need to know about all certificates.
1107 certificate = configuration.certificates[0];
1108 }
1109
Steve Antond25da372017-11-06 14:50:29 -08001110 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001111
1112 if (options.disable_encryption) {
1113 dtls_enabled_ = false;
1114 } else {
1115 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001116 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001117 // |configuration| can override the default |dtls_enabled_| value.
1118 if (configuration.enable_dtls_srtp) {
1119 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1120 }
1121 }
1122
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001123 if (configuration.use_media_transport_for_data_channels) {
1124 if (configuration.enable_rtp_data_channel) {
1125 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1126 "use_media_transport_for_data_channels are "
1127 "incompatible and cannot both be set to true";
1128 return false;
1129 }
1130 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1131 } else if (configuration.enable_rtp_data_channel) {
1132 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1133 // set. It takes precendence over the disable_sctp_data_channels
1134 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001135 data_channel_type_ = cricket::DCT_RTP;
1136 } else {
1137 // DTLS has to be enabled to use SCTP.
1138 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1139 data_channel_type_ = cricket::DCT_SCTP;
1140 }
1141 }
1142
1143 video_options_.screencast_min_bitrate_kbps =
1144 configuration.screencast_min_bitrate;
1145 audio_options_.combined_audio_video_bwe =
1146 configuration.combined_audio_video_bwe;
1147
1148 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001149 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001150
1151 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001152 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001153
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001154 audio_options_.audio_jitter_buffer_min_delay_ms =
1155 configuration.audio_jitter_buffer_min_delay_ms;
1156
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001157 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1158 configuration.audio_jitter_buffer_enable_rtx_handling;
1159
Steve Anton75737c02017-11-06 10:37:17 -08001160 // Whether the certificate generator/certificate is null or not determines
1161 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1162 // the right instructions by clearing the variables if needed.
1163 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001164 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001165 certificate = nullptr;
1166 } else if (certificate) {
1167 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001168 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001169 }
1170
1171 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1172 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001173 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001174 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1175 this, &PeerConnection::OnCertificateReady);
1176
1177 if (options.disable_encryption) {
1178 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1179 }
1180
1181 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001182 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001183 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184
Steve Anton4171afb2017-11-20 10:20:22 -08001185 // Add default audio/video transceivers for Plan B SDP.
1186 if (!IsUnifiedPlan()) {
1187 transceivers_.push_back(
1188 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1189 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1190 transceivers_.push_back(
1191 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1192 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1193 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001194 int delay_ms =
1195 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001196 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1197 MSG_REPORT_USAGE_PATTERN, nullptr);
Jonas Orelanda3aa9bd2019-04-17 07:38:40 +02001198
1199 if (dependencies.video_bitrate_allocator_factory) {
1200 video_bitrate_allocator_factory_ =
1201 std::move(dependencies.video_bitrate_allocator_factory);
1202 } else {
1203 video_bitrate_allocator_factory_ =
1204 CreateBuiltinVideoBitrateAllocatorFactory();
1205 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 return true;
1207}
1208
Steve Anton038834f2017-07-14 15:59:59 -07001209RTCError PeerConnection::ValidateConfiguration(
1210 const RTCConfiguration& config) const {
1211 if (config.ice_regather_interval_range &&
1212 config.continual_gathering_policy == GATHER_ONCE) {
1213 return RTCError(RTCErrorType::INVALID_PARAMETER,
1214 "ice_regather_interval_range specified but continual "
1215 "gathering policy is GATHER_ONCE");
1216 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001217 auto result =
1218 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1219 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001220}
1221
Yves Gerey665174f2018-06-19 15:03:05 +02001222rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001223 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001224 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1225 "Plan SdpSemantics. Please use GetSenders "
1226 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001227 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228}
1229
Yves Gerey665174f2018-06-19 15:03:05 +02001230rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001231 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001232 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1233 "Plan SdpSemantics. Please use GetReceivers "
1234 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001235 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236}
1237
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001238bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001239 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001240 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1241 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001242 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243 if (IsClosed()) {
1244 return false;
1245 }
deadbeefab9b2d12015-10-14 11:33:11 -07001246 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247 return false;
1248 }
deadbeefab9b2d12015-10-14 11:33:11 -07001249
1250 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001251 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1252 observer->SignalAudioTrackAdded.connect(this,
1253 &PeerConnection::OnAudioTrackAdded);
1254 observer->SignalAudioTrackRemoved.connect(
1255 this, &PeerConnection::OnAudioTrackRemoved);
1256 observer->SignalVideoTrackAdded.connect(this,
1257 &PeerConnection::OnVideoTrackAdded);
1258 observer->SignalVideoTrackRemoved.connect(
1259 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001260 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001261
deadbeefab9b2d12015-10-14 11:33:11 -07001262 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001263 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001264 }
1265 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001266 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001267 }
1268
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001269 stats_->AddStream(local_stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001270 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271 return true;
1272}
1273
1274void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001275 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001276 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1277 "Plan SdpSemantics. Please use RemoveTrack "
1278 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001279 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001280 if (!IsClosed()) {
1281 for (const auto& track : local_stream->GetAudioTracks()) {
1282 RemoveAudioTrack(track.get(), local_stream);
1283 }
1284 for (const auto& track : local_stream->GetVideoTracks()) {
1285 RemoveVideoTrack(track.get(), local_stream);
1286 }
deadbeefab9b2d12015-10-14 11:33:11 -07001287 }
deadbeefab9b2d12015-10-14 11:33:11 -07001288 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001289 stream_observers_.erase(
1290 std::remove_if(
1291 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001292 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001293 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001294 }),
1295 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001296
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 if (IsClosed()) {
1298 return;
1299 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001300 UpdateNegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301}
1302
Steve Anton2d6c76a2018-01-05 17:10:52 -08001303RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001304 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001305 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001306 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001307 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001308 if (!track) {
1309 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1310 }
1311 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1312 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1314 "Track has invalid kind: " + track->kind());
1315 }
Steve Antonf9381f02017-12-14 10:23:57 -08001316 if (IsClosed()) {
1317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1318 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001319 }
Steve Anton4171afb2017-11-20 10:20:22 -08001320 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001321 LOG_AND_RETURN_ERROR(
1322 RTCErrorType::INVALID_PARAMETER,
1323 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001324 }
Steve Antonf9381f02017-12-14 10:23:57 -08001325 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001326 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1327 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001328 if (sender_or_error.ok()) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001329 UpdateNegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001330 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001331 }
1332 return sender_or_error;
1333}
deadbeefe1f9d832016-01-14 15:35:42 -08001334
Steve Antonf9381f02017-12-14 10:23:57 -08001335RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1336PeerConnection::AddTrackPlanB(
1337 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001338 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001339 if (stream_ids.size() > 1u) {
1340 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1341 "AddTrack with more than one stream is not "
1342 "supported with Plan B semantics.");
1343 }
1344 std::vector<std::string> adjusted_stream_ids = stream_ids;
1345 if (adjusted_stream_ids.empty()) {
1346 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1347 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001348 cricket::MediaType media_type =
1349 (track->kind() == MediaStreamTrackInterface::kAudioKind
1350 ? cricket::MEDIA_TYPE_AUDIO
1351 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001352 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001353 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001354 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001355 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001356 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001357 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001358 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001359 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001360 if (sender_info) {
1361 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001362 }
Steve Antonf9381f02017-12-14 10:23:57 -08001363 } else {
1364 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001365 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001366 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001367 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001368 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001369 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001370 if (sender_info) {
1371 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001372 }
deadbeefe1f9d832016-01-14 15:35:42 -08001373 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001374 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001375}
deadbeefe1f9d832016-01-14 15:35:42 -08001376
Steve Antonf9381f02017-12-14 10:23:57 -08001377RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1378PeerConnection::AddTrackUnifiedPlan(
1379 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001380 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001381 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1382 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001383 RTC_LOG(LS_INFO) << "Reusing an existing "
1384 << cricket::MediaTypeToString(transceiver->media_type())
1385 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001386 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001387 transceiver->internal()->set_direction(
1388 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001389 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001390 transceiver->internal()->set_direction(
1391 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001392 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001393 transceiver->sender()->SetTrack(track);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001394 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001395 } else {
1396 cricket::MediaType media_type =
1397 (track->kind() == MediaStreamTrackInterface::kAudioKind
1398 ? cricket::MEDIA_TYPE_AUDIO
1399 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001400 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1401 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001402 std::string sender_id = track->id();
1403 // Avoid creating a sender with an existing ID by generating a random ID.
1404 // This can happen if this is the second time AddTrack has created a sender
1405 // for this track.
1406 if (FindSenderById(sender_id)) {
1407 sender_id = rtc::CreateRandomUuid();
1408 }
Florent Castelli892acf02018-10-01 22:47:20 +02001409 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001410 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1411 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001412 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001413 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001414 }
Steve Antonf9381f02017-12-14 10:23:57 -08001415 return transceiver->sender();
1416}
1417
1418rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1419PeerConnection::FindFirstTransceiverForAddedTrack(
1420 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1421 RTC_DCHECK(track);
1422 for (auto transceiver : transceivers_) {
1423 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001424 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001425 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001426 !transceiver->internal()->has_ever_been_used_to_send() &&
1427 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001428 return transceiver;
1429 }
1430 }
1431 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001432}
1433
1434bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1435 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001436 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001437}
1438
Steve Anton24db5732018-07-23 10:27:33 -07001439RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001440 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001441 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001442 if (!sender) {
1443 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1444 }
deadbeefe1f9d832016-01-14 15:35:42 -08001445 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001446 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1447 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001448 }
Steve Antonf9381f02017-12-14 10:23:57 -08001449 if (IsUnifiedPlan()) {
1450 auto transceiver = FindTransceiverBySender(sender);
1451 if (!transceiver || !sender->track()) {
1452 return RTCError::OK();
1453 }
1454 sender->SetTrack(nullptr);
1455 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001456 transceiver->internal()->set_direction(
1457 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001458 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001459 transceiver->internal()->set_direction(
1460 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001461 }
Steve Anton4171afb2017-11-20 10:20:22 -08001462 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001463 bool removed;
1464 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1465 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1466 } else {
1467 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1468 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1469 }
1470 if (!removed) {
1471 LOG_AND_RETURN_ERROR(
1472 RTCErrorType::INVALID_PARAMETER,
1473 "Couldn't find sender " + sender->id() + " to remove.");
1474 }
Steve Anton4171afb2017-11-20 10:20:22 -08001475 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001476 UpdateNegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001477 return RTCError::OK();
1478}
1479
1480rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1481PeerConnection::FindTransceiverBySender(
1482 rtc::scoped_refptr<RtpSenderInterface> sender) {
1483 for (auto transceiver : transceivers_) {
1484 if (transceiver->sender() == sender) {
1485 return transceiver;
1486 }
1487 }
1488 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001489}
1490
Steve Anton9158ef62017-11-27 13:01:52 -08001491RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1492PeerConnection::AddTransceiver(
1493 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1494 return AddTransceiver(track, RtpTransceiverInit());
1495}
1496
1497RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1498PeerConnection::AddTransceiver(
1499 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1500 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001501 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001502 RTC_CHECK(IsUnifiedPlan())
1503 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001504 if (!track) {
1505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1506 }
1507 cricket::MediaType media_type;
1508 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1509 media_type = cricket::MEDIA_TYPE_AUDIO;
1510 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1511 media_type = cricket::MEDIA_TYPE_VIDEO;
1512 } else {
1513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1514 "Track kind is not audio or video");
1515 }
1516 return AddTransceiver(media_type, track, init);
1517}
1518
1519RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1520PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1521 return AddTransceiver(media_type, RtpTransceiverInit());
1522}
1523
1524RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1525PeerConnection::AddTransceiver(cricket::MediaType media_type,
1526 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001527 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001528 RTC_CHECK(IsUnifiedPlan())
1529 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001530 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1531 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1533 "media type is not audio or video");
1534 }
1535 return AddTransceiver(media_type, nullptr, init);
1536}
1537
1538RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1539PeerConnection::AddTransceiver(
1540 cricket::MediaType media_type,
1541 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001542 const RtpTransceiverInit& init,
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001543 bool update_negotiation_needed) {
Steve Anton9158ef62017-11-27 13:01:52 -08001544 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1545 media_type == cricket::MEDIA_TYPE_VIDEO));
1546 if (track) {
1547 RTC_DCHECK_EQ(media_type,
1548 (track->kind() == MediaStreamTrackInterface::kAudioKind
1549 ? cricket::MEDIA_TYPE_AUDIO
1550 : cricket::MEDIA_TYPE_VIDEO));
1551 }
1552
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001553 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1554 init.send_encodings.size(), 0, 7, 8);
1555
Amit Hilbuchaa584152019-02-06 17:09:52 -08001556 size_t num_rids = absl::c_count_if(init.send_encodings,
1557 [](const RtpEncodingParameters& encoding) {
1558 return !encoding.rid.empty();
1559 });
1560 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001561 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001562 RTCErrorType::INVALID_PARAMETER,
1563 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001564 }
1565
Amit Hilbuchf4770402019-04-08 14:11:57 -07001566 if (num_rids > 0 && absl::c_any_of(init.send_encodings,
1567 [](const RtpEncodingParameters& encoding) {
1568 return !IsLegalRsidName(encoding.rid);
1569 })) {
1570 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1571 "Invalid RID value provided.");
1572 }
1573
Amit Hilbuchaa584152019-02-06 17:09:52 -08001574 if (absl::c_any_of(init.send_encodings,
1575 [](const RtpEncodingParameters& encoding) {
1576 return encoding.ssrc.has_value();
1577 })) {
1578 LOG_AND_RETURN_ERROR(
1579 RTCErrorType::UNSUPPORTED_PARAMETER,
1580 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001581 }
1582
1583 RtpParameters parameters;
1584 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001585
1586 // Encodings are dropped from the tail if too many are provided.
1587 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1588 parameters.encodings.erase(
1589 parameters.encodings.begin() + kMaxSimulcastStreams,
1590 parameters.encodings.end());
1591 }
1592
1593 // Single RID should be removed.
1594 if (parameters.encodings.size() == 1 &&
1595 !parameters.encodings[0].rid.empty()) {
1596 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1597 parameters.encodings[0].rid.clear();
1598 }
1599
1600 // If RIDs were not provided, they are generated for simulcast scenario.
1601 if (parameters.encodings.size() > 1 && num_rids == 0) {
1602 rtc::UniqueStringGenerator rid_generator;
1603 for (RtpEncodingParameters& encoding : parameters.encodings) {
1604 encoding.rid = rid_generator();
1605 }
1606 }
1607
Florent Castelli892acf02018-10-01 22:47:20 +02001608 if (UnimplementedRtpParameterHasValue(parameters)) {
1609 LOG_AND_RETURN_ERROR(
1610 RTCErrorType::UNSUPPORTED_PARAMETER,
1611 "Attempted to set an unimplemented parameter of RtpParameters.");
1612 }
Steve Anton9158ef62017-11-27 13:01:52 -08001613
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001614 auto result = cricket::CheckRtpParametersValues(parameters);
1615 if (!result.ok()) {
1616 LOG_AND_RETURN_ERROR(result.type(), result.message());
1617 }
1618
Steve Anton3d954a62018-04-02 11:27:23 -07001619 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1620 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001621 // Set the sender ID equal to the track ID if the track is specified unless
1622 // that sender ID is already in use.
1623 std::string sender_id =
1624 (track && !FindSenderById(track->id()) ? track->id()
1625 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001626 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001627 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001628 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1629 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1630 transceiver->internal()->set_direction(init.direction);
1631
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001632 if (update_negotiation_needed) {
1633 UpdateNegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001634 }
Steve Antonf9381f02017-12-14 10:23:57 -08001635
1636 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1637}
1638
Steve Anton02ee47c2018-01-10 16:26:06 -08001639rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1640PeerConnection::CreateSender(
1641 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001642 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001643 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001644 const std::vector<std::string>& stream_ids,
1645 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001646 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001647 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001648 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1649 RTC_DCHECK(!track ||
1650 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1651 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1652 signaling_thread(),
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001653 AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001654 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001655 } else {
1656 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1657 RTC_DCHECK(!track ||
1658 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1659 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001660 signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001661 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001662 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001663 bool set_track_succeeded = sender->SetTrack(track);
1664 RTC_DCHECK(set_track_succeeded);
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001665 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001666 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001667 return sender;
1668}
1669
1670rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1671PeerConnection::CreateReceiver(cricket::MediaType media_type,
1672 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001673 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1674 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001675 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001676 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001677 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1678 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001679 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001680 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001681 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001682 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001683 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1684 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001685 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001686 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001687 return receiver;
1688}
1689
1690rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1691PeerConnection::CreateAndAddTransceiver(
1692 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1693 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1694 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001695 // Ensure that the new sender does not have an ID that is already in use by
1696 // another sender.
1697 // Allow receiver IDs to conflict since those come from remote SDP (which
1698 // could be invalid, but should not cause a crash).
1699 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001700 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
Florent Castelli2d9d82e2019-04-23 19:25:51 +02001701 signaling_thread(),
1702 new RtpTransceiver(sender, receiver, channel_manager()));
Steve Anton9158ef62017-11-27 13:01:52 -08001703 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001704 transceiver->internal()->SignalNegotiationNeeded.connect(
1705 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001706 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001707}
1708
Steve Anton52d86772018-02-20 15:48:12 -08001709void PeerConnection::OnNegotiationNeeded() {
1710 RTC_DCHECK_RUN_ON(signaling_thread());
1711 RTC_DCHECK(!IsClosed());
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001712 UpdateNegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001713}
1714
deadbeeffac06552015-11-25 11:26:01 -08001715rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001716 const std::string& kind,
1717 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001718 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001719 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1720 "Plan SdpSemantics. Please use AddTransceiver "
1721 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001722 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001723 if (IsClosed()) {
1724 return nullptr;
1725 }
Steve Anton4171afb2017-11-20 10:20:22 -08001726
Seth Hampson5b4f0752018-04-02 16:31:36 -07001727 // Internally we need to have one stream with Plan B semantics, so we
1728 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001729 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001730 if (stream_id.empty()) {
1731 stream_ids.push_back(rtc::CreateRandomUuid());
1732 RTC_LOG(LS_INFO)
1733 << "No stream_id specified for sender. Generated stream ID: "
1734 << stream_ids[0];
1735 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001736 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001737 }
1738
Steve Anton4171afb2017-11-20 10:20:22 -08001739 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001740 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001741 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001742 auto audio_sender = AudioRtpSender::Create(
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001743 worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001744 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001745 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001746 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001747 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001748 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001749 auto video_sender =
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02001750 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001751 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001752 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001753 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001754 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001755 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001756 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001757 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001758 }
Henrik Andreasssoncc189172019-05-20 09:01:38 +00001759 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001760
deadbeefe1f9d832016-01-14 15:35:42 -08001761 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001762}
1763
deadbeef70ab1a12015-09-28 16:53:55 -07001764std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1765 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001766 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001767 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001768 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001769 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001770 }
1771 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001772}
1773
Steve Anton4171afb2017-11-20 10:20:22 -08001774std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1775PeerConnection::GetSendersInternal() const {
1776 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1777 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001778 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001779 auto senders = transceiver->internal()->senders();
1780 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1781 }
1782 return all_senders;
1783}
1784
deadbeef70ab1a12015-09-28 16:53:55 -07001785std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1786PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001787 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001788 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001789 for (const auto& receiver : GetReceiversInternal()) {
1790 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001791 }
1792 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001793}
1794
Steve Anton4171afb2017-11-20 10:20:22 -08001795std::vector<
1796 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1797PeerConnection::GetReceiversInternal() const {
1798 std::vector<
1799 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1800 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001801 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001802 auto receivers = transceiver->internal()->receivers();
1803 all_receivers.insert(all_receivers.end(), receivers.begin(),
1804 receivers.end());
1805 }
1806 return all_receivers;
1807}
1808
Steve Anton9158ef62017-11-27 13:01:52 -08001809std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1810PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001811 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001812 RTC_CHECK(IsUnifiedPlan())
1813 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001814 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001815 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001816 all_transceivers.push_back(transceiver);
1817 }
1818 return all_transceivers;
1819}
1820
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001822 MediaStreamTrackInterface* track,
1823 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001824 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001825 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001826 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001828 return false;
1829 }
1830
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001831 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001832 // The StatsCollector is used to tell if a track is valid because it may
1833 // remember tracks that the PeerConnection previously removed.
1834 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001835 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1836 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001837 return false;
1838 }
Steve Antonad182762018-09-05 20:22:40 +00001839 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1840 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841 return true;
1842}
1843
hbos74e1a4f2016-09-15 23:33:01 -07001844void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001845 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001846 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001847 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001848 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001849 stats_collector_->GetStatsReport(callback);
1850}
1851
Henrik Boström1df1bf82018-03-20 13:24:20 +01001852void PeerConnection::GetStats(
1853 rtc::scoped_refptr<RtpSenderInterface> selector,
1854 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1855 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001856 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001857 RTC_DCHECK(callback);
1858 RTC_DCHECK(stats_collector_);
1859 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1860 if (selector) {
1861 for (const auto& proxy_transceiver : transceivers_) {
1862 for (const auto& proxy_sender :
1863 proxy_transceiver->internal()->senders()) {
1864 if (proxy_sender == selector) {
1865 internal_sender = proxy_sender->internal();
1866 break;
1867 }
1868 }
1869 if (internal_sender)
1870 break;
1871 }
1872 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001873 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001874 // belong to the PeerConnection (in Plan B, senders can be removed from the
1875 // PeerConnection). This means that "all the stats objects representing the
1876 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1877 // produces an empty stats report.
1878 stats_collector_->GetStatsReport(internal_sender, callback);
1879}
1880
1881void PeerConnection::GetStats(
1882 rtc::scoped_refptr<RtpReceiverInterface> selector,
1883 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1884 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001885 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001886 RTC_DCHECK(callback);
1887 RTC_DCHECK(stats_collector_);
1888 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1889 if (selector) {
1890 for (const auto& proxy_transceiver : transceivers_) {
1891 for (const auto& proxy_receiver :
1892 proxy_transceiver->internal()->receivers()) {
1893 if (proxy_receiver == selector) {
1894 internal_receiver = proxy_receiver->internal();
1895 break;
1896 }
1897 }
1898 if (internal_receiver)
1899 break;
1900 }
1901 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001902 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001903 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1904 // the PeerConnection). This means that "all the stats objects representing
1905 // the selector" is an empty set. Invoking GetStatsReport() with a null
1906 // selector produces an empty stats report.
1907 stats_collector_->GetStatsReport(internal_receiver, callback);
1908}
1909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001911 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912 return signaling_state_;
1913}
1914
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915PeerConnectionInterface::IceConnectionState
1916PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001917 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 return ice_connection_state_;
1919}
1920
Alex Loiko9289eda2018-11-23 16:18:59 +00001921PeerConnectionInterface::IceConnectionState
1922PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001923 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001924 return standardized_ice_connection_state_;
1925}
1926
Jonas Olsson635474e2018-10-18 15:58:17 +02001927PeerConnectionInterface::PeerConnectionState
1928PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001929 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001930 return connection_state_;
1931}
1932
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933PeerConnectionInterface::IceGatheringState
1934PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001935 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 return ice_gathering_state_;
1937}
1938
Yves Gerey665174f2018-06-19 15:03:05 +02001939rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001940 const std::string& label,
1941 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001942 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001943 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001944
deadbeefab9b2d12015-10-14 11:33:11 -07001945 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001946
kwibergd1fe2812016-04-27 06:47:29 -07001947 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001948 if (config) {
1949 internal_config.reset(new InternalDataChannelInit(*config));
1950 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001951 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001952 InternalCreateDataChannel(label, internal_config.get()));
1953 if (!channel.get()) {
1954 return nullptr;
1955 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001956
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001957 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1958 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001959 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Guido Urdaneta70c2db12019-04-16 12:24:14 +02001960 UpdateNegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001961 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001962 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001963 return DataChannelProxy::Create(signaling_thread(), channel.get());
1964}
1965
1966void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001967 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001968 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001969 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001970
nisse7ce109a2017-01-31 00:57:56 -08001971 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001973 return;
1974 }
deadbeefab9b2d12015-10-14 11:33:11 -07001975
Steve Anton8d3444d2017-10-20 15:30:51 -07001976 if (IsClosed()) {
1977 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001978 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001979 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001980 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001981 return;
1982 }
1983
Steve Anton25ca0ac2019-06-25 10:40:48 -07001984 // If a session error has occurred the PeerConnection is in a possibly
1985 // inconsistent state so fail right away.
1986 if (session_error() != SessionError::kNone) {
1987 std::string error_message = GetSessionErrorMsg();
1988 RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
1989 PostCreateSessionDescriptionFailure(
1990 observer,
1991 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
1992 return;
1993 }
1994
zhihuang1c378ed2017-08-17 14:10:50 -07001995 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001996 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001997 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001998 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001999 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07002000 return;
2001 }
2002
Steve Anton22da89f2018-01-25 13:58:07 -08002003 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
2004 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
2005 if (IsUnifiedPlan()) {
2006 RTCError error = HandleLegacyOfferOptions(options);
2007 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002008 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08002009 return;
2010 }
2011 }
2012
zhihuang1c378ed2017-08-17 14:10:50 -07002013 cricket::MediaSessionOptions session_options;
2014 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08002015 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016}
2017
Steve Anton22da89f2018-01-25 13:58:07 -08002018RTCError PeerConnection::HandleLegacyOfferOptions(
2019 const RTCOfferAnswerOptions& options) {
2020 RTC_DCHECK(IsUnifiedPlan());
2021
2022 if (options.offer_to_receive_audio == 0) {
2023 RemoveRecvDirectionFromReceivingTransceiversOfType(
2024 cricket::MEDIA_TYPE_AUDIO);
2025 } else if (options.offer_to_receive_audio == 1) {
2026 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
2027 } else if (options.offer_to_receive_audio > 1) {
2028 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2029 "offer_to_receive_audio > 1 is not supported.");
2030 }
2031
2032 if (options.offer_to_receive_video == 0) {
2033 RemoveRecvDirectionFromReceivingTransceiversOfType(
2034 cricket::MEDIA_TYPE_VIDEO);
2035 } else if (options.offer_to_receive_video == 1) {
2036 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2037 } else if (options.offer_to_receive_video > 1) {
2038 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2039 "offer_to_receive_video > 1 is not supported.");
2040 }
2041
2042 return RTCError::OK();
2043}
2044
2045void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2046 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002047 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002048 RtpTransceiverDirection new_direction =
2049 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2050 if (new_direction != transceiver->direction()) {
2051 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2052 << " transceiver (MID="
2053 << transceiver->mid().value_or("<not set>") << ") from "
2054 << RtpTransceiverDirectionToString(
2055 transceiver->direction())
2056 << " to "
2057 << RtpTransceiverDirectionToString(new_direction)
2058 << " since CreateOffer specified offer_to_receive=0";
2059 transceiver->internal()->set_direction(new_direction);
2060 }
Steve Anton22da89f2018-01-25 13:58:07 -08002061 }
2062}
2063
2064void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2065 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002066 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002067 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002068 RTC_LOG(LS_INFO)
2069 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2070 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002071 RtpTransceiverInit init;
2072 init.direction = RtpTransceiverDirection::kRecvOnly;
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002073 AddTransceiver(media_type, nullptr, init,
2074 /*update_negotiation_needed=*/false);
Steve Anton22da89f2018-01-25 13:58:07 -08002075 }
2076}
2077
2078std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2079PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2080 std::vector<
2081 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2082 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002083 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002084 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002085 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2086 receiving_transceivers.push_back(transceiver);
2087 }
2088 }
2089 return receiving_transceivers;
2090}
2091
htaa2a49d92016-03-04 02:51:39 -08002092void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2093 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002094 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002095 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002096 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002097 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002098 return;
2099 }
2100
Steve Anton25ca0ac2019-06-25 10:40:48 -07002101 // If a session error has occurred the PeerConnection is in a possibly
2102 // inconsistent state so fail right away.
2103 if (session_error() != SessionError::kNone) {
2104 std::string error_message = GetSessionErrorMsg();
2105 RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
2106 PostCreateSessionDescriptionFailure(
2107 observer,
2108 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2109 return;
2110 }
2111
Steve Antondffead82018-02-06 10:31:29 -08002112 if (!(signaling_state_ == kHaveRemoteOffer ||
2113 signaling_state_ == kHaveLocalPrAnswer)) {
2114 std::string error =
2115 "PeerConnection cannot create an answer in a state other than "
2116 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002117 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002118 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002119 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002120 return;
2121 }
2122
Steve Antondffead82018-02-06 10:31:29 -08002123 // The remote description should be set if we're in the right state.
2124 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002125
Steve Anton22da89f2018-01-25 13:58:07 -08002126 if (IsUnifiedPlan()) {
2127 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2128 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2129 "supported with Unified Plan semantics. Use the "
2130 "RtpTransceiver API instead.";
2131 }
2132 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2133 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2134 "supported with Unified Plan semantics. Use the "
2135 "RtpTransceiver API instead.";
2136 }
2137 }
2138
htaa2a49d92016-03-04 02:51:39 -08002139 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002140 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002141
Steve Antond25da372017-11-06 14:50:29 -08002142 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002143}
2144
2145void PeerConnection::SetLocalDescription(
2146 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002147 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002148 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002149 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002150
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 // The SetLocalDescription contract is that we take ownership of the session
2152 // description regardless of the outcome, so wrap it in a unique_ptr right
2153 // away. Ideally, SetLocalDescription's signature will be changed to take the
2154 // description as a unique_ptr argument to formalize this agreement.
2155 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2156
nisse7ce109a2017-01-31 00:57:56 -08002157 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002158 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002159 return;
2160 }
Steve Anton8a006912017-12-04 15:25:56 -08002161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002163 PostSetSessionDescriptionFailure(
2164 observer,
2165 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 return;
2167 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002168
Steve Anton80dd7b52018-02-16 17:08:42 -08002169 // If a session error has occurred the PeerConnection is in a possibly
2170 // inconsistent state so fail right away.
2171 if (session_error() != SessionError::kNone) {
2172 std::string error_message = GetSessionErrorMsg();
2173 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002174 PostSetSessionDescriptionFailure(
2175 observer,
2176 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002177 return;
2178 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002179
Steve Anton80dd7b52018-02-16 17:08:42 -08002180 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2181 if (!error.ok()) {
2182 std::string error_message = GetSetDescriptionErrorMessage(
2183 cricket::CS_LOCAL, desc->GetType(), error);
2184 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002185 PostSetSessionDescriptionFailure(
2186 observer,
2187 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002188 return;
2189 }
2190
2191 // Grab the description type before moving ownership to ApplyLocalDescription,
2192 // which may destroy it before returning.
2193 const SdpType type = desc->GetType();
2194
2195 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002196 // |desc| may be destroyed at this point.
2197
2198 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002199 // If ApplyLocalDescription fails, the PeerConnection could be in an
2200 // inconsistent state, so act conservatively here and set the session error
2201 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2202 SetSessionError(SessionError::kContent, error.message());
2203 std::string error_message =
2204 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2205 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002206 PostSetSessionDescriptionFailure(
2207 observer,
2208 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002209 return;
2210 }
Steve Anton8a006912017-12-04 15:25:56 -08002211 RTC_DCHECK(local_description());
2212
2213 PostSetSessionDescriptionSuccess(observer);
2214
Steve Antonad182762018-09-05 20:22:40 +00002215 // MaybeStartGathering needs to be called after posting
2216 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2217 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002218 transport_controller_->MaybeStartGathering();
2219
Steve Antona3a92c22017-12-07 10:27:41 -08002220 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002221 // TODO(deadbeef): We already had to hop to the network thread for
2222 // MaybeStartGathering...
2223 network_thread()->Invoke<void>(
2224 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2225 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002226 // Make UMA notes about what was agreed to.
2227 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002228 }
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002229
2230 if (IsUnifiedPlan()) {
2231 bool was_negotiation_needed = is_negotiation_needed_;
2232 UpdateNegotiationNeeded();
2233 if (signaling_state() == kStable && was_negotiation_needed &&
2234 is_negotiation_needed_) {
2235 Observer()->OnRenegotiationNeeded();
2236 }
2237 }
2238
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002239 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002240}
2241
2242RTCError PeerConnection::ApplyLocalDescription(
2243 std::unique_ptr<SessionDescriptionInterface> desc) {
2244 RTC_DCHECK_RUN_ON(signaling_thread());
2245 RTC_DCHECK(desc);
2246
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002247 // Update stats here so that we have the most recent stats for tracks and
2248 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002249 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002250
Steve Antondcc3c022017-12-22 16:02:54 -08002251 // Take a reference to the old local description since it's used below to
2252 // compare against the new local description. When setting the new local
2253 // description, grab ownership of the replaced session description in case it
2254 // is the same as |old_local_description|, to keep it alive for the duration
2255 // of the method.
2256 const SessionDescriptionInterface* old_local_description =
2257 local_description();
2258 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002259 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002260 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002261 replaced_local_description = pending_local_description_
2262 ? std::move(pending_local_description_)
2263 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002264 current_local_description_ = std::move(desc);
2265 pending_local_description_ = nullptr;
2266 current_remote_description_ = std::move(pending_remote_description_);
2267 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002268 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002269 pending_local_description_ = std::move(desc);
2270 }
2271 // The session description to apply now must be accessed by
2272 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002273 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002274
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002275 // Report statistics about any use of simulcast.
2276 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2277 *local_description()->description());
2278
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002279 if (!is_caller_) {
2280 if (remote_description()) {
2281 // Remote description was applied first, so this PC is the callee.
2282 is_caller_ = false;
2283 } else {
2284 // Local description is applied first, so this PC is the caller.
2285 is_caller_ = true;
2286 }
2287 }
2288
Zhi Huange830e682018-03-30 10:48:35 -07002289 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2290 if (!error.ok()) {
2291 return error;
2292 }
2293
Steve Antondcc3c022017-12-22 16:02:54 -08002294 if (IsUnifiedPlan()) {
2295 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002296 cricket::CS_LOCAL, *local_description(), old_local_description,
2297 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002298 if (!error.ok()) {
2299 return error;
2300 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002301 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2302 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002303 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002304 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2305 // Note that code paths that don't set MID won't be able to use
2306 // information about DTLS transports.
2307 if (transceiver->mid()) {
2308 auto dtls_transport =
2309 LookupDtlsTransportByMidInternal(*transceiver->mid());
2310 transceiver->internal()->sender_internal()->set_transport(
2311 dtls_transport);
2312 transceiver->internal()->receiver_internal()->set_transport(
2313 dtls_transport);
2314 }
2315
Steve Antondcc3c022017-12-22 16:02:54 -08002316 const ContentInfo* content =
2317 FindMediaSectionForTransceiver(transceiver, local_description());
2318 if (!content) {
2319 continue;
2320 }
2321 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002322 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2323 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002324 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002325 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2326 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2327 // "recvonly", process the removal of a remote track for the media
2328 // description, given transceiver, removeList, and muteTracks.
2329 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2330 (transceiver->internal()->fired_direction() &&
2331 RtpTransceiverDirectionHasRecv(
2332 *transceiver->internal()->fired_direction()))) {
2333 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2334 &removed_streams);
2335 }
2336 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2337 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002338 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002339 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002340 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002341 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002342 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002343 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002344 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002345 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002346 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002347 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002348 }
2349 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002350 // Media channels will be created only when offer is set. These may use new
2351 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002352 if (type == SdpType::kOffer) {
2353 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2354 // description is applied. Restore back to old description.
2355 RTCError error = CreateChannels(*local_description()->description());
2356 if (!error.ok()) {
2357 return error;
2358 }
2359 }
Steve Antondcc3c022017-12-22 16:02:54 -08002360 // Remove unused channels if MediaContentDescription is rejected.
2361 RemoveUnusedChannels(local_description()->description());
2362 }
Steve Anton8a006912017-12-04 15:25:56 -08002363
Zhi Huange830e682018-03-30 10:48:35 -07002364 error = UpdateSessionState(type, cricket::CS_LOCAL,
2365 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002366 if (!error.ok()) {
2367 return error;
2368 }
Steve Antondcc3c022017-12-22 16:02:54 -08002369
Steve Anton8a006912017-12-04 15:25:56 -08002370 if (remote_description()) {
2371 // Now that we have a local description, we can push down remote candidates.
2372 UseCandidatesInSessionDescription(remote_description());
2373 }
2374
2375 pending_ice_restarts_.clear();
2376 if (session_error() != SessionError::kNone) {
2377 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2378 }
2379
deadbeefab9b2d12015-10-14 11:33:11 -07002380 // If setting the description decided our SSL role, allocate any necessary
2381 // SCTP sids.
2382 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002383 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002384 AllocateSctpSids(role);
2385 }
2386
Steve Antond3679212018-01-17 17:41:02 -08002387 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002388 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002389 const ContentInfo* content =
2390 FindMediaSectionForTransceiver(transceiver, local_description());
2391 if (!content) {
2392 continue;
2393 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002394 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2395 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002396 // 0 is a special value meaning "this sender has no associated send
2397 // stream". Need to call this so the sender won't attempt to configure
2398 // a no longer existing stream and run into DCHECKs in the lower
2399 // layers.
2400 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002401 } else {
2402 // Get the StreamParams from the channel which could generate SSRCs.
2403 const std::vector<StreamParams>& streams = channel->local_streams();
Henrik Andreasssoncc189172019-05-20 09:01:38 +00002404 transceiver->internal()->sender_internal()->set_stream_ids(
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002405 streams[0].stream_ids());
2406 transceiver->internal()->sender_internal()->SetSsrc(
2407 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002408 }
2409 }
2410 } else {
2411 // Plan B semantics.
2412
Steve Antondcc3c022017-12-22 16:02:54 -08002413 // Update state and SSRC of local MediaStreams and DataChannels based on the
2414 // local session description.
2415 const cricket::ContentInfo* audio_content =
2416 GetFirstAudioContent(local_description()->description());
2417 if (audio_content) {
2418 if (audio_content->rejected) {
2419 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2420 } else {
2421 const cricket::AudioContentDescription* audio_desc =
2422 audio_content->media_description()->as_audio();
2423 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2424 }
deadbeeffaac4972015-11-12 15:33:07 -08002425 }
deadbeefab9b2d12015-10-14 11:33:11 -07002426
Steve Antondcc3c022017-12-22 16:02:54 -08002427 const cricket::ContentInfo* video_content =
2428 GetFirstVideoContent(local_description()->description());
2429 if (video_content) {
2430 if (video_content->rejected) {
2431 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2432 } else {
2433 const cricket::VideoContentDescription* video_desc =
2434 video_content->media_description()->as_video();
2435 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2436 }
deadbeeffaac4972015-11-12 15:33:07 -08002437 }
deadbeefab9b2d12015-10-14 11:33:11 -07002438 }
2439
2440 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002441 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002442 if (data_content) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002443 const cricket::RtpDataContentDescription* rtp_data_desc =
2444 data_content->media_description()->as_rtp_data();
2445 // rtp_data_desc will be null if this is an SCTP description.
2446 if (rtp_data_desc) {
2447 UpdateLocalRtpDataChannels(rtp_data_desc->streams());
deadbeefab9b2d12015-10-14 11:33:11 -07002448 }
2449 }
2450
Steve Anton8a006912017-12-04 15:25:56 -08002451 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002452}
2453
Steve Anton06817cd2018-12-18 15:55:30 -08002454// The SDP parser used to populate these values by default for the 'content
2455// name' if an a=mid line was absent.
2456static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2457 switch (media_type) {
2458 case cricket::MEDIA_TYPE_AUDIO:
2459 return cricket::CN_AUDIO;
2460 case cricket::MEDIA_TYPE_VIDEO:
2461 return cricket::CN_VIDEO;
2462 case cricket::MEDIA_TYPE_DATA:
2463 return cricket::CN_DATA;
2464 }
2465 RTC_NOTREACHED();
2466 return "";
2467}
2468
2469void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002470 cricket::SessionDescription* new_remote_description) {
2471 RTC_DCHECK(new_remote_description);
Harald Alvestrand1716d392019-06-03 20:35:45 +02002472 const cricket::ContentInfos no_infos;
Steve Anton06817cd2018-12-18 15:55:30 -08002473 const cricket::ContentInfos& local_contents =
2474 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002475 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002476 const cricket::ContentInfos& remote_contents =
2477 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02002478 : no_infos);
Steve Antond7180cc2019-02-07 10:44:53 -08002479 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2480 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002481 if (!content.name.empty()) {
2482 continue;
2483 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002484 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002485 absl::string_view source_explanation;
2486 if (IsUnifiedPlan()) {
2487 if (i < local_contents.size()) {
2488 new_mid = local_contents[i].name;
2489 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002490 } else if (i < remote_contents.size()) {
2491 new_mid = remote_contents[i].name;
2492 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002493 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002494 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002495 source_explanation = "generated just now";
2496 }
2497 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002498 new_mid = std::string(
2499 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002500 source_explanation = "to match pre-existing behavior";
2501 }
Steve Antond7180cc2019-02-07 10:44:53 -08002502 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002503 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002504 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002505 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2506 << " is missing an a=mid line. Filling in the value '"
2507 << new_mid << "' " << source_explanation << ".";
2508 }
2509}
2510
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002511void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002512 SetSessionDescriptionObserver* observer,
2513 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002514 SetRemoteDescription(
2515 std::unique_ptr<SessionDescriptionInterface>(desc),
2516 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2517 new SetRemoteDescriptionObserverAdapter(this, observer)));
2518}
2519
2520void PeerConnection::SetRemoteDescription(
2521 std::unique_ptr<SessionDescriptionInterface> desc,
2522 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002523 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002524 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002525
nisse7ce109a2017-01-31 00:57:56 -08002526 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002527 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528 return;
2529 }
Steve Anton8a006912017-12-04 15:25:56 -08002530
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002532 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002533 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534 return;
2535 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002536
Steve Anton80dd7b52018-02-16 17:08:42 -08002537 // If a session error has occurred the PeerConnection is in a possibly
2538 // inconsistent state so fail right away.
2539 if (session_error() != SessionError::kNone) {
2540 std::string error_message = GetSessionErrorMsg();
2541 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2542 observer->OnSetRemoteDescriptionComplete(
2543 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2544 return;
2545 }
Steve Anton71439a62018-02-15 11:53:06 -08002546
Steve Antonba42e992018-04-09 14:10:01 -07002547 if (desc->GetType() == SdpType::kOffer) {
2548 // Report to UMA the format of the received offer.
2549 ReportSdpFormatReceived(*desc);
2550 }
2551
Steve Anton06817cd2018-12-18 15:55:30 -08002552 // Handle remote descriptions missing a=mid lines for interop with legacy end
2553 // points.
2554 FillInMissingRemoteMids(desc->description());
2555
Steve Anton80dd7b52018-02-16 17:08:42 -08002556 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002557 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002558 std::string error_message = GetSetDescriptionErrorMessage(
2559 cricket::CS_REMOTE, desc->GetType(), error);
2560 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002561 observer->OnSetRemoteDescriptionComplete(
2562 RTCError(error.type(), std::move(error_message)));
2563 return;
2564 }
Steve Anton71439a62018-02-15 11:53:06 -08002565
Steve Anton80dd7b52018-02-16 17:08:42 -08002566 // Grab the description type before moving ownership to
2567 // ApplyRemoteDescription, which may destroy it before returning.
2568 const SdpType type = desc->GetType();
2569
2570 error = ApplyRemoteDescription(std::move(desc));
2571 // |desc| may be destroyed at this point.
2572
2573 if (!error.ok()) {
2574 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2575 // inconsistent state, so act conservatively here and set the session error
2576 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2577 SetSessionError(SessionError::kContent, error.message());
2578 std::string error_message =
2579 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2580 RTC_LOG(LS_ERROR) << error_message;
2581 observer->OnSetRemoteDescriptionComplete(
2582 RTCError(error.type(), std::move(error_message)));
2583 return;
2584 }
2585 RTC_DCHECK(remote_description());
2586
2587 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002588 // TODO(deadbeef): We already had to hop to the network thread for
2589 // MaybeStartGathering...
2590 network_thread()->Invoke<void>(
2591 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2592 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002593 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002594 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002595 }
2596
Guido Urdaneta70c2db12019-04-16 12:24:14 +02002597 if (IsUnifiedPlan()) {
2598 bool was_negotiation_needed = is_negotiation_needed_;
2599 UpdateNegotiationNeeded();
2600 if (signaling_state() == kStable && was_negotiation_needed &&
2601 is_negotiation_needed_) {
2602 Observer()->OnRenegotiationNeeded();
2603 }
2604 }
2605
Steve Anton8a006912017-12-04 15:25:56 -08002606 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002607 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002608}
2609
2610RTCError PeerConnection::ApplyRemoteDescription(
2611 std::unique_ptr<SessionDescriptionInterface> desc) {
2612 RTC_DCHECK_RUN_ON(signaling_thread());
2613 RTC_DCHECK(desc);
2614
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615 // Update stats here so that we have the most recent stats for tracks and
2616 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002617 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002618
Steve Antondcc3c022017-12-22 16:02:54 -08002619 // Take a reference to the old remote description since it's used below to
2620 // compare against the new remote description. When setting the new remote
2621 // description, grab ownership of the replaced session description in case it
2622 // is the same as |old_remote_description|, to keep it alive for the duration
2623 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002624 const SessionDescriptionInterface* old_remote_description =
2625 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002626 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002627 SdpType type = desc->GetType();
2628 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002629 replaced_remote_description = pending_remote_description_
2630 ? std::move(pending_remote_description_)
2631 : std::move(current_remote_description_);
2632 current_remote_description_ = std::move(desc);
2633 pending_remote_description_ = nullptr;
2634 current_local_description_ = std::move(pending_local_description_);
2635 } else {
2636 replaced_remote_description = std::move(pending_remote_description_);
2637 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638 }
Steve Anton8a006912017-12-04 15:25:56 -08002639 // The session description to apply now must be accessed by
2640 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002641 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002643 // Report statistics about any use of simulcast.
2644 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2645 *remote_description()->description());
2646
Zhi Huange830e682018-03-30 10:48:35 -07002647 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2648 if (!error.ok()) {
2649 return error;
2650 }
Steve Anton8a006912017-12-04 15:25:56 -08002651 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002652 if (IsUnifiedPlan()) {
2653 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002654 cricket::CS_REMOTE, *remote_description(), local_description(),
2655 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002656 if (!error.ok()) {
2657 return error;
2658 }
Steve Antondcc3c022017-12-22 16:02:54 -08002659 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002660 // Media channels will be created only when offer is set. These may use new
2661 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002662 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002663 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002664 // description is applied. Restore back to old description.
2665 RTCError error = CreateChannels(*remote_description()->description());
2666 if (!error.ok()) {
2667 return error;
2668 }
2669 }
Steve Antondcc3c022017-12-22 16:02:54 -08002670 // Remove unused channels if MediaContentDescription is rejected.
2671 RemoveUnusedChannels(remote_description()->description());
2672 }
Steve Anton8a006912017-12-04 15:25:56 -08002673
Zhi Huange830e682018-03-30 10:48:35 -07002674 // NOTE: Candidates allocation will be initiated only when
2675 // SetLocalDescription is called.
2676 error = UpdateSessionState(type, cricket::CS_REMOTE,
2677 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002678 if (!error.ok()) {
2679 return error;
2680 }
2681
2682 if (local_description() &&
2683 !UseCandidatesInSessionDescription(remote_description())) {
2684 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2685 }
2686
2687 if (old_remote_description) {
2688 for (const cricket::ContentInfo& content :
2689 old_remote_description->description()->contents()) {
2690 // Check if this new SessionDescription contains new ICE ufrag and
2691 // password that indicates the remote peer requests an ICE restart.
2692 // TODO(deadbeef): When we start storing both the current and pending
2693 // remote description, this should reset pending_ice_restarts and compare
2694 // against the current description.
2695 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2696 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002697 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002698 pending_ice_restarts_.insert(content.name);
2699 }
2700 } else {
2701 // We retain all received candidates only if ICE is not restarted.
2702 // When ICE is restarted, all previous candidates belong to an old
2703 // generation and should not be kept.
2704 // TODO(deadbeef): This goes against the W3C spec which says the remote
2705 // description should only contain candidates from the last set remote
2706 // description plus any candidates added since then. We should remove
2707 // this once we're sure it won't break anything.
2708 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2709 old_remote_description, content.name, mutable_remote_description());
2710 }
2711 }
2712 }
2713
2714 if (session_error() != SessionError::kNone) {
2715 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2716 }
2717
2718 // Set the the ICE connection state to connecting since the connection may
2719 // become writable with peer reflexive candidates before any remote candidate
2720 // is signaled.
2721 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2722 // is to have a new signal the indicates a change in checking state from the
2723 // transport and expose a new checking() member from transport that can be
2724 // read to determine the current checking state. The existing SignalConnecting
2725 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002726 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002727 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002728 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2729 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2730 }
2731
deadbeefab9b2d12015-10-14 11:33:11 -07002732 // If setting the description decided our SSL role, allocate any necessary
2733 // SCTP sids.
2734 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002735 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002736 AllocateSctpSids(role);
2737 }
2738
Steve Antondcc3c022017-12-22 16:02:54 -08002739 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002740 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002741 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002742 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002743 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002744 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002745 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002746 const ContentInfo* content =
2747 FindMediaSectionForTransceiver(transceiver, remote_description());
2748 if (!content) {
2749 continue;
2750 }
2751 const MediaContentDescription* media_desc = content->media_description();
2752 RtpTransceiverDirection local_direction =
2753 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002754 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2755 // RTCSessionDescription: Set the associated remote streams given
2756 // transceiver.[[Receiver]], msids, addList, and removeList".
2757 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2758 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2759 std::vector<std::string> stream_ids;
2760 if (!media_desc->streams().empty()) {
2761 // The remote description has signaled the stream IDs.
2762 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002763 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002764 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2765 << " (" << GetStreamIdsString(stream_ids) << ").";
2766 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2767 stream_ids, &added_streams,
2768 &removed_streams);
2769 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2770 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2771 // and transceiver's current direction is neither sendrecv nor recvonly,
2772 // process the addition of a remote track for the media description.
2773 if (!transceiver->fired_direction() ||
2774 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2775 RTC_LOG(LS_INFO)
2776 << "Processing the addition of a remote track for MID="
2777 << content->name << ".";
2778 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002779 }
Steve Antondcc3c022017-12-22 16:02:54 -08002780 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002781 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002782 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2783 // removal of a remote track for the media description, given transceiver,
2784 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002785 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002786 (transceiver->fired_direction() &&
2787 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2788 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2789 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002790 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002791 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002792 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002793 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002794 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002795 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002796 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002797 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002798 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002799 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2800 if (transceiver->mid()) {
2801 auto dtls_transport =
2802 LookupDtlsTransportByMidInternal(*transceiver->mid());
2803 transceiver->internal()->sender_internal()->set_transport(
2804 dtls_transport);
2805 transceiver->internal()->receiver_internal()->set_transport(
2806 dtls_transport);
2807 }
Steve Antondcc3c022017-12-22 16:02:54 -08002808 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002809 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002810 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002811 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002812 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2813 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002814 transceiver->Stop();
2815 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002816 if (!content->rejected &&
2817 RtpTransceiverDirectionHasRecv(local_direction)) {
2818 // Set ssrc to 0 in the case of an unsignalled ssrc.
2819 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002820 if (!media_desc->streams().empty() &&
2821 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002822 ssrc = media_desc->streams()[0].first_ssrc();
2823 }
2824 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002825 }
Steve Antondcc3c022017-12-22 16:02:54 -08002826 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002827 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002828 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002829 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002830 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002831 observer->OnTrack(transceiver);
2832 observer->OnAddTrack(transceiver->receiver(),
2833 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002834 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002835 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002836 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002837 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002838 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002839 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002840 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002841 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002842 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002843 }
Steve Antondcc3c022017-12-22 16:02:54 -08002844 }
2845
Henrik Boströmfdb92012017-11-09 19:55:44 +01002846 const cricket::ContentInfo* audio_content =
2847 GetFirstAudioContent(remote_description()->description());
2848 const cricket::ContentInfo* video_content =
2849 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002850 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002851 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002852 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002853 GetFirstVideoContentDescription(remote_description()->description());
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002854 const cricket::RtpDataContentDescription* rtp_data_desc =
2855 GetFirstRtpDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002856
2857 // Check if the descriptions include streams, just in case the peer supports
2858 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002859 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002860 (audio_desc && !audio_desc->streams().empty()) ||
2861 (video_desc && !video_desc->streams().empty())) {
2862 remote_peer_supports_msid_ = true;
2863 }
deadbeefab9b2d12015-10-14 11:33:11 -07002864
2865 // We wait to signal new streams until we finish processing the description,
2866 // since only at that point will new streams have all their tracks.
2867 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2868
Steve Antondcc3c022017-12-22 16:02:54 -08002869 if (!IsUnifiedPlan()) {
2870 // TODO(steveanton): When removing RTP senders/receivers in response to a
2871 // rejected media section, there is some cleanup logic that expects the
2872 // voice/ video channel to still be set. But in this method the voice/video
2873 // channel would have been destroyed by the SetRemoteDescription caller
2874 // above so the cleanup that relies on them fails to run. The RemoveSenders
2875 // calls should be moved to right before the DestroyChannel calls to fix
2876 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002877
Steve Antondcc3c022017-12-22 16:02:54 -08002878 // Find all audio rtp streams and create corresponding remote AudioTracks
2879 // and MediaStreams.
2880 if (audio_content) {
2881 if (audio_content->rejected) {
2882 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2883 } else {
2884 bool default_audio_track_needed =
2885 !remote_peer_supports_msid_ &&
2886 RtpTransceiverDirectionHasSend(audio_desc->direction());
2887 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2888 default_audio_track_needed, audio_desc->type(),
2889 new_streams);
2890 }
deadbeeffaac4972015-11-12 15:33:07 -08002891 }
deadbeefab9b2d12015-10-14 11:33:11 -07002892
Steve Antondcc3c022017-12-22 16:02:54 -08002893 // Find all video rtp streams and create corresponding remote VideoTracks
2894 // and MediaStreams.
2895 if (video_content) {
2896 if (video_content->rejected) {
2897 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2898 } else {
2899 bool default_video_track_needed =
2900 !remote_peer_supports_msid_ &&
2901 RtpTransceiverDirectionHasSend(video_desc->direction());
2902 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2903 default_video_track_needed, video_desc->type(),
2904 new_streams);
2905 }
deadbeeffaac4972015-11-12 15:33:07 -08002906 }
deadbeefab9b2d12015-10-14 11:33:11 -07002907
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02002908 // If this is an RTP data transport, update the DataChannels with the
2909 // information from the remote peer.
2910 if (rtp_data_desc) {
2911 UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07002912 }
deadbeefab9b2d12015-10-14 11:33:11 -07002913
Steve Antondcc3c022017-12-22 16:02:54 -08002914 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002915 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002916 for (size_t i = 0; i < new_streams->count(); ++i) {
2917 MediaStreamInterface* new_stream = new_streams->at(i);
2918 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002919 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002920 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2921 }
deadbeefab9b2d12015-10-14 11:33:11 -07002922
Steve Antondcc3c022017-12-22 16:02:54 -08002923 UpdateEndedRemoteMediaStreams();
2924 }
deadbeefab9b2d12015-10-14 11:33:11 -07002925
Steve Anton8a006912017-12-04 15:25:56 -08002926 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002927}
2928
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002929void PeerConnection::SetAssociatedRemoteStreams(
2930 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2931 const std::vector<std::string>& stream_ids,
2932 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2933 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2934 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2935 for (const std::string& stream_id : stream_ids) {
2936 rtc::scoped_refptr<MediaStreamInterface> stream =
2937 remote_streams_->find(stream_id);
2938 if (!stream) {
2939 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2940 MediaStream::Create(stream_id));
2941 remote_streams_->AddStream(stream);
2942 added_streams->push_back(stream);
2943 }
2944 media_streams.push_back(stream);
2945 }
2946 // Special case: "a=msid" missing, use random stream ID.
2947 if (media_streams.empty() &&
2948 !(remote_description()->description()->msid_signaling() &
2949 cricket::kMsidSignalingMediaSection)) {
2950 if (!missing_msid_default_stream_) {
2951 missing_msid_default_stream_ = MediaStreamProxy::Create(
2952 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2953 added_streams->push_back(missing_msid_default_stream_);
2954 }
2955 media_streams.push_back(missing_msid_default_stream_);
2956 }
2957 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2958 receiver->streams();
2959 // SetStreams() will add/remove the receiver's track to/from the streams. This
2960 // differs from the spec - the spec uses an "addList" and "removeList" to
2961 // update the stream-track relationships in a later step. We do this earlier,
2962 // changing the order of things, but the end-result is the same.
2963 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2964 // instead. https://crbug.com/webrtc/9480
2965 receiver->SetStreams(media_streams);
2966 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2967}
2968
Steve Anton0f5400a2018-07-17 14:25:36 -07002969void PeerConnection::ProcessRemovalOfRemoteTrack(
2970 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2971 transceiver,
2972 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2973 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2974 RTC_DCHECK(transceiver->mid());
2975 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2976 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002977 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002978 transceiver->internal()->receiver_internal()->streams();
2979 // This will remove the remote track from the streams.
2980 transceiver->internal()->receiver_internal()->set_stream_ids({});
2981 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002982 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2983}
2984
2985void PeerConnection::RemoveRemoteStreamsIfEmpty(
2986 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2987 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2988 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2989 // streams, see if the stream was removed by checking if this was the last
2990 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002991 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002992 if (remote_stream->GetAudioTracks().empty() &&
2993 remote_stream->GetVideoTracks().empty()) {
2994 remote_streams_->RemoveStream(remote_stream);
2995 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002996 }
2997 }
2998}
2999
Steve Antondcc3c022017-12-22 16:02:54 -08003000RTCError PeerConnection::UpdateTransceiversAndDataChannels(
3001 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003002 const SessionDescriptionInterface& new_session,
3003 const SessionDescriptionInterface* old_local_description,
3004 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08003005 RTC_DCHECK(IsUnifiedPlan());
3006
Steve Anton7464fca2018-01-19 11:10:37 -08003007 const cricket::ContentGroup* bundle_group = nullptr;
3008 if (new_session.GetType() == SdpType::kOffer) {
3009 auto bundle_group_or_error =
3010 GetEarlyBundleGroup(*new_session.description());
3011 if (!bundle_group_or_error.ok()) {
3012 return bundle_group_or_error.MoveError();
3013 }
3014 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003015 }
Steve Antondcc3c022017-12-22 16:02:54 -08003016
Steve Antondcc3c022017-12-22 16:02:54 -08003017 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08003018 for (size_t i = 0; i < new_contents.size(); ++i) {
3019 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08003020 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08003021 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003022 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3023 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003024 const cricket::ContentInfo* old_local_content = nullptr;
3025 if (old_local_description &&
3026 i < old_local_description->description()->contents().size()) {
3027 old_local_content =
3028 &old_local_description->description()->contents()[i];
3029 }
3030 const cricket::ContentInfo* old_remote_content = nullptr;
3031 if (old_remote_description &&
3032 i < old_remote_description->description()->contents().size()) {
3033 old_remote_content =
3034 &old_remote_description->description()->contents()[i];
3035 }
Steve Antondcc3c022017-12-22 16:02:54 -08003036 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003037 AssociateTransceiver(source, new_session.GetType(), i, new_content,
3038 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08003039 if (!transceiver_or_error.ok()) {
3040 return transceiver_or_error.MoveError();
3041 }
3042 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08003043 RTCError error =
3044 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
3045 if (!error.ok()) {
3046 return error;
3047 }
3048 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003049 if (GetDataMid() && new_content.name != *GetDataMid()) {
3050 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07003051 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
3052 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08003053 continue;
3054 }
3055 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
3056 if (!error.ok()) {
3057 return error;
3058 }
Steve Antondcc3c022017-12-22 16:02:54 -08003059 } else {
3060 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3061 "Unknown section type.");
3062 }
3063 }
3064
3065 return RTCError::OK();
3066}
3067
3068RTCError PeerConnection::UpdateTransceiverChannel(
3069 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3070 transceiver,
3071 const cricket::ContentInfo& content,
3072 const cricket::ContentGroup* bundle_group) {
3073 RTC_DCHECK(IsUnifiedPlan());
3074 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003075 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003076 if (content.rejected) {
3077 if (channel) {
3078 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003079 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003080 }
3081 } else {
3082 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003083 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003084 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003085 } else {
Steve Anton69470252018-02-09 11:43:08 -08003086 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003087 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003088 }
3089 if (!channel) {
3090 LOG_AND_RETURN_ERROR(
3091 RTCErrorType::INTERNAL_ERROR,
3092 "Failed to create channel for mid=" + content.name);
3093 }
3094 transceiver->internal()->SetChannel(channel);
3095 }
3096 }
3097 return RTCError::OK();
3098}
3099
Steve Antonfa2260d2017-12-28 16:38:23 -08003100RTCError PeerConnection::UpdateDataChannel(
3101 cricket::ContentSource source,
3102 const cricket::ContentInfo& content,
3103 const cricket::ContentGroup* bundle_group) {
3104 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003105 // If data channels are disabled, ignore this media section. CreateAnswer
3106 // will take care of rejecting it.
3107 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003108 }
3109 if (content.rejected) {
3110 DestroyDataChannel();
3111 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003112 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003113 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003114 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3115 "Failed to create data channel.");
3116 }
3117 }
3118 if (source == cricket::CS_REMOTE) {
3119 const MediaContentDescription* data_desc = content.media_description();
3120 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3121 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3122 }
3123 }
3124 }
3125 return RTCError::OK();
3126}
3127
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003128// This method will extract any send encodings that were sent by the remote
3129// connection. This is currently only relevant for Simulcast scenario (where
3130// the number of layers may be communicated by the server).
3131static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3132 const MediaContentDescription& desc) {
3133 if (!desc.HasSimulcast()) {
3134 return {};
3135 }
3136 std::vector<RtpEncodingParameters> result;
3137 const SimulcastDescription& simulcast = desc.simulcast_description();
3138
3139 // This is a remote description, the parameters we are after should appear
3140 // as receive streams.
3141 for (const auto& alternatives : simulcast.receive_layers()) {
3142 RTC_DCHECK(!alternatives.empty());
3143 // There is currently no way to specify or choose from alternatives.
3144 // We will always use the first alternative, which is the most preferred.
3145 const SimulcastLayer& layer = alternatives[0];
3146 RtpEncodingParameters parameters;
3147 parameters.rid = layer.rid;
3148 parameters.active = !layer.is_paused;
3149 result.push_back(parameters);
3150 }
3151
3152 return result;
3153}
3154
3155static RTCError UpdateSimulcastLayerStatusInSender(
3156 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003157 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003158 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003159 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003160 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003161
3162 // The simulcast envelope cannot be changed, only the status of the streams.
3163 // So we will iterate over the send encodings rather than the layers.
3164 for (RtpEncodingParameters& encoding : parameters.encodings) {
3165 auto iter = std::find_if(layers.begin(), layers.end(),
3166 [&encoding](const SimulcastLayer& layer) {
3167 return layer.rid == encoding.rid;
3168 });
3169 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003170 if (iter == layers.end()) {
3171 disabled_layers.push_back(encoding.rid);
3172 continue;
3173 }
3174
3175 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003176 }
3177
Amit Hilbuch619b2942019-02-26 15:55:19 -08003178 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003179 if (result.ok()) {
3180 result = sender->DisableEncodingLayers(disabled_layers);
3181 }
3182
3183 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003184}
3185
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003186static bool SimulcastIsRejected(
3187 const ContentInfo* local_content,
3188 const MediaContentDescription& answer_media_desc) {
3189 bool simulcast_offered = local_content &&
3190 local_content->media_description() &&
3191 local_content->media_description()->HasSimulcast();
3192 bool simulcast_answered = answer_media_desc.HasSimulcast();
3193 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3194 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3195 return simulcast_offered && (!simulcast_answered || !rids_supported);
3196}
3197
Amit Hilbuch2297d332019-02-19 12:49:22 -08003198static RTCError DisableSimulcastInSender(
3199 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003200 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003201 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003202 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003203 return RTCError::OK();
3204 }
3205
Amit Hilbuch2297d332019-02-19 12:49:22 -08003206 std::vector<std::string> disabled_layers;
3207 std::transform(
3208 parameters.encodings.begin() + 1, parameters.encodings.end(),
3209 std::back_inserter(disabled_layers),
3210 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3211 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003212}
3213
Steve Antondcc3c022017-12-22 16:02:54 -08003214RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3215PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003216 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003217 size_t mline_index,
3218 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003219 const ContentInfo* old_local_content,
3220 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003221 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003222 // If this is an offer then the m= section might be recycled. If the m=
3223 // section is being recycled (defined as: rejected in the current local or
3224 // remote description and not rejected in new description), dissociate the
3225 // currently associated RtpTransceiver by setting its mid property to null,
3226 // and discard the mapping between the transceiver and its m= section index.
3227 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3228 old_remote_content)) {
3229 // We want to dissociate the transceiver that has the rejected mid.
3230 const std::string& old_mid =
3231 (old_local_content && old_local_content->rejected)
3232 ? old_local_content->name
3233 : old_remote_content->name;
3234 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003235 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003236 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3237 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003238 old_transceiver->internal()->set_mid(absl::nullopt);
3239 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003240 }
3241 }
3242 const MediaContentDescription* media_desc = content.media_description();
3243 auto transceiver = GetAssociatedTransceiver(content.name);
3244 if (source == cricket::CS_LOCAL) {
3245 // Find the RtpTransceiver that corresponds to this m= section, using the
3246 // mapping between transceivers and m= section indices established when
3247 // creating the offer.
3248 if (!transceiver) {
3249 transceiver = GetTransceiverByMLineIndex(mline_index);
3250 }
3251 if (!transceiver) {
3252 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3253 "Unknown transceiver");
3254 }
3255 } else {
3256 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3257 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3258 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003259 // When simulcast is requested, a transceiver cannot be associated because
3260 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003261 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003262 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3263 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003264 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3265 }
3266 // If no RtpTransceiver was found in the previous step, create one with a
3267 // recvonly direction.
3268 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003269 RTC_LOG(LS_INFO) << "Adding "
3270 << cricket::MediaTypeToString(media_desc->type())
3271 << " transceiver for MID=" << content.name
3272 << " at i=" << mline_index
3273 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003274 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003275 std::vector<RtpEncodingParameters> send_encodings =
3276 GetSendEncodingsFromRemoteDescription(*media_desc);
3277 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3278 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003279 std::string receiver_id;
3280 if (!media_desc->streams().empty()) {
3281 receiver_id = media_desc->streams()[0].id;
3282 } else {
3283 receiver_id = rtc::CreateRandomUuid();
3284 }
3285 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003286 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003287 transceiver->internal()->set_direction(
3288 RtpTransceiverDirection::kRecvOnly);
3289 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003290
3291 // Check if the offer indicated simulcast but the answer rejected it.
3292 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003293 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003294 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003295 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003296 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003297 if (!error.ok()) {
3298 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3299 return std::move(error);
3300 }
3301 }
Steve Antondcc3c022017-12-22 16:02:54 -08003302 }
3303 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003304 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003305 LOG_AND_RETURN_ERROR(
3306 RTCErrorType::INVALID_PARAMETER,
3307 "Transceiver type does not match media description type.");
3308 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003309 if (media_desc->HasSimulcast()) {
3310 std::vector<SimulcastLayer> layers =
3311 source == cricket::CS_LOCAL
3312 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3313 : media_desc->simulcast_description()
3314 .receive_layers()
3315 .GetAllLayers();
3316 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003317 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003318 if (!error.ok()) {
3319 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3320 return std::move(error);
3321 }
3322 }
Steve Antondcc3c022017-12-22 16:02:54 -08003323 // Associate the found or created RtpTransceiver with the m= section by
3324 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3325 // section, and establish a mapping between the transceiver and the index of
3326 // the m= section.
3327 transceiver->internal()->set_mid(content.name);
3328 transceiver->internal()->set_mline_index(mline_index);
3329 return std::move(transceiver);
3330}
3331
3332rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3333PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3334 RTC_DCHECK(IsUnifiedPlan());
3335 for (auto transceiver : transceivers_) {
3336 if (transceiver->mid() == mid) {
3337 return transceiver;
3338 }
3339 }
3340 return nullptr;
3341}
3342
3343rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3344PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3345 RTC_DCHECK(IsUnifiedPlan());
3346 for (auto transceiver : transceivers_) {
3347 if (transceiver->internal()->mline_index() == mline_index) {
3348 return transceiver;
3349 }
3350 }
3351 return nullptr;
3352}
3353
3354rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3355PeerConnection::FindAvailableTransceiverToReceive(
3356 cricket::MediaType media_type) const {
3357 RTC_DCHECK(IsUnifiedPlan());
3358 // From JSEP section 5.10 (Applying a Remote Description):
3359 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3360 // the same type that were added to the PeerConnection by addTrack and are not
3361 // associated with any m= section and are not stopped, find the first such
3362 // RtpTransceiver.
3363 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003364 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003365 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3366 !transceiver->stopped()) {
3367 return transceiver;
3368 }
3369 }
3370 return nullptr;
3371}
3372
Steve Antoned10bd92017-12-05 10:52:59 -08003373const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3374 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3375 transceiver,
3376 const SessionDescriptionInterface* sdesc) const {
3377 RTC_DCHECK(transceiver);
3378 RTC_DCHECK(sdesc);
3379 if (IsUnifiedPlan()) {
3380 if (!transceiver->internal()->mid()) {
3381 // This transceiver is not associated with a media section yet.
3382 return nullptr;
3383 }
3384 return sdesc->description()->GetContentByName(
3385 *transceiver->internal()->mid());
3386 } else {
3387 // Plan B only allows at most one audio and one video section, so use the
3388 // first media section of that type.
3389 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003390 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003391 }
3392}
3393
deadbeef46c73892016-11-16 19:42:04 -08003394PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003395 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003396 return configuration_;
3397}
3398
deadbeef293e9262017-01-11 12:28:30 -08003399bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3400 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003401 RTC_DCHECK_RUN_ON(signaling_thread());
3402 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003403 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003404 if (IsClosed()) {
3405 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3406 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3407 }
3408
Qingsi Wanga2d60672018-04-11 16:57:45 -07003409 // According to JSEP, after setLocalDescription, changing the candidate pool
3410 // size is not allowed, and changing the set of ICE servers will not result
3411 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003412 if (local_description() && configuration.ice_candidate_pool_size !=
3413 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003414 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3415 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003416 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003417 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003418
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003419 if (local_description() &&
3420 configuration.use_media_transport != configuration_.use_media_transport) {
3421 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3422 "SetLocalDescription.";
3423 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3424 }
3425
3426 if (remote_description() &&
3427 configuration.use_media_transport != configuration_.use_media_transport) {
3428 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3429 "SetRemoteDescription.";
3430 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3431 }
3432
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003433 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003434 configuration.use_media_transport_for_data_channels !=
3435 configuration_.use_media_transport_for_data_channels) {
3436 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3437 "after calling SetLocalDescription.";
3438 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3439 }
3440
3441 if (remote_description() &&
3442 configuration.use_media_transport_for_data_channels !=
3443 configuration_.use_media_transport_for_data_channels) {
3444 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3445 "after calling SetRemoteDescription.";
3446 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3447 }
3448
3449 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003450 configuration.crypto_options != configuration_.crypto_options) {
3451 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3452 "SetLocalDescription.";
3453 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3454 }
3455
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003456 if (local_description() && configuration.use_datagram_transport !=
3457 configuration_.use_datagram_transport) {
3458 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3459 "after calling SetLocalDescription.";
3460 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3461 }
3462
3463 if (remote_description() && configuration.use_datagram_transport !=
3464 configuration_.use_datagram_transport) {
3465 RTC_LOG(LS_ERROR) << "Can't change use_datagram_transport "
3466 "after calling SetRemoteDescription.";
3467 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3468 }
3469
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003470 if (configuration.use_media_transport_for_data_channels ||
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003471 configuration.use_media_transport ||
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003472 (configuration.use_datagram_transport &&
3473 *configuration.use_datagram_transport)) {
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003474 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3475 << "Media transport requires MaxBundle policy.";
3476 }
3477
deadbeef293e9262017-01-11 12:28:30 -08003478 // The simplest (and most future-compatible) way to tell if the config was
3479 // modified in an invalid way is to copy each property we do support
3480 // modifying, then use operator==. There are far more properties we don't
3481 // support modifying than those we do, and more could be added.
3482 RTCConfiguration modified_config = configuration_;
3483 modified_config.servers = configuration.servers;
3484 modified_config.type = configuration.type;
3485 modified_config.ice_candidate_pool_size =
3486 configuration.ice_candidate_pool_size;
3487 modified_config.prune_turn_ports = configuration.prune_turn_ports;
Qingsi Wangbca14852019-06-26 14:56:02 -07003488 modified_config.surface_ice_candidates_on_ice_transport_type_changed =
3489 configuration.surface_ice_candidates_on_ice_transport_type_changed;
skvladd1f5fda2017-02-03 16:54:05 -08003490 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003491 modified_config.ice_check_interval_strong_connectivity =
3492 configuration.ice_check_interval_strong_connectivity;
3493 modified_config.ice_check_interval_weak_connectivity =
3494 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003495 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3496 modified_config.ice_unwritable_min_checks =
3497 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003498 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003499 modified_config.stun_candidate_keepalive_interval =
3500 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003501 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003502 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003503 modified_config.active_reset_srtp_params =
3504 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003505 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003506 modified_config.use_media_transport_for_data_channels =
3507 configuration.use_media_transport_for_data_channels;
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003508 modified_config.use_datagram_transport = configuration.use_datagram_transport;
deadbeef293e9262017-01-11 12:28:30 -08003509 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003510 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003511 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3512 }
3513
Steve Anton038834f2017-07-14 15:59:59 -07003514 // Validate the modified configuration.
3515 RTCError validate_error = ValidateConfiguration(modified_config);
3516 if (!validate_error.ok()) {
3517 return SafeSetError(std::move(validate_error), error);
3518 }
3519
deadbeef293e9262017-01-11 12:28:30 -08003520 // Note that this isn't possible through chromium, since it's an unsigned
3521 // short in WebIDL.
3522 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003523 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003524 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3525 }
3526
3527 // Parse ICE servers before hopping to network thread.
3528 cricket::ServerAddresses stun_servers;
3529 std::vector<cricket::RelayServerConfig> turn_servers;
3530 RTCErrorType parse_error =
3531 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3532 if (parse_error != RTCErrorType::NONE) {
3533 return SafeSetError(parse_error, error);
3534 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003535 // Note if STUN or TURN servers were supplied.
3536 if (!stun_servers.empty()) {
3537 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3538 }
3539 if (!turn_servers.empty()) {
3540 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3541 }
deadbeef293e9262017-01-11 12:28:30 -08003542
3543 // In theory this shouldn't fail.
3544 if (!network_thread()->Invoke<bool>(
3545 RTC_FROM_HERE,
3546 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3547 stun_servers, turn_servers, modified_config.type,
3548 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003549 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003550 modified_config.turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02003551 modified_config.stun_candidate_keepalive_interval,
3552 static_cast<bool>(local_description())))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003553 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003554 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3555 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003556
deadbeefd1a38b52016-12-10 13:15:33 -08003557 // As described in JSEP, calling setConfiguration with new ICE servers or
3558 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3559 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003560 if (modified_config.servers != configuration_.servers ||
3561 modified_config.type != configuration_.type ||
3562 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003563 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003564 }
skvladd1f5fda2017-02-03 16:54:05 -08003565
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003566 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003567
3568 use_datagram_transport_ = datagram_transport_config_.enabled &&
3569 modified_config.use_datagram_transport.value_or(
3570 datagram_transport_config_.default_value);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003571 transport_controller_->SetMediaTransportSettings(
3572 modified_config.use_media_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07003573 modified_config.use_media_transport_for_data_channels,
Bjorn A Mellem5985a042019-06-28 14:19:38 -07003574 use_datagram_transport_);
skvladd1f5fda2017-02-03 16:54:05 -08003575
Zhi Huangb57e1692018-06-12 11:41:11 -07003576 if (configuration_.active_reset_srtp_params !=
3577 modified_config.active_reset_srtp_params) {
3578 transport_controller_->SetActiveResetSrtpParams(
3579 modified_config.active_reset_srtp_params);
3580 }
3581
deadbeef293e9262017-01-11 12:28:30 -08003582 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003583 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003584 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003585}
3586
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003587bool PeerConnection::AddIceCandidate(
3588 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003589 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003590 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003591 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003592 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003593 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003594 return false;
3595 }
Steve Antond25da372017-11-06 14:50:29 -08003596
3597 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003598 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003599 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003600 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003601 return false;
3602 }
3603
3604 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003605 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003606 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003607 return false;
3608 }
3609
3610 bool valid = false;
3611 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3612 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003613 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003614 return false;
3615 }
3616
3617 // Add this candidate to the remote session description.
3618 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003619 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003620 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003621 return false;
3622 }
3623
3624 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003625 bool result = UseCandidate(ice_candidate);
3626 if (result) {
3627 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Jeroen de Borstaf242c82019-04-24 13:13:48 -07003628 if (ice_candidate->candidate().address().IsUnresolvedIP()) {
3629 NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
3630 }
3631 if (ice_candidate->candidate().address().IsPrivateIP()) {
3632 NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
3633 }
Harald Alvestrand76829d72018-07-18 23:24:36 +02003634 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3635 } else {
3636 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3637 }
3638 return result;
Steve Antond25da372017-11-06 14:50:29 -08003639 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003640 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003641 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003642 return true;
3643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003644}
3645
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003646bool PeerConnection::RemoveIceCandidates(
3647 const std::vector<cricket::Candidate>& candidates) {
3648 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003649 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonc79268f2018-04-24 09:54:10 -07003650 if (IsClosed()) {
3651 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3652 return false;
3653 }
3654
Steve Antond25da372017-11-06 14:50:29 -08003655 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003656 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3657 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003658 return false;
3659 }
3660
3661 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003662 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003663 return false;
3664 }
3665
3666 size_t number_removed =
3667 mutable_remote_description()->RemoveCandidates(candidates);
3668 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003669 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003670 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003671 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003672 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003673 }
3674
3675 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003676 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3677 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003678 RTC_LOG(LS_ERROR)
3679 << "RemoveIceCandidates: Error when removing remote candidates: "
3680 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003681 }
3682 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003683}
3684
Niels Möller0c4f7be2018-05-07 14:01:37 +02003685RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003686 if (!worker_thread()->IsCurrent()) {
3687 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003688 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003689 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003690 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003691
Niels Möller0c4f7be2018-05-07 14:01:37 +02003692 const bool has_min = bitrate.min_bitrate_bps.has_value();
3693 const bool has_start = bitrate.start_bitrate_bps.has_value();
3694 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003695 if (has_min && *bitrate.min_bitrate_bps < 0) {
3696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3697 "min_bitrate_bps <= 0");
3698 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003699 if (has_start) {
3700 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003701 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003702 "start_bitrate_bps < min_bitrate_bps");
3703 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3705 "curent_bitrate_bps < 0");
3706 }
3707 }
3708 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003709 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003710 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003711 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003712 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3713 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3714 "max_bitrate_bps < min_bitrate_bps");
3715 } else if (*bitrate.max_bitrate_bps < 0) {
3716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3717 "max_bitrate_bps < 0");
3718 }
3719 }
3720
zstein4b979802017-06-02 14:37:37 -07003721 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003722 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003723
3724 return RTCError::OK();
3725}
3726
Alex Narest78609d52017-10-20 10:37:47 +02003727void PeerConnection::SetBitrateAllocationStrategy(
3728 std::unique_ptr<rtc::BitrateAllocationStrategy>
3729 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003730 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003731 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3732 // move-capture values in lambdas.
3733 struct Task {
3734 PeerConnection* const pc;
3735 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3736 void operator()() {
3737 RTC_DCHECK_RUN_ON(pc->worker_thread());
3738 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3739 }
3740 };
3741 worker_thread()->Invoke<void>(
3742 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003743 return;
3744 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003745 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003746 RTC_DCHECK(call_.get());
3747 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3748}
3749
henrika5f6bf242017-11-01 11:06:56 +01003750void PeerConnection::SetAudioPlayout(bool playout) {
3751 if (!worker_thread()->IsCurrent()) {
3752 worker_thread()->Invoke<void>(
3753 RTC_FROM_HERE,
3754 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3755 return;
3756 }
3757 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003758 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003759 audio_state->SetPlayout(playout);
3760}
3761
3762void PeerConnection::SetAudioRecording(bool recording) {
3763 if (!worker_thread()->IsCurrent()) {
3764 worker_thread()->Invoke<void>(
3765 RTC_FROM_HERE,
3766 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3767 return;
3768 }
3769 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003770 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003771 audio_state->SetRecording(recording);
3772}
3773
Steve Anton8c0f7a72017-10-03 10:03:10 -07003774std::unique_ptr<rtc::SSLCertificate>
3775PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003776 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3777 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003778 return nullptr;
3779 }
Steve Antonf25303e2018-10-16 15:23:31 -07003780 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003781}
3782
Zhi Huang70b820f2018-01-27 14:16:15 -08003783std::unique_ptr<rtc::SSLCertChain>
3784PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003785 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003786 auto audio_transceiver = GetFirstAudioTransceiver();
3787 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003788 return nullptr;
3789 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003790 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003791 audio_transceiver->internal()->channel()->transport_name());
3792}
3793
3794rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3795PeerConnection::GetFirstAudioTransceiver() const {
3796 for (auto transceiver : transceivers_) {
3797 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3798 return transceiver;
3799 }
3800 }
3801 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003802}
3803
Bjorn Tereliusde939432017-11-20 17:38:14 +01003804bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3805 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003806 // TODO(eladalon): In C++14, this can be done with a lambda.
3807 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003808 bool operator()() {
3809 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3810 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003811 PeerConnection* const pc;
3812 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003813 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003814 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003815 return worker_thread()->Invoke<bool>(
3816 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003817}
3818
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003819bool PeerConnection::StartRtcEventLog(
3820 std::unique_ptr<RtcEventLogOutput> output) {
Niels Möller695cf6a2019-05-13 12:27:23 +02003821 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3822 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3823 output_period_ms = 5000;
3824 }
3825 return StartRtcEventLog(std::move(output), output_period_ms);
Niels Möllerf00ca1a2019-05-10 11:33:12 +02003826}
3827
ivoc14d5dbe2016-07-04 07:06:55 -07003828void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003829 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003830 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3831}
3832
Harald Alvestrandad88c882018-11-28 16:47:46 +01003833rtc::scoped_refptr<DtlsTransportInterface>
3834PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003835 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandad88c882018-11-28 16:47:46 +01003836 return transport_controller_->LookupDtlsTransportByMid(mid);
3837}
3838
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003839rtc::scoped_refptr<DtlsTransport>
3840PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003841 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003842 return transport_controller_->LookupDtlsTransportByMid(mid);
3843}
3844
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003845rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3846 const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02003847 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003848 return sctp_transport_;
3849}
3850
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003851const SessionDescriptionInterface* PeerConnection::local_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003852 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003853 return pending_local_description_ ? pending_local_description_.get()
3854 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003855}
3856
3857const SessionDescriptionInterface* PeerConnection::remote_description() const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003858 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003859 return pending_remote_description_ ? pending_remote_description_.get()
3860 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003861}
3862
deadbeeffe4a8a42016-12-20 17:56:17 -08003863const SessionDescriptionInterface* PeerConnection::current_local_description()
3864 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003865 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003866 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003867}
3868
3869const SessionDescriptionInterface* PeerConnection::current_remote_description()
3870 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003871 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003872 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003873}
3874
3875const SessionDescriptionInterface* PeerConnection::pending_local_description()
3876 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003877 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003878 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003879}
3880
3881const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3882 const {
Karl Wiberg739506e2019-04-03 11:37:28 +02003883 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003884 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003885}
3886
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003887void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003888 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003889 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003890 // Update stats here so that we have the most recent stats for tracks and
3891 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003892 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003893
Steve Anton75737c02017-11-06 10:37:17 -08003894 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003895 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003896
Mirko Bonadei739baf02019-01-27 17:29:42 +01003897 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003898 transceiver->Stop();
3899 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003900
3901 // Ensure that all asynchronous stats requests are completed before destroying
3902 // the transport controller below.
3903 if (stats_collector_) {
3904 stats_collector_->WaitForPendingRequest();
3905 }
3906
3907 // Don't destroy BaseChannels until after stats has been cleaned up so that
3908 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003909 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003910
Qingsi Wang93a84392018-01-30 17:13:09 -08003911 // The event log is used in the transport controller, which must be outlived
3912 // by the former. CreateOffer by the peer connection is implemented
3913 // asynchronously and if the peer connection is closed without resetting the
3914 // WebRTC session description factory, the session description factory would
3915 // call the transport controller.
3916 webrtc_session_desc_factory_.reset();
3917 transport_controller_.reset();
3918
deadbeef42a42632017-03-10 15:18:00 -08003919 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003920 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3921 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003922
Steve Anton978b8762017-09-29 12:15:02 -07003923 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003924 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003925 call_.reset();
3926 // The event log must outlive call (and any other object that uses it).
3927 event_log_.reset();
3928 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003929 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003930 // The .h file says that observer can be discarded after close() returns.
3931 // Make sure this is true.
3932 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003933}
3934
Steve Antonad182762018-09-05 20:22:40 +00003935void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003936 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003937 switch (msg->message_id) {
3938 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3939 SetSessionDescriptionMsg* param =
3940 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3941 param->observer->OnSuccess();
3942 delete param;
3943 break;
3944 }
3945 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3946 SetSessionDescriptionMsg* param =
3947 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3948 param->observer->OnFailure(std::move(param->error));
3949 delete param;
3950 break;
3951 }
3952 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3953 CreateSessionDescriptionMsg* param =
3954 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3955 param->observer->OnFailure(std::move(param->error));
3956 delete param;
3957 break;
3958 }
3959 case MSG_GETSTATS: {
3960 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3961 StatsReports reports;
3962 stats_->GetStats(param->track, &reports);
3963 param->observer->OnComplete(reports);
3964 delete param;
3965 break;
3966 }
3967 case MSG_FREE_DATACHANNELS: {
3968 sctp_data_channels_to_free_.clear();
3969 break;
3970 }
3971 case MSG_REPORT_USAGE_PATTERN: {
3972 ReportUsagePattern();
3973 break;
3974 }
3975 default:
3976 RTC_NOTREACHED() << "Not implemented";
3977 break;
3978 }
3979}
3980
Steve Antonafb0bb72018-02-20 11:35:37 -08003981cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3982 RTC_DCHECK(!IsUnifiedPlan());
3983 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3984 GetAudioTransceiver()->internal()->channel());
3985 if (voice_channel) {
3986 return voice_channel->media_channel();
3987 } else {
3988 return nullptr;
3989 }
3990}
3991
3992cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3993 RTC_DCHECK(!IsUnifiedPlan());
3994 auto* video_channel = static_cast<cricket::VideoChannel*>(
3995 GetVideoTransceiver()->internal()->channel());
3996 if (video_channel) {
3997 return video_channel->media_channel();
3998 } else {
3999 return nullptr;
4000 }
4001}
4002
Steve Anton4171afb2017-11-20 10:20:22 -08004003void PeerConnection::CreateAudioReceiver(
4004 MediaStreamInterface* stream,
4005 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004006 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4007 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004008 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4009 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004010 auto* audio_receiver = new AudioRtpReceiver(
4011 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004012 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004013 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4014 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4015 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004016 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004017 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004018 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004019}
4020
Steve Anton4171afb2017-11-20 10:20:22 -08004021void PeerConnection::CreateVideoReceiver(
4022 MediaStreamInterface* stream,
4023 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01004024 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
4025 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02004026 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
4027 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08004028 auto* video_receiver = new VideoRtpReceiver(
4029 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004030 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08004031 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
4032 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
4033 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08004034 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01004035 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004036 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004037}
4038
deadbeef70ab1a12015-09-28 16:53:55 -07004039// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
4040// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07004041rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08004042 const RtpSenderInfo& remote_sender_info) {
4043 auto receiver = FindReceiverById(remote_sender_info.sender_id);
4044 if (!receiver) {
4045 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
4046 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07004047 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004048 }
Steve Anton4171afb2017-11-20 10:20:22 -08004049 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4050 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
4051 } else {
4052 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
4053 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004054 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004055}
4056
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004057void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
4058 MediaStreamInterface* stream) {
4059 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004060 RTC_DCHECK(track);
4061 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004062 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004063 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004064 // We already have a sender for this track, so just change the stream_id
4065 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004066 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004067 return;
4068 }
4069
4070 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004071 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004072 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004073 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004074 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004075 // If the sender has already been configured in SDP, we call SetSsrc,
4076 // which will connect the sender to the underlying transport. This can
4077 // occur if a local session description that contains the ID of the sender
4078 // is set before AddStream is called. It can also occur if the local
4079 // session description is not changed and RemoveStream is called, and
4080 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08004081 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004082 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004083 if (sender_info) {
4084 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004085 }
4086}
4087
4088// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
4089// indefinitely, when we have unified plan SDP.
4090void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
4091 MediaStreamInterface* stream) {
4092 RTC_DCHECK(!IsClosed());
4093 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004094 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004095 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4096 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004097 return;
4098 }
Steve Anton4171afb2017-11-20 10:20:22 -08004099 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004100}
4101
4102void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4103 MediaStreamInterface* stream) {
4104 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004105 RTC_DCHECK(track);
4106 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004107 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004108 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004109 // We already have a sender for this track, so just change the stream_id
4110 // so that it's correct in the next call to CreateOffer.
Henrik Andreasssoncc189172019-05-20 09:01:38 +00004111 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004112 return;
4113 }
4114
4115 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004116 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004117 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004118 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004119 GetVideoTransceiver()->internal()->AddSender(new_sender);
4120 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004121 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004122 if (sender_info) {
4123 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004124 }
4125}
4126
4127void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4128 MediaStreamInterface* stream) {
4129 RTC_DCHECK(!IsClosed());
4130 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004131 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004132 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4133 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004134 return;
4135 }
Steve Anton4171afb2017-11-20 10:20:22 -08004136 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004137}
4138
Steve Antonba818672017-11-06 10:21:57 -08004139void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004140 if (ice_connection_state_ == new_state) {
4141 return;
4142 }
4143
deadbeefcbecd352015-09-23 11:50:27 -07004144 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004145 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004146 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004147 return;
4148 }
Steve Antonba818672017-11-06 10:21:57 -08004149
Mirko Bonadei675513b2017-11-09 11:09:25 +01004150 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4151 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004152 RTC_DCHECK(ice_connection_state_ !=
4153 PeerConnectionInterface::kIceConnectionClosed);
4154
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004155 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004156 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004157}
4158
Alex Loiko9289eda2018-11-23 16:18:59 +00004159void PeerConnection::SetStandardizedIceConnectionState(
4160 PeerConnectionInterface::IceConnectionState new_state) {
Qingsi Wang36e31472019-05-29 11:37:26 -07004161 if (standardized_ice_connection_state_ == new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004162 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004163 }
4164
4165 if (IsClosed()) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004166 return;
Qingsi Wang36e31472019-05-29 11:37:26 -07004167 }
4168
4169 RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
4170 << standardized_ice_connection_state_ << " => " << new_state;
4171
Alex Loiko9289eda2018-11-23 16:18:59 +00004172 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004173 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004174}
4175
Jonas Olsson635474e2018-10-18 15:58:17 +02004176void PeerConnection::SetConnectionState(
4177 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004178 if (connection_state_ == new_state)
4179 return;
4180 if (IsClosed())
4181 return;
4182 connection_state_ = new_state;
4183 Observer()->OnConnectionChange(new_state);
4184}
4185
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004186void PeerConnection::OnIceGatheringChange(
4187 PeerConnectionInterface::IceGatheringState new_state) {
4188 if (IsClosed()) {
4189 return;
4190 }
4191 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004192 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004193}
4194
jbauch81bf7b02017-03-25 08:31:12 -07004195void PeerConnection::OnIceCandidate(
4196 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004197 if (IsClosed()) {
4198 return;
4199 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004200 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004201 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4202 candidate->candidate().address().IsPrivateIP()) {
4203 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4204 }
Jeroen de Borstaf242c82019-04-24 13:13:48 -07004205 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4206 candidate->candidate().address().IsUnresolvedIP()) {
4207 NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
4208 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004209 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004210}
4211
Eldar Relloda13ea22019-06-01 12:23:43 +03004212void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
4213 const std::string& url,
4214 int error_code,
4215 const std::string& error_text) {
4216 if (IsClosed()) {
4217 return;
4218 }
4219 Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
4220}
4221
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004222void PeerConnection::OnIceCandidatesRemoved(
4223 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004224 if (IsClosed()) {
4225 return;
4226 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004227 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004228}
4229
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004230void PeerConnection::ChangeSignalingState(
4231 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004232 if (signaling_state_ == signaling_state) {
4233 return;
4234 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004235 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4236 << GetSignalingStateString(signaling_state_)
4237 << " New state: "
4238 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004239 signaling_state_ = signaling_state;
4240 if (signaling_state == kClosed) {
4241 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004242 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004243 standardized_ice_connection_state_ =
4244 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004245 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4246 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004247 if (ice_gathering_state_ != kIceGatheringComplete) {
4248 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004249 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004250 }
4251 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004252 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004253}
4254
deadbeefeb459812015-12-15 19:24:43 -08004255void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4256 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004257 if (IsClosed()) {
4258 return;
4259 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004260 AddAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004261 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004262}
4263
deadbeefeb459812015-12-15 19:24:43 -08004264void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4265 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004266 if (IsClosed()) {
4267 return;
4268 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004269 RemoveAudioTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004270 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004271}
4272
4273void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4274 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004275 if (IsClosed()) {
4276 return;
4277 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004278 AddVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004279 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004280}
4281
4282void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4283 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004284 if (IsClosed()) {
4285 return;
4286 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004287 RemoveVideoTrack(track, stream);
Guido Urdaneta70c2db12019-04-16 12:24:14 +02004288 UpdateNegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004289}
4290
Henrik Boström31638672017-11-23 17:48:32 +01004291void PeerConnection::PostSetSessionDescriptionSuccess(
4292 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004293 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4294 signaling_thread()->Post(RTC_FROM_HERE, this,
4295 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004296}
4297
deadbeefab9b2d12015-10-14 11:33:11 -07004298void PeerConnection::PostSetSessionDescriptionFailure(
4299 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004300 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004301 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004302 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4303 msg->error = std::move(error);
4304 signaling_thread()->Post(RTC_FROM_HERE, this,
4305 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004306}
4307
4308void PeerConnection::PostCreateSessionDescriptionFailure(
4309 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004310 RTCError error) {
4311 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004312 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4313 msg->error = std::move(error);
4314 signaling_thread()->Post(RTC_FROM_HERE, this,
4315 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004316}
4317
zhihuang1c378ed2017-08-17 14:10:50 -07004318void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004319 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004320 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004321 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004322
Steve Antondcc3c022017-12-22 16:02:54 -08004323 if (IsUnifiedPlan()) {
4324 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4325 } else {
4326 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4327 }
4328
Steve Antonfa2260d2017-12-28 16:38:23 -08004329 // Intentionally unset the data channel type for RTP data channel with the
4330 // second condition. Otherwise the RTP data channels would be successfully
4331 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4332 // when building with chromium. We want to leave RTP data channels broken, so
4333 // people won't try to use them.
4334 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4335 session_options->data_channel_type = data_channel_type();
4336 }
4337
Steve Antondcc3c022017-12-22 16:02:54 -08004338 // Apply ICE restart flag and renomination flag.
4339 for (auto& options : session_options->media_description_options) {
4340 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4341 options.transport_options.enable_ice_renomination =
4342 configuration_.enable_ice_renomination;
4343 }
4344
4345 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004346 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004347 session_options->pooled_ice_credentials =
4348 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4349 RTC_FROM_HERE,
4350 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4351 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004352 session_options->offer_extmap_allow_mixed =
4353 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004354
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004355 if (configuration_.use_media_transport ||
4356 configuration_.use_media_transport_for_data_channels) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004357 session_options->media_transport_settings =
4358 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4359 }
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004360
4361 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004362 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004363 for (auto& options : session_options->media_description_options) {
4364 options.transport_options.opaque_parameters =
4365 transport_controller_->GetTransportParameters(options.mid);
4366 }
4367 }
4368
Harald Alvestrand4aa11922019-05-14 22:00:01 +02004369 // Allow fallback for using obsolete SCTP syntax.
4370 // Note that the default in |session_options| is true, while
4371 // the default in |options| is false.
4372 session_options->use_obsolete_sctp_sdp =
4373 offer_answer_options.use_obsolete_sctp_sdp;
Steve Antondcc3c022017-12-22 16:02:54 -08004374}
4375
4376void PeerConnection::GetOptionsForPlanBOffer(
4377 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4378 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004379 // Figure out transceiver directional preferences.
4380 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4381 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4382
4383 // By default, generate sendrecv/recvonly m= sections.
4384 bool recv_audio = true;
4385 bool recv_video = true;
4386
4387 // By default, only offer a new m= section if we have media to send with it.
4388 bool offer_new_audio_description = send_audio;
4389 bool offer_new_video_description = send_video;
4390 bool offer_new_data_description = HasDataChannels();
4391
4392 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004393 if (offer_answer_options.offer_to_receive_audio !=
4394 RTCOfferAnswerOptions::kUndefined) {
4395 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004396 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004397 offer_new_audio_description ||
4398 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004399 }
Steve Antondcc3c022017-12-22 16:02:54 -08004400 if (offer_answer_options.offer_to_receive_video !=
4401 RTCOfferAnswerOptions::kUndefined) {
4402 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004403 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004404 offer_new_video_description ||
4405 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004406 }
4407
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004408 absl::optional<size_t> audio_index;
4409 absl::optional<size_t> video_index;
4410 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004411 // If a current description exists, generate m= sections in the same order,
4412 // using the first audio/video/data section that appears and rejecting
4413 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004414 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004415 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004416 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004417 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4418 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4419 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004420 }
4421
zhihuang1c378ed2017-08-17 14:10:50 -07004422 // Add audio/video/data m= sections to the end if needed.
4423 if (!audio_index && offer_new_audio_description) {
4424 session_options->media_description_options.push_back(
4425 cricket::MediaDescriptionOptions(
4426 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004427 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4428 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004429 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004430 }
zhihuang1c378ed2017-08-17 14:10:50 -07004431 if (!video_index && offer_new_video_description) {
4432 session_options->media_description_options.push_back(
4433 cricket::MediaDescriptionOptions(
4434 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004435 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4436 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004437 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004438 }
zhihuang1c378ed2017-08-17 14:10:50 -07004439 if (!data_index && offer_new_data_description) {
4440 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004441 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004442 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004443 }
4444
4445 cricket::MediaDescriptionOptions* audio_media_description_options =
4446 !audio_index ? nullptr
4447 : &session_options->media_description_options[*audio_index];
4448 cricket::MediaDescriptionOptions* video_media_description_options =
4449 !video_index ? nullptr
4450 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004451
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004452 AddPlanBRtpSenderOptions(GetSendersInternal(),
4453 audio_media_description_options,
4454 video_media_description_options,
4455 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004456}
4457
Steve Antondcc3c022017-12-22 16:02:54 -08004458static cricket::MediaDescriptionOptions
4459GetMediaDescriptionOptionsForTransceiver(
4460 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4461 transceiver,
4462 const std::string& mid) {
4463 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004464 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004465 transceiver->stopped());
Florent Castelli2d9d82e2019-04-23 19:25:51 +02004466 media_description_options.codec_preferences =
4467 transceiver->codec_preferences();
Steve Anton5f94aa22018-02-01 10:58:30 -08004468 // This behavior is specified in JSEP. The gist is that:
4469 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4470 // sendrecv.
4471 // 2. If the MSID is included, then it must be included in any subsequent
4472 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004473 if (transceiver->stopped() ||
4474 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4475 !transceiver->internal()->has_ever_been_used_to_send())) {
4476 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004477 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004478
4479 cricket::SenderOptions sender_options;
4480 sender_options.track_id = transceiver->sender()->id();
4481 sender_options.stream_ids = transceiver->sender()->stream_ids();
4482
4483 // The following sets up RIDs and Simulcast.
4484 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004485 RtpParameters send_parameters =
4486 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004487 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4488 send_parameters.encodings.end(),
4489 [](const RtpEncodingParameters& encoding) {
4490 return !encoding.rid.empty();
4491 });
4492
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004493 std::vector<RidDescription> send_rids;
4494 SimulcastLayerList send_layers;
4495 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4496 if (encoding.rid.empty()) {
4497 continue;
4498 }
4499 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4500 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4501 }
4502
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004503 if (has_rids) {
4504 sender_options.rids = send_rids;
4505 }
4506
4507 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004508 // When RIDs are configured, we must set num_sim_layers to 0 to.
4509 // Otherwise, num_sim_layers must be 1 because either there is no
4510 // simulcast, or simulcast is acheived by munging the SDP.
4511 sender_options.num_sim_layers = has_rids ? 0 : 1;
4512 media_description_options.sender_options.push_back(sender_options);
4513
Steve Antondcc3c022017-12-22 16:02:54 -08004514 return media_description_options;
4515}
4516
Steve Anton5c72e712018-12-10 14:25:30 -08004517// Returns the ContentInfo at mline index |i|, or null if none exists.
4518static const ContentInfo* GetContentByIndex(
4519 const SessionDescriptionInterface* sdesc,
4520 size_t i) {
4521 if (!sdesc) {
4522 return nullptr;
4523 }
4524 const ContentInfos& contents = sdesc->description()->contents();
4525 return (i < contents.size() ? &contents[i] : nullptr);
4526}
4527
Steve Antondcc3c022017-12-22 16:02:54 -08004528void PeerConnection::GetOptionsForUnifiedPlanOffer(
4529 const RTCOfferAnswerOptions& offer_answer_options,
4530 cricket::MediaSessionOptions* session_options) {
4531 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4532 // Offers) and 5.2.2 (Subsequent Offers).
4533 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
Harald Alvestrand1716d392019-06-03 20:35:45 +02004534 const ContentInfos no_infos;
Steve Antondcc3c022017-12-22 16:02:54 -08004535 const ContentInfos& local_contents =
4536 (local_description() ? local_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004537 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004538 const ContentInfos& remote_contents =
4539 (remote_description() ? remote_description()->description()->contents()
Harald Alvestrand1716d392019-06-03 20:35:45 +02004540 : no_infos);
Steve Antondcc3c022017-12-22 16:02:54 -08004541 // The mline indices that can be recycled. New transceivers should reuse these
4542 // slots first.
4543 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004544 // First, go through each media section that exists in either the local or
4545 // remote description and generate a media section in this offer for the
4546 // associated transceiver. If a media section can be recycled, generate a
4547 // default, rejected media section here that can be later overwritten.
4548 for (size_t i = 0;
4549 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4550 // Either |local_content| or |remote_content| is non-null.
4551 const ContentInfo* local_content =
4552 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004553 const ContentInfo* current_local_content =
4554 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004555 const ContentInfo* remote_content =
4556 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004557 const ContentInfo* current_remote_content =
4558 GetContentByIndex(current_remote_description(), i);
4559 bool had_been_rejected =
4560 (current_local_content && current_local_content->rejected) ||
4561 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004562 const std::string& mid =
4563 (local_content ? local_content->name : remote_content->name);
4564 cricket::MediaType media_type =
4565 (local_content ? local_content->media_description()->type()
4566 : remote_content->media_description()->type());
4567 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4568 media_type == cricket::MEDIA_TYPE_VIDEO) {
4569 auto transceiver = GetAssociatedTransceiver(mid);
4570 RTC_CHECK(transceiver);
4571 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004572 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004573 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004574 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004575 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4576 RtpTransceiverDirection::kInactive,
4577 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004578 recycleable_mline_indices.push(i);
4579 } else {
4580 session_options->media_description_options.push_back(
4581 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4582 // CreateOffer shouldn't really cause any state changes in
4583 // PeerConnection, but we need a way to match new transceivers to new
4584 // media sections in SetLocalDescription and JSEP specifies this is done
4585 // by recording the index of the media section generated for the
4586 // transceiver in the offer.
4587 transceiver->internal()->set_mline_index(i);
4588 }
4589 } else {
4590 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004591 RTC_CHECK(GetDataMid());
4592 if (had_been_rejected || mid != *GetDataMid()) {
4593 session_options->media_description_options.push_back(
4594 GetMediaDescriptionOptionsForRejectedData(mid));
4595 } else {
4596 session_options->media_description_options.push_back(
4597 GetMediaDescriptionOptionsForActiveData(mid));
4598 }
Steve Antondcc3c022017-12-22 16:02:54 -08004599 }
4600 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004601
Steve Antondcc3c022017-12-22 16:02:54 -08004602 // Next, look for transceivers that are newly added (that is, are not stopped
4603 // and not associated). Reuse media sections marked as recyclable first,
4604 // otherwise append to the end of the offer. New media sections should be
4605 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004606 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004607 if (transceiver->mid() || transceiver->stopped()) {
4608 continue;
4609 }
4610 size_t mline_index;
4611 if (!recycleable_mline_indices.empty()) {
4612 mline_index = recycleable_mline_indices.front();
4613 recycleable_mline_indices.pop();
4614 session_options->media_description_options[mline_index] =
4615 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004616 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004617 } else {
4618 mline_index = session_options->media_description_options.size();
4619 session_options->media_description_options.push_back(
4620 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004621 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004622 }
4623 // See comment above for why CreateOffer changes the transceiver's state.
4624 transceiver->internal()->set_mline_index(mline_index);
4625 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004626 // Lastly, add a m-section if we have local data channels and an m section
4627 // does not already exist.
4628 if (!GetDataMid() && HasDataChannels()) {
4629 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004630 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004631 }
Steve Antondcc3c022017-12-22 16:02:54 -08004632}
4633
4634void PeerConnection::GetOptionsForAnswer(
4635 const RTCOfferAnswerOptions& offer_answer_options,
4636 cricket::MediaSessionOptions* session_options) {
4637 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4638
4639 if (IsUnifiedPlan()) {
4640 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4641 } else {
4642 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4643 }
4644
Steve Antonfa2260d2017-12-28 16:38:23 -08004645 // Intentionally unset the data channel type for RTP data channel. Otherwise
4646 // the RTP data channels would be successfully negotiated by default and the
4647 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4648 // We want to leave RTP data channels broken, so people won't try to use them.
4649 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4650 session_options->data_channel_type = data_channel_type();
4651 }
4652
Steve Antondcc3c022017-12-22 16:02:54 -08004653 // Apply ICE renomination flag.
4654 for (auto& options : session_options->media_description_options) {
4655 options.transport_options.enable_ice_renomination =
4656 configuration_.enable_ice_renomination;
4657 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004658
4659 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004660 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004661 session_options->pooled_ice_credentials =
4662 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4663 RTC_FROM_HERE,
4664 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4665 port_allocator_.get()));
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004666
4667 // If datagram transport is in use, add opaque transport parameters.
Bjorn A Mellem5985a042019-06-28 14:19:38 -07004668 if (use_datagram_transport_) {
Bjorn A Mellemc85ebbe2019-06-07 10:28:06 -07004669 for (auto& options : session_options->media_description_options) {
4670 options.transport_options.opaque_parameters =
4671 transport_controller_->GetTransportParameters(options.mid);
4672 }
4673 }
deadbeefab9b2d12015-10-14 11:33:11 -07004674}
4675
Steve Antondcc3c022017-12-22 16:02:54 -08004676void PeerConnection::GetOptionsForPlanBAnswer(
4677 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004678 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004679 // Figure out transceiver directional preferences.
4680 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4681 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4682
4683 // By default, generate sendrecv/recvonly m= sections. The direction is also
4684 // restricted by the direction in the offer.
4685 bool recv_audio = true;
4686 bool recv_video = true;
4687
4688 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004689 if (offer_answer_options.offer_to_receive_audio !=
4690 RTCOfferAnswerOptions::kUndefined) {
4691 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004692 }
Steve Antondcc3c022017-12-22 16:02:54 -08004693 if (offer_answer_options.offer_to_receive_video !=
4694 RTCOfferAnswerOptions::kUndefined) {
4695 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004696 }
4697
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004698 absl::optional<size_t> audio_index;
4699 absl::optional<size_t> video_index;
4700 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004701
4702 // Generate m= sections that match those in the offer.
4703 // Note that mediasession.cc will handle intersection our preferred
4704 // direction with the offered direction.
4705 GenerateMediaDescriptionOptions(
4706 remote_description(),
4707 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4708 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4709 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004710
4711 cricket::MediaDescriptionOptions* audio_media_description_options =
4712 !audio_index ? nullptr
4713 : &session_options->media_description_options[*audio_index];
4714 cricket::MediaDescriptionOptions* video_media_description_options =
4715 !video_index ? nullptr
4716 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004717
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004718 AddPlanBRtpSenderOptions(GetSendersInternal(),
4719 audio_media_description_options,
4720 video_media_description_options,
4721 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004722}
zhihuangaf388472016-11-02 16:49:48 -07004723
Steve Antondcc3c022017-12-22 16:02:54 -08004724void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4725 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4726 cricket::MediaSessionOptions* session_options) {
4727 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4728 // Answers) and 5.3.2 (Subsequent Answers).
4729 RTC_DCHECK(remote_description());
4730 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4731 for (const ContentInfo& content :
4732 remote_description()->description()->contents()) {
4733 cricket::MediaType media_type = content.media_description()->type();
4734 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4735 media_type == cricket::MEDIA_TYPE_VIDEO) {
4736 auto transceiver = GetAssociatedTransceiver(content.name);
4737 RTC_CHECK(transceiver);
4738 session_options->media_description_options.push_back(
4739 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4740 } else {
4741 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004742 // Reject all data sections if data channels are disabled.
4743 // Reject a data section if it has already been rejected.
4744 // Reject all data sections except for the first one.
4745 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4746 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004747 session_options->media_description_options.push_back(
4748 GetMediaDescriptionOptionsForRejectedData(content.name));
4749 } else {
4750 session_options->media_description_options.push_back(
4751 GetMediaDescriptionOptionsForActiveData(content.name));
4752 }
Steve Antondcc3c022017-12-22 16:02:54 -08004753 }
4754 }
htaa2a49d92016-03-04 02:51:39 -08004755}
4756
zhihuang1c378ed2017-08-17 14:10:50 -07004757void PeerConnection::GenerateMediaDescriptionOptions(
4758 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004759 RtpTransceiverDirection audio_direction,
4760 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004761 absl::optional<size_t>* audio_index,
4762 absl::optional<size_t>* video_index,
4763 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004764 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004765 for (const cricket::ContentInfo& content :
4766 session_desc->description()->contents()) {
4767 if (IsAudioContent(&content)) {
4768 // If we already have an audio m= section, reject this extra one.
4769 if (*audio_index) {
4770 session_options->media_description_options.push_back(
4771 cricket::MediaDescriptionOptions(
4772 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004773 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004774 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004775 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004776 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004777 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4778 content.name, audio_direction,
4779 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004780 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004781 }
4782 } else if (IsVideoContent(&content)) {
4783 // If we already have an video m= section, reject this extra one.
4784 if (*video_index) {
4785 session_options->media_description_options.push_back(
4786 cricket::MediaDescriptionOptions(
4787 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004788 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004789 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004790 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004791 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004792 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4793 content.name, video_direction,
4794 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004795 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004796 }
4797 } else {
4798 RTC_DCHECK(IsDataContent(&content));
4799 // If we already have an data m= section, reject this extra one.
4800 if (*data_index) {
4801 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004802 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004803 } else {
4804 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004805 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004806 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004807 }
4808 }
htaa2a49d92016-03-04 02:51:39 -08004809 }
deadbeefab9b2d12015-10-14 11:33:11 -07004810}
4811
Steve Antonfa2260d2017-12-28 16:38:23 -08004812cricket::MediaDescriptionOptions
4813PeerConnection::GetMediaDescriptionOptionsForActiveData(
4814 const std::string& mid) const {
4815 // Direction for data sections is meaningless, but legacy endpoints might
4816 // expect sendrecv.
4817 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4818 RtpTransceiverDirection::kSendRecv,
4819 /*stopped=*/false);
4820 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4821 return options;
4822}
4823
4824cricket::MediaDescriptionOptions
4825PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4826 const std::string& mid) const {
4827 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4828 RtpTransceiverDirection::kInactive,
4829 /*stopped=*/true);
4830 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4831 return options;
4832}
4833
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004834absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004835 switch (data_channel_type_) {
4836 case cricket::DCT_RTP:
4837 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004838 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004839 }
4840 return rtp_data_channel_->content_name();
4841 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004842 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004843 case cricket::DCT_MEDIA_TRANSPORT:
4844 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004845 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004846 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004847 }
4848}
4849
Steve Anton4171afb2017-11-20 10:20:22 -08004850void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4851 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4852 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004853 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004854}
4855
Steve Anton4171afb2017-11-20 10:20:22 -08004856void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004857 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004858 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004859 cricket::MediaType media_type,
4860 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004861 RTC_DCHECK(!IsUnifiedPlan());
4862
Steve Anton4171afb2017-11-20 10:20:22 -08004863 std::vector<RtpSenderInfo>* current_senders =
4864 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004865
Steve Anton4171afb2017-11-20 10:20:22 -08004866 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004867 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004868 for (auto sender_it = current_senders->begin();
4869 sender_it != current_senders->end();
4870 /* incremented manually */) {
4871 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004872 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004873 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004874 std::string params_stream_id;
4875 if (params) {
4876 params_stream_id =
4877 (!params->first_stream_id().empty() ? params->first_stream_id()
4878 : kDefaultStreamId);
4879 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004880 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004881 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004882 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004883 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004884 sender_exists) {
4885 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004886 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004887 OnRemoteSenderRemoved(info, media_type);
4888 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004889 }
4890 }
4891
Steve Anton4171afb2017-11-20 10:20:22 -08004892 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004893 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004894 if (!params.has_ssrcs()) {
4895 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4896 // sender, this means it is coming from a Unified Plan endpoint,so we just
4897 // create a default.
4898 default_sender_needed = true;
4899 break;
4900 }
4901
Seth Hampson845e8782018-03-02 11:34:10 -08004902 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004903 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004904 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4905 // not supported in Plan B, we just take the first here and create the
4906 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004907 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004908 (!params.first_stream_id().empty() ? params.first_stream_id()
4909 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004910 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004911 uint32_t ssrc = params.first_ssrc();
4912
4913 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004914 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004915 if (!stream) {
4916 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004917 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004918 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004919 remote_streams_->AddStream(stream);
4920 new_streams->AddStream(stream);
4921 }
4922
Steve Anton4171afb2017-11-20 10:20:22 -08004923 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004924 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004925 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004926 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004927 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004928 }
4929 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004930
Steve Anton4171afb2017-11-20 10:20:22 -08004931 // Add default sender if necessary.
4932 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004933 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004934 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004935 if (!default_stream) {
4936 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004937 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004938 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004939 remote_streams_->AddStream(default_stream);
4940 new_streams->AddStream(default_stream);
4941 }
Steve Anton4171afb2017-11-20 10:20:22 -08004942 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4943 ? kDefaultAudioSenderId
4944 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004945 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004946 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004947 if (!default_sender_info) {
4948 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004949 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004950 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004951 }
4952 }
deadbeefab9b2d12015-10-14 11:33:11 -07004953}
4954
Steve Anton4171afb2017-11-20 10:20:22 -08004955void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4956 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004957 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4958 << " receiver for track_id=" << sender_info.sender_id
4959 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004960
Steve Anton3d954a62018-04-02 11:27:23 -07004961 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004962 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004963 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004964 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004965 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004966 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004967 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004968 }
4969}
4970
Steve Anton4171afb2017-11-20 10:20:22 -08004971void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4972 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004973 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4974 << " receiver for track_id=" << sender_info.sender_id
4975 << " and stream_id=" << sender_info.stream_id;
4976
Seth Hampson845e8782018-03-02 11:34:10 -08004977 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004978
Henrik Boström933d8b02017-10-10 10:05:16 -07004979 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004980 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004981 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4982 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004983 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004984 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004985 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004986 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004987 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004988 }
4989 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004990 // Stopping or destroying a VideoRtpReceiver will end the
4991 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004992 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004993 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004994 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004995 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004996 // There's no guarantee the track is still available, e.g. the track may
4997 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004998 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004999 }
5000 } else {
nisseede5da42017-01-12 05:15:36 -08005001 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07005002 }
Henrik Boström933d8b02017-10-10 10:05:16 -07005003 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005004 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07005005 }
deadbeefab9b2d12015-10-14 11:33:11 -07005006}
5007
5008void PeerConnection::UpdateEndedRemoteMediaStreams() {
5009 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
5010 for (size_t i = 0; i < remote_streams_->count(); ++i) {
5011 MediaStreamInterface* stream = remote_streams_->at(i);
5012 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
5013 streams_to_remove.push_back(stream);
5014 }
5015 }
5016
Taylor Brandstetter98cde262016-05-31 13:02:21 -07005017 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07005018 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005019 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07005020 }
5021}
5022
Steve Anton4171afb2017-11-20 10:20:22 -08005023void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07005024 const std::vector<cricket::StreamParams>& streams,
5025 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08005026 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005027
Seth Hampson845e8782018-03-02 11:34:10 -08005028 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07005029 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08005030 for (auto sender_it = current_senders->begin();
5031 sender_it != current_senders->end();
5032 /* incremented manually */) {
5033 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005034 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08005035 cricket::GetStreamBySsrc(streams, info.first_ssrc);
5036 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08005037 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005038 OnLocalSenderRemoved(info, media_type);
5039 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07005040 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08005041 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07005042 }
5043 }
5044
Steve Anton4171afb2017-11-20 10:20:22 -08005045 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07005046 for (const cricket::StreamParams& params : streams) {
5047 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08005048 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08005049 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08005050 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07005051 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08005052 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005053 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08005054 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08005055 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08005056 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07005057 }
5058 }
5059}
5060
Steve Anton4171afb2017-11-20 10:20:22 -08005061void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
5062 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07005063 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08005064 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005065 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08005066 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
5067 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01005068 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07005069 return;
5070 }
5071
deadbeeffac06552015-11-25 11:26:01 -08005072 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005073 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005074 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005075 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005076 }
deadbeeffac06552015-11-25 11:26:01 -08005077
Henrik Andreasssoncc189172019-05-20 09:01:38 +00005078 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08005079 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07005080}
5081
Steve Anton4171afb2017-11-20 10:20:22 -08005082void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
5083 cricket::MediaType media_type) {
5084 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08005085 if (!sender) {
5086 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07005087 // SessionDescriptions has been renegotiated.
5088 return;
5089 }
deadbeeffac06552015-11-25 11:26:01 -08005090
5091 // A sender has been removed from the SessionDescription but it's still
5092 // associated with the PeerConnection. This only occurs if the SDP doesn't
5093 // match with the calls to CreateSender, AddStream and RemoveStream.
5094 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005095 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005096 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08005097 return;
deadbeefab9b2d12015-10-14 11:33:11 -07005098 }
deadbeeffac06552015-11-25 11:26:01 -08005099
Steve Anton4171afb2017-11-20 10:20:22 -08005100 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07005101}
5102
5103void PeerConnection::UpdateLocalRtpDataChannels(
5104 const cricket::StreamParamsVec& streams) {
5105 std::vector<std::string> existing_channels;
5106
5107 // Find new and active data channels.
5108 for (const cricket::StreamParams& params : streams) {
5109 // |it->sync_label| is actually the data channel label. The reason is that
5110 // we use the same naming of data channels as we do for
5111 // MediaStreams and Tracks.
5112 // For MediaStreams, the sync_label is the MediaStream label and the
5113 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08005114 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005115 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08005116 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005117 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07005118 continue;
5119 }
5120 // Set the SSRC the data channel should use for sending.
5121 data_channel_it->second->SetSendSsrc(params.first_ssrc());
5122 existing_channels.push_back(data_channel_it->first);
5123 }
5124
5125 UpdateClosingRtpDataChannels(existing_channels, true);
5126}
5127
5128void PeerConnection::UpdateRemoteRtpDataChannels(
5129 const cricket::StreamParamsVec& streams) {
5130 std::vector<std::string> existing_channels;
5131
5132 // Find new and active data channels.
5133 for (const cricket::StreamParams& params : streams) {
5134 // The data channel label is either the mslabel or the SSRC if the mslabel
5135 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08005136 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07005137 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08005138 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07005139 auto data_channel_it = rtp_data_channels_.find(label);
5140 if (data_channel_it == rtp_data_channels_.end()) {
5141 // This is a new data channel.
5142 CreateRemoteRtpDataChannel(label, params.first_ssrc());
5143 } else {
5144 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
5145 }
5146 existing_channels.push_back(label);
5147 }
5148
5149 UpdateClosingRtpDataChannels(existing_channels, false);
5150}
5151
5152void PeerConnection::UpdateClosingRtpDataChannels(
5153 const std::vector<std::string>& active_channels,
5154 bool is_local_update) {
5155 auto it = rtp_data_channels_.begin();
5156 while (it != rtp_data_channels_.end()) {
5157 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005158 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005159 ++it;
5160 continue;
5161 }
5162
5163 if (is_local_update) {
5164 data_channel->SetSendSsrc(0);
5165 } else {
5166 data_channel->RemotePeerRequestClose();
5167 }
5168
5169 if (data_channel->state() == DataChannel::kClosed) {
5170 rtp_data_channels_.erase(it);
5171 it = rtp_data_channels_.begin();
5172 } else {
5173 ++it;
5174 }
5175 }
5176}
5177
5178void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5179 uint32_t remote_ssrc) {
5180 rtc::scoped_refptr<DataChannel> channel(
5181 InternalCreateDataChannel(label, nullptr));
5182 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005183 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005184 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005185 return;
5186 }
5187 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005188 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5189 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005190 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005191}
5192
5193rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5194 const std::string& label,
5195 const InternalDataChannelInit* config) {
5196 if (IsClosed()) {
5197 return nullptr;
5198 }
Steve Anton75737c02017-11-06 10:37:17 -08005199 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005200 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005201 << "InternalCreateDataChannel: Data is not supported in this call.";
5202 return nullptr;
5203 }
5204 InternalDataChannelInit new_config =
5205 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005206 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005207 if (new_config.id < 0) {
5208 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005209 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005210 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005211 RTC_LOG(LS_ERROR)
5212 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005213 return nullptr;
5214 }
5215 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005216 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005217 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005218 return nullptr;
5219 }
5220 }
5221
Steve Anton75737c02017-11-06 10:37:17 -08005222 rtc::scoped_refptr<DataChannel> channel(
5223 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005224 if (!channel) {
5225 sid_allocator_.ReleaseSid(new_config.id);
5226 return nullptr;
5227 }
5228
5229 if (channel->data_channel_type() == cricket::DCT_RTP) {
5230 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005231 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5232 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005233 return nullptr;
5234 }
5235 rtp_data_channels_[channel->label()] = channel;
5236 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005237 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005238 sctp_data_channels_.push_back(channel);
5239 channel->SignalClosed.connect(this,
5240 &PeerConnection::OnSctpDataChannelClosed);
5241 }
5242
Steve Anton2d8609c2018-01-23 16:38:46 -08005243 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005244 return channel;
5245}
5246
5247bool PeerConnection::HasDataChannels() const {
5248 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5249}
5250
5251void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005252 std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
deadbeefab9b2d12015-10-14 11:33:11 -07005253 for (const auto& channel : sctp_data_channels_) {
5254 if (channel->id() < 0) {
5255 int sid;
5256 if (!sid_allocator_.AllocateSid(role, &sid)) {
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005257 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
5258 channels_to_close.push_back(channel);
deadbeefab9b2d12015-10-14 11:33:11 -07005259 continue;
5260 }
5261 channel->SetSctpSid(sid);
5262 }
5263 }
Harald Alvestrand1f928d32019-03-28 11:29:38 +01005264 // Since closing modifies the list of channels, we have to do the actual
5265 // closing outside the loop.
5266 for (const auto& channel : channels_to_close) {
5267 channel->CloseAbruptly();
5268 }
deadbeefab9b2d12015-10-14 11:33:11 -07005269}
5270
5271void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005272 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005273 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5274 ++it) {
5275 if (it->get() == channel) {
5276 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005277 // After the closing procedure is done, it's safe to use this ID for
5278 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005279 sid_allocator_.ReleaseSid(channel->id());
5280 }
deadbeefbd292462015-12-14 18:15:29 -08005281 // Since this method is triggered by a signal from the DataChannel,
5282 // we can't free it directly here; we need to free it asynchronously.
5283 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005284 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005285 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5286 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005287 return;
5288 }
5289 }
5290}
5291
deadbeefab9b2d12015-10-14 11:33:11 -07005292void PeerConnection::OnDataChannelDestroyed() {
5293 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5294 // DataChannel may callback to us and try to modify the list.
5295 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5296 temp_rtp_dcs.swap(rtp_data_channels_);
5297 for (const auto& kv : temp_rtp_dcs) {
5298 kv.second->OnTransportChannelDestroyed();
5299 }
5300
5301 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5302 temp_sctp_dcs.swap(sctp_data_channels_);
5303 for (const auto& channel : temp_sctp_dcs) {
5304 channel->OnTransportChannelDestroyed();
5305 }
5306}
5307
5308void PeerConnection::OnDataChannelOpenMessage(
5309 const std::string& label,
5310 const InternalDataChannelInit& config) {
5311 rtc::scoped_refptr<DataChannel> channel(
5312 InternalCreateDataChannel(label, &config));
5313 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005314 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005315 return;
5316 }
5317
deadbeefa601f5c2016-06-06 14:27:39 -07005318 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5319 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005320 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005321 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005322}
5323
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005324bool PeerConnection::HandleOpenMessage_s(
5325 const cricket::ReceiveDataParams& params,
5326 const rtc::CopyOnWriteBuffer& buffer) {
5327 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5328 // Received OPEN message; parse and signal that a new data channel should
5329 // be created.
5330 std::string label;
5331 InternalDataChannelInit config;
5332 config.id = params.ssrc;
5333 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5334 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5335 << params.ssrc;
5336 return true;
5337 }
5338 config.open_handshake_role = InternalDataChannelInit::kAcker;
5339 OnDataChannelOpenMessage(label, config);
5340 return true;
5341 }
5342 return false;
5343}
5344
Steve Anton4171afb2017-11-20 10:20:22 -08005345rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5346PeerConnection::GetAudioTransceiver() const {
5347 // This method only works with Plan B SDP, where there is a single
5348 // audio/video transceiver.
5349 RTC_DCHECK(!IsUnifiedPlan());
5350 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005351 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005352 return transceiver;
5353 }
5354 }
5355 RTC_NOTREACHED();
5356 return nullptr;
5357}
5358
5359rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5360PeerConnection::GetVideoTransceiver() const {
5361 // This method only works with Plan B SDP, where there is a single
5362 // audio/video transceiver.
5363 RTC_DCHECK(!IsUnifiedPlan());
5364 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005365 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005366 return transceiver;
5367 }
5368 }
5369 RTC_NOTREACHED();
5370 return nullptr;
5371}
5372
5373// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5374// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005375bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005376 switch (type) {
5377 case cricket::MEDIA_TYPE_AUDIO:
5378 return !GetAudioTransceiver()->internal()->senders().empty();
5379 case cricket::MEDIA_TYPE_VIDEO:
5380 return !GetVideoTransceiver()->internal()->senders().empty();
5381 case cricket::MEDIA_TYPE_DATA:
5382 return false;
5383 }
5384 RTC_NOTREACHED();
5385 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005386}
5387
Steve Anton4171afb2017-11-20 10:20:22 -08005388rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5389PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005390 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005391 for (auto sender : transceiver->internal()->senders()) {
5392 if (sender->track() == track) {
5393 return sender;
5394 }
5395 }
5396 }
5397 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005398}
5399
Steve Anton4171afb2017-11-20 10:20:22 -08005400rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5401PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005402 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005403 for (auto sender : transceiver->internal()->senders()) {
5404 if (sender->id() == sender_id) {
5405 return sender;
5406 }
5407 }
5408 }
5409 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005410}
5411
Steve Anton4171afb2017-11-20 10:20:22 -08005412rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5413PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005414 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005415 for (auto receiver : transceiver->internal()->receivers()) {
5416 if (receiver->id() == receiver_id) {
5417 return receiver;
5418 }
5419 }
5420 }
5421 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005422}
5423
Steve Anton4171afb2017-11-20 10:20:22 -08005424std::vector<PeerConnection::RtpSenderInfo>*
5425PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5426 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5427 media_type == cricket::MEDIA_TYPE_VIDEO);
5428 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5429 ? &remote_audio_sender_infos_
5430 : &remote_video_sender_infos_;
5431}
5432
5433std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005434 cricket::MediaType media_type) {
5435 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5436 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005437 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5438 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005439}
5440
Steve Anton4171afb2017-11-20 10:20:22 -08005441const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5442 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005443 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005444 const std::string sender_id) const {
5445 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005446 if (sender_info.stream_id == stream_id &&
5447 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005448 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005449 }
5450 }
5451 return nullptr;
5452}
5453
5454DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5455 for (const auto& channel : sctp_data_channels_) {
5456 if (channel->id() == sid) {
5457 return channel;
5458 }
5459 }
5460 return nullptr;
5461}
5462
Karl Wibergfb3be392019-03-22 14:13:22 +01005463PeerConnection::InitializePortAllocatorResult
5464PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005465 const cricket::ServerAddresses& stun_servers,
5466 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005467 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005468 RTC_DCHECK_RUN_ON(network_thread());
5469
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005470 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005471 // To handle both internal and externally created port allocator, we will
5472 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005473 int port_allocator_flags = port_allocator_->flags();
5474 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5475 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5476 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005477 // If the disable-IPv6 flag was specified, we'll not override it
5478 // by experiment.
5479 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005480 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005481 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5482 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005483 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005484 }
5485
zhihuangb09b3f92017-03-07 14:40:51 -08005486 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005487 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005488 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005489 }
5490
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005491 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005492 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005493 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005494 }
5495
honghaiz60347052016-05-31 18:29:12 -07005496 if (configuration.candidate_network_policy ==
5497 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005498 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005499 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005500 }
5501
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005502 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005503 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005504 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5505 }
5506
Karl Wibergfb3be392019-03-22 14:13:22 +01005507 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005508 // No step delay is used while allocating ports.
5509 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
Qingsi Wangc129c352019-04-18 10:41:58 -07005510 port_allocator_->SetCandidateFilter(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005511 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005512 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005513
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005514 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005515 for (auto& turn_server : turn_servers_copy) {
5516 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005517 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005518 // Call this last since it may create pooled allocator sessions using the
5519 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005520 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005521 stun_servers, std::move(turn_servers_copy),
5522 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5523 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005524 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005525
5526 InitializePortAllocatorResult res;
5527 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5528 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005529}
5530
deadbeef91dd5672016-05-18 16:55:30 -07005531bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005532 const cricket::ServerAddresses& stun_servers,
5533 const std::vector<cricket::RelayServerConfig>& turn_servers,
5534 IceTransportsType type,
5535 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005536 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005537 webrtc::TurnCustomizer* turn_customizer,
Karl Wiberg739506e2019-04-03 11:37:28 +02005538 absl::optional<int> stun_candidate_keepalive_interval,
5539 bool have_local_description) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005540 port_allocator_->SetCandidateFilter(
deadbeef293e9262017-01-11 12:28:30 -08005541 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005542 // According to JSEP, after setLocalDescription, changing the candidate pool
5543 // size is not allowed, and changing the set of ICE servers will not result
5544 // in new candidates being gathered.
Karl Wiberg739506e2019-04-03 11:37:28 +02005545 if (have_local_description) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005546 port_allocator_->FreezeCandidatePool();
5547 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005548 // Add the custom tls turn servers if they exist.
5549 auto turn_servers_copy = turn_servers;
5550 for (auto& turn_server : turn_servers_copy) {
5551 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5552 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005553 // Call this last since it may create pooled allocator sessions using the
5554 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005555 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005556 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5557 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005558}
5559
Steve Antonba818672017-11-06 10:21:57 -08005560cricket::ChannelManager* PeerConnection::channel_manager() const {
5561 return factory_->channel_manager();
5562}
5563
Elad Alon99c3fe52017-10-13 16:29:40 +02005564bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005565 std::unique_ptr<RtcEventLogOutput> output,
5566 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005567 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005568 if (!event_log_) {
5569 return false;
5570 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005571 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005572}
5573
5574void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005575 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005576 if (event_log_) {
5577 event_log_->StopLogging();
5578 }
ivoc14d5dbe2016-07-04 07:06:55 -07005579}
nisseeaabdf62017-05-05 02:23:02 -07005580
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005581cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005582 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005583 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005584 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005585 if (channel && channel->content_name() == content_name) {
5586 return channel;
5587 }
Steve Anton75737c02017-11-06 10:37:17 -08005588 }
5589 if (rtp_data_channel() &&
5590 rtp_data_channel()->content_name() == content_name) {
5591 return rtp_data_channel();
5592 }
5593 return nullptr;
5594}
5595
5596bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005597 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005598 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005599 RTC_LOG(LS_INFO)
5600 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005601 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005602 return false;
5603 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005604 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005605 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005606 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005607 return false;
5608 }
5609
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005610 absl::optional<rtc::SSLRole> dtls_role;
5611 if (sctp_mid_) {
5612 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5613 } else if (is_caller_) {
5614 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5615 }
Zhi Huange830e682018-03-30 10:48:35 -07005616 if (dtls_role) {
5617 *role = *dtls_role;
5618 return true;
5619 }
5620 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005621}
5622
5623bool PeerConnection::GetSslRole(const std::string& content_name,
5624 rtc::SSLRole* role) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005625 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005626 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005627 RTC_LOG(LS_INFO)
5628 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005629 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005630 return false;
5631 }
5632
Zhi Huange830e682018-03-30 10:48:35 -07005633 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5634 if (dtls_role) {
5635 *role = *dtls_role;
5636 return true;
5637 }
5638 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005639}
5640
Steve Antonf8470812017-12-04 10:46:21 -08005641void PeerConnection::SetSessionError(SessionError error,
5642 const std::string& error_desc) {
5643 RTC_DCHECK_RUN_ON(signaling_thread());
5644 if (error != session_error_) {
5645 session_error_ = error;
5646 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005647 }
5648}
5649
Zhi Huange830e682018-03-30 10:48:35 -07005650RTCError PeerConnection::UpdateSessionState(
5651 SdpType type,
5652 cricket::ContentSource source,
5653 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005654 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005655
5656 // If there's already a pending error then no state transition should happen.
5657 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005658 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005659
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005660 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005661 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005662 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005663 }
5664
5665 // Update the signaling state according to the specified state machine (see
5666 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005667 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005668 ChangeSignalingState(source == cricket::CS_LOCAL
5669 ? PeerConnectionInterface::kHaveLocalOffer
5670 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005671 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005672 ChangeSignalingState(source == cricket::CS_LOCAL
5673 ? PeerConnectionInterface::kHaveLocalPrAnswer
5674 : PeerConnectionInterface::kHaveRemotePrAnswer);
5675 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005676 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005677 ChangeSignalingState(PeerConnectionInterface::kStable);
5678 }
5679
5680 // Update internal objects according to the session description's media
5681 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005682 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005683 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005684 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005685 }
5686
Steve Anton8a006912017-12-04 15:25:56 -08005687 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005688}
5689
Steve Anton8a006912017-12-04 15:25:56 -08005690RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005691 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005692 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005693 const SessionDescriptionInterface* sdesc =
5694 (source == cricket::CS_LOCAL ? local_description()
5695 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005696 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005697
5698 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005699 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005700 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005701 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005702 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005703 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005704 continue;
5705 }
5706 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005707 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005708 if (!content_desc) {
5709 continue;
5710 }
5711 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005712 bool success = (source == cricket::CS_LOCAL)
5713 ? channel->SetLocalContent(content_desc, type, &error)
5714 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005715 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005717 }
5718 }
5719
5720 // If using the RtpDataChannel, push down the new SDP section for it too.
5721 if (rtp_data_channel_) {
5722 const ContentInfo* data_content =
5723 cricket::GetFirstDataContent(sdesc->description());
5724 if (data_content && !data_content->rejected) {
5725 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005726 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005727 if (data_desc) {
5728 std::string error;
5729 bool success =
5730 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005731 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005732 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005733 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005734 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005735 }
Steve Anton75737c02017-11-06 10:37:17 -08005736 }
5737 }
5738 }
Steve Antoned10bd92017-12-05 10:52:59 -08005739
Steve Anton75737c02017-11-06 10:37:17 -08005740 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5741 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005742 if (sctp_transport_ && local_description() && remote_description()) {
5743 auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
5744 local_description()->description());
5745 auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
5746 remote_description()->description());
5747 if (local_sctp_description && remote_sctp_description) {
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005748 int max_message_size;
5749 // A remote max message size of zero means "any size supported".
5750 // We configure the connection with our own max message size.
5751 if (remote_sctp_description->max_message_size() == 0) {
5752 max_message_size = local_sctp_description->max_message_size();
5753 } else {
5754 max_message_size =
5755 std::min(local_sctp_description->max_message_size(),
5756 remote_sctp_description->max_message_size());
Harald Alvestrandfbb45bd2019-05-15 08:07:47 +02005757 }
Harald Alvestrand8d3d6cf2019-05-16 11:49:17 +02005758 sctp_transport_->Start(local_sctp_description->port(),
5759 remote_sctp_description->port(), max_message_size);
Steve Anton8a006912017-12-04 15:25:56 -08005760 }
Steve Anton75737c02017-11-06 10:37:17 -08005761 }
Steve Antoned10bd92017-12-05 10:52:59 -08005762
Steve Anton8a006912017-12-04 15:25:56 -08005763 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005764}
5765
Steve Anton8a006912017-12-04 15:25:56 -08005766RTCError PeerConnection::PushdownTransportDescription(
5767 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005768 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005769 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005770
Zhi Huange830e682018-03-30 10:48:35 -07005771 if (source == cricket::CS_LOCAL) {
5772 const SessionDescriptionInterface* sdesc = local_description();
5773 RTC_DCHECK(sdesc);
5774 return transport_controller_->SetLocalDescription(type,
5775 sdesc->description());
5776 } else {
5777 const SessionDescriptionInterface* sdesc = remote_description();
5778 RTC_DCHECK(sdesc);
5779 return transport_controller_->SetRemoteDescription(type,
5780 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005781 }
Steve Anton75737c02017-11-06 10:37:17 -08005782}
5783
5784bool PeerConnection::GetTransportDescription(
5785 const SessionDescription* description,
5786 const std::string& content_name,
5787 cricket::TransportDescription* tdesc) {
5788 if (!description || !tdesc) {
5789 return false;
5790 }
5791 const TransportInfo* transport_info =
5792 description->GetTransportInfoByName(content_name);
5793 if (!transport_info) {
5794 return false;
5795 }
5796 *tdesc = transport_info->description;
5797 return true;
5798}
5799
Steve Anton75737c02017-11-06 10:37:17 -08005800cricket::IceConfig PeerConnection::ParseIceConfig(
5801 const PeerConnectionInterface::RTCConfiguration& config) const {
5802 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005803 switch (config.continual_gathering_policy) {
5804 case PeerConnectionInterface::GATHER_ONCE:
5805 gathering_policy = cricket::GATHER_ONCE;
5806 break;
5807 case PeerConnectionInterface::GATHER_CONTINUALLY:
5808 gathering_policy = cricket::GATHER_CONTINUALLY;
5809 break;
5810 default:
5811 RTC_NOTREACHED();
5812 gathering_policy = cricket::GATHER_ONCE;
5813 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005814
Steve Anton75737c02017-11-06 10:37:17 -08005815 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005816 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5817 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005818 ice_config.prioritize_most_likely_candidate_pairs =
5819 config.prioritize_most_likely_ice_candidate_pairs;
5820 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005821 RTCConfigurationToIceConfigOptionalInt(
5822 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005823 ice_config.continual_gathering_policy = gathering_policy;
5824 ice_config.presume_writable_when_fully_relayed =
5825 config.presume_writable_when_fully_relayed;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005826 ice_config.surface_ice_candidates_on_ice_transport_type_changed =
5827 config.surface_ice_candidates_on_ice_transport_type_changed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005828 ice_config.ice_check_interval_strong_connectivity =
5829 config.ice_check_interval_strong_connectivity;
5830 ice_config.ice_check_interval_weak_connectivity =
5831 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005832 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005833 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5834 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005835 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005836 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005837 ice_config.regather_all_networks_interval_range =
5838 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005839 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005840 return ice_config;
5841}
5842
Steve Anton75737c02017-11-06 10:37:17 -08005843bool PeerConnection::SendData(const cricket::SendDataParams& params,
5844 const rtc::CopyOnWriteBuffer& payload,
5845 cricket::SendDataResult* result) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02005846 RTC_DCHECK_RUN_ON(signaling_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005847 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5848 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5849 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005850 return false;
5851 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005852 if (media_transport_) {
5853 SendDataParams send_params;
5854 send_params.type = ToWebrtcDataMessageType(params.type);
5855 send_params.ordered = params.ordered;
5856 if (params.max_rtx_count >= 0) {
5857 send_params.max_rtx_count = params.max_rtx_count;
5858 } else if (params.max_rtx_ms >= 0) {
5859 send_params.max_rtx_ms = params.max_rtx_ms;
5860 }
5861 return media_transport_->SendData(params.sid, send_params, payload).ok();
5862 }
Steve Anton75737c02017-11-06 10:37:17 -08005863 return rtp_data_channel_
5864 ? rtp_data_channel_->SendData(params, payload, result)
5865 : network_thread()->Invoke<bool>(
5866 RTC_FROM_HERE,
5867 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005868 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005869}
5870
5871bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005872 RTC_DCHECK_RUN_ON(signaling_thread());
5873 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005874 // Don't log an error here, because DataChannels are expected to call
5875 // ConnectDataChannel in this state. It's the only way to initially tell
5876 // whether or not the underlying transport is ready.
5877 return false;
5878 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005879 if (media_transport_) {
5880 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5881 &DataChannel::OnChannelReady);
5882 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5883 &DataChannel::OnDataReceived);
5884 SignalMediaTransportChannelClosing_s.connect(
5885 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5886 SignalMediaTransportChannelClosed_s.connect(
5887 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5888 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005889 rtp_data_channel_->SignalReadyToSendData.connect(
5890 webrtc_data_channel, &DataChannel::OnChannelReady);
5891 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5892 &DataChannel::OnDataReceived);
5893 } else {
5894 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5895 &DataChannel::OnChannelReady);
5896 SignalSctpDataReceived.connect(webrtc_data_channel,
5897 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005898 SignalSctpClosingProcedureStartedRemotely.connect(
5899 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5900 SignalSctpClosingProcedureComplete.connect(
5901 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005902 }
5903 return true;
5904}
5905
5906void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005907 RTC_DCHECK_RUN_ON(signaling_thread());
5908 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005909 RTC_LOG(LS_ERROR)
5910 << "DisconnectDataChannel called when rtp_data_channel_ and "
5911 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005912 return;
5913 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005914 if (media_transport_) {
5915 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5916 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5917 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5918 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5919 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005920 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5921 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5922 } else {
5923 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5924 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005925 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5926 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005927 }
5928}
5929
5930void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005931 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005932 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005933 return;
5934 }
Steve Anton75737c02017-11-06 10:37:17 -08005935 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005936 RTC_LOG(LS_ERROR)
5937 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005938 return;
5939 }
5940 network_thread()->Invoke<void>(
5941 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005942 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005943}
5944
5945void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005946 if (media_transport_) {
5947 media_transport_->CloseChannel(sid);
5948 return;
5949 }
Steve Anton75737c02017-11-06 10:37:17 -08005950 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005951 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005952 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005953 return;
5954 }
5955 network_thread()->Invoke<void>(
5956 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005957 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005958}
5959
5960bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005961 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005962 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005963 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005964 sctp_ready_to_send_data_;
5965}
5966
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005967void PeerConnection::OnDataReceived(int channel_id,
5968 DataMessageType type,
5969 const rtc::CopyOnWriteBuffer& buffer) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005970 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005971 cricket::ReceiveDataParams params;
5972 params.sid = channel_id;
5973 params.type = ToCricketDataMessageType(type);
5974 media_transport_invoker_->AsyncInvoke<void>(
5975 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5976 RTC_DCHECK_RUN_ON(signaling_thread());
5977 if (!HandleOpenMessage_s(params, buffer)) {
5978 SignalMediaTransportReceivedData_s(params, buffer);
5979 }
5980 });
5981}
5982
5983void PeerConnection::OnChannelClosing(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005984 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005985 media_transport_invoker_->AsyncInvoke<void>(
5986 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5987 RTC_DCHECK_RUN_ON(signaling_thread());
5988 SignalMediaTransportChannelClosing_s(channel_id);
5989 });
5990}
5991
5992void PeerConnection::OnChannelClosed(int channel_id) {
Karl Wiberg739506e2019-04-03 11:37:28 +02005993 RTC_DCHECK_RUN_ON(network_thread());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005994 media_transport_invoker_->AsyncInvoke<void>(
5995 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5996 RTC_DCHECK_RUN_ON(signaling_thread());
5997 SignalMediaTransportChannelClosed_s(channel_id);
5998 });
5999}
6000
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006001absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006002 RTC_DCHECK_RUN_ON(signaling_thread());
Zhi Huange830e682018-03-30 10:48:35 -07006003 if (sctp_mid_ && transport_controller_) {
6004 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
6005 if (dtls_transport) {
6006 return dtls_transport->transport_name();
6007 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006008 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006009 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006010 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07006011}
6012
Qingsi Wang72a43a12018-02-20 16:03:18 -08006013cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
6014 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07006015 network_thread()->Invoke<void>(
6016 RTC_FROM_HERE,
6017 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
6018 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08006019 return candidate_states_list;
6020}
6021
Steve Anton5dfde182018-02-06 10:34:40 -08006022std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
6023 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01006024 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006025 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006026 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006027 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08006028 if (channel) {
6029 transport_names_by_mid[channel->content_name()] =
6030 channel->transport_name();
6031 }
Steve Anton75737c02017-11-06 10:37:17 -08006032 }
Steve Anton5dfde182018-02-06 10:34:40 -08006033 if (rtp_data_channel_) {
6034 transport_names_by_mid[rtp_data_channel_->content_name()] =
6035 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006036 }
6037 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006038 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006039 RTC_DCHECK(transport_name);
6040 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08006041 }
Steve Anton5dfde182018-02-06 10:34:40 -08006042 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08006043}
6044
Steve Anton5dfde182018-02-06 10:34:40 -08006045std::map<std::string, cricket::TransportStats>
6046PeerConnection::GetTransportStatsByNames(
6047 const std::set<std::string>& transport_names) {
6048 if (!network_thread()->IsCurrent()) {
6049 return network_thread()
6050 ->Invoke<std::map<std::string, cricket::TransportStats>>(
6051 RTC_FROM_HERE,
6052 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08006053 }
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006054 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08006055 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
6056 for (const std::string& transport_name : transport_names) {
6057 cricket::TransportStats transport_stats;
6058 bool success =
6059 transport_controller_->GetStats(transport_name, &transport_stats);
6060 if (success) {
6061 transport_stats_by_name[transport_name] = std::move(transport_stats);
6062 } else {
6063 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
6064 << transport_name;
6065 }
6066 }
6067 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08006068}
6069
6070bool PeerConnection::GetLocalCertificate(
6071 const std::string& transport_name,
6072 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07006073 if (!certificate) {
6074 return false;
6075 }
6076 *certificate = transport_controller_->GetLocalCertificate(transport_name);
6077 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006078}
6079
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006080std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08006081 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08006082 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08006083}
6084
6085cricket::DataChannelType PeerConnection::data_channel_type() const {
6086 return data_channel_type_;
6087}
6088
6089bool PeerConnection::IceRestartPending(const std::string& content_name) const {
Karl Wibergf73f7d62019-04-08 15:36:53 +02006090 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006091 return pending_ice_restarts_.find(content_name) !=
6092 pending_ice_restarts_.end();
6093}
6094
Steve Anton75737c02017-11-06 10:37:17 -08006095bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
6096 return transport_controller_->NeedsIceRestart(content_name);
6097}
6098
6099void PeerConnection::OnCertificateReady(
6100 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
6101 transport_controller_->SetLocalCertificate(certificate);
6102}
6103
6104void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08006105 SetSessionError(SessionError::kTransport,
6106 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08006107}
6108
Alex Loiko9289eda2018-11-23 16:18:59 +00006109void PeerConnection::OnTransportControllerConnectionState(
6110 cricket::IceConnectionState state) {
6111 switch (state) {
6112 case cricket::kIceConnectionConnecting:
6113 // If the current state is Connected or Completed, then there were
6114 // writable channels but now there are not, so the next state must
6115 // be Disconnected.
6116 // kIceConnectionConnecting is currently used as the default,
6117 // un-connected state by the TransportController, so its only use is
6118 // detecting disconnections.
6119 if (ice_connection_state_ ==
6120 PeerConnectionInterface::kIceConnectionConnected ||
6121 ice_connection_state_ ==
6122 PeerConnectionInterface::kIceConnectionCompleted) {
6123 SetIceConnectionState(
6124 PeerConnectionInterface::kIceConnectionDisconnected);
6125 }
6126 break;
6127 case cricket::kIceConnectionFailed:
6128 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
6129 break;
6130 case cricket::kIceConnectionConnected:
6131 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
6132 "all transports are writable.";
6133 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6134 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6135 break;
6136 case cricket::kIceConnectionCompleted:
6137 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6138 "all transports are complete.";
6139 if (ice_connection_state_ !=
6140 PeerConnectionInterface::kIceConnectionConnected) {
6141 // If jumping directly from "checking" to "connected",
6142 // signal "connected" first.
6143 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6144 }
6145 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6146 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6147 ReportTransportStats();
6148 break;
6149 default:
6150 RTC_NOTREACHED();
6151 }
6152}
6153
Steve Anton75737c02017-11-06 10:37:17 -08006154void PeerConnection::OnTransportControllerCandidatesGathered(
6155 const std::string& transport_name,
6156 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006157 int sdp_mline_index;
6158 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006159 RTC_LOG(LS_ERROR)
6160 << "OnTransportControllerCandidatesGathered: content name "
6161 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006162 return;
6163 }
6164
6165 for (cricket::Candidates::const_iterator citer = candidates.begin();
6166 citer != candidates.end(); ++citer) {
6167 // Use transport_name as the candidate media id.
6168 std::unique_ptr<JsepIceCandidate> candidate(
6169 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6170 if (local_description()) {
6171 mutable_local_description()->AddCandidate(candidate.get());
6172 }
6173 OnIceCandidate(std::move(candidate));
6174 }
6175}
6176
Eldar Relloda13ea22019-06-01 12:23:43 +03006177void PeerConnection::OnTransportControllerCandidateError(
6178 const cricket::IceCandidateErrorEvent& event) {
6179 OnIceCandidateError(event.host_candidate, event.url, event.error_code,
6180 event.error_text);
6181}
6182
Steve Anton75737c02017-11-06 10:37:17 -08006183void PeerConnection::OnTransportControllerCandidatesRemoved(
6184 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006185 // Sanity check.
6186 for (const cricket::Candidate& candidate : candidates) {
6187 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006188 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006189 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006190 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006191 return;
6192 }
6193 }
6194
6195 if (local_description()) {
6196 mutable_local_description()->RemoveCandidates(candidates);
6197 }
6198 OnIceCandidatesRemoved(candidates);
6199}
6200
6201void PeerConnection::OnTransportControllerDtlsHandshakeError(
6202 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006203 RTC_HISTOGRAM_ENUMERATION(
6204 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6205 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006206}
6207
Steve Antoned10bd92017-12-05 10:52:59 -08006208void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006209 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006210 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006211 if (channel && !channel->enabled()) {
6212 channel->Enable(true);
6213 }
Steve Anton75737c02017-11-06 10:37:17 -08006214 }
6215
Steve Anton4171afb2017-11-20 10:20:22 -08006216 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006217 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006218 }
Steve Anton75737c02017-11-06 10:37:17 -08006219}
6220
6221// Returns the media index for a local ice candidate given the content name.
6222bool PeerConnection::GetLocalCandidateMediaIndex(
6223 const std::string& content_name,
6224 int* sdp_mline_index) {
6225 if (!local_description() || !sdp_mline_index) {
6226 return false;
6227 }
6228
6229 bool content_found = false;
6230 const ContentInfos& contents = local_description()->description()->contents();
6231 for (size_t index = 0; index < contents.size(); ++index) {
6232 if (contents[index].name == content_name) {
6233 *sdp_mline_index = static_cast<int>(index);
6234 content_found = true;
6235 break;
6236 }
6237 }
6238 return content_found;
6239}
6240
6241bool PeerConnection::UseCandidatesInSessionDescription(
6242 const SessionDescriptionInterface* remote_desc) {
6243 if (!remote_desc) {
6244 return true;
6245 }
6246 bool ret = true;
6247
6248 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6249 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6250 for (size_t n = 0; n < candidates->count(); ++n) {
6251 const IceCandidateInterface* candidate = candidates->at(n);
6252 bool valid = false;
6253 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6254 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006255 RTC_LOG(LS_INFO)
6256 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006257 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006258 }
6259 continue;
6260 }
6261 ret = UseCandidate(candidate);
6262 if (!ret) {
6263 break;
6264 }
6265 }
6266 }
6267 return ret;
6268}
6269
6270bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
Guido Urdaneta41633172019-05-23 20:12:29 +02006271 RTCErrorOr<const cricket::ContentInfo*> result =
6272 FindContentInfo(remote_description(), candidate);
6273 if (!result.ok()) {
6274 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
6275 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006276 return false;
6277 }
Steve Anton75737c02017-11-06 10:37:17 -08006278 std::vector<cricket::Candidate> candidates;
6279 candidates.push_back(candidate->candidate());
6280 // Invoking BaseSession method to handle remote candidates.
Guido Urdaneta41633172019-05-23 20:12:29 +02006281 RTCError error = transport_controller_->AddRemoteCandidates(
6282 result.value()->name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006283 if (error.ok()) {
6284 // Candidates successfully submitted for checking.
6285 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6286 ice_connection_state_ ==
6287 PeerConnectionInterface::kIceConnectionDisconnected) {
6288 // If state is New, then the session has just gotten its first remote ICE
6289 // candidates, so go to Checking.
6290 // If state is Disconnected, the session is re-using old candidates or
6291 // receiving additional ones, so go to Checking.
6292 // If state is Connected, stay Connected.
6293 // TODO(bemasc): If state is Connected, and the new candidates are for a
6294 // newly added transport, then the state actually _should_ move to
6295 // checking. Add a way to distinguish that case.
6296 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6297 }
6298 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006299 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006300 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006301 }
6302 return true;
6303}
6304
Guido Urdaneta41633172019-05-23 20:12:29 +02006305RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
6306 const SessionDescriptionInterface* description,
6307 const IceCandidateInterface* candidate) {
6308 if (candidate->sdp_mline_index() >= 0) {
6309 size_t mediacontent_index =
6310 static_cast<size_t>(candidate->sdp_mline_index());
6311 size_t content_size = description->description()->contents().size();
6312 if (mediacontent_index < content_size) {
6313 return &description->description()->contents()[mediacontent_index];
6314 } else {
6315 return RTCError(RTCErrorType::INVALID_RANGE,
6316 "Media line index (" +
6317 rtc::ToString(candidate->sdp_mline_index()) +
6318 ") out of range (number of mlines: " +
6319 rtc::ToString(content_size) + ").");
6320 }
6321 } else if (!candidate->sdp_mid().empty()) {
6322 auto& contents = description->description()->contents();
6323 auto it = absl::c_find_if(
6324 contents, [candidate](const cricket::ContentInfo& content_info) {
6325 return content_info.mid() == candidate->sdp_mid();
6326 });
6327 if (it == contents.end()) {
6328 return RTCError(
6329 RTCErrorType::INVALID_PARAMETER,
6330 "Mid " + candidate->sdp_mid() +
6331 " specified but no media section with that mid found.");
6332 } else {
6333 return &*it;
6334 }
6335 }
6336
6337 return RTCError(RTCErrorType::INVALID_PARAMETER,
6338 "Neither sdp_mline_index nor sdp_mid specified.");
6339}
6340
Steve Anton75737c02017-11-06 10:37:17 -08006341void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006342 // Destroy video channel first since it may have a pointer to the
6343 // voice channel.
6344 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006345 if (!video_info || video_info->rejected) {
6346 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006347 }
6348
Steve Anton6fec8802017-12-04 10:37:29 -08006349 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6350 if (!audio_info || audio_info->rejected) {
6351 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006352 }
6353
6354 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6355 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006356 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006357 }
6358}
6359
Steve Antondcc3c022017-12-22 16:02:54 -08006360RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6361 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006362 const cricket::ContentGroup* bundle_group = nullptr;
6363 if (configuration_.bundle_policy ==
6364 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006365 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006366 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006367 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6368 "max-bundle configured but session description "
6369 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006370 }
6371 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006372 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006373}
6374
6375RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006376 // Creating the media channels. Transports should already have been created
6377 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006378 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006379 if (voice && !voice->rejected &&
6380 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006381 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006382 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006383 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6384 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006385 }
6386 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6387 }
6388
Steve Antondcc3c022017-12-22 16:02:54 -08006389 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006390 if (video && !video->rejected &&
6391 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006392 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006393 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006394 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6395 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006396 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006397 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006398 }
6399
Steve Antondcc3c022017-12-22 16:02:54 -08006400 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006401 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006402 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006403 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006404 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6405 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006406 }
6407 }
6408
Steve Anton8a006912017-12-04 15:25:56 -08006409 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006410}
6411
Steve Anton4171afb2017-11-20 10:20:22 -08006412// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006413cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006414 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006415 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006416 MediaTransportConfig media_transport_config =
6417 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006418
Steve Anton75737c02017-11-06 10:37:17 -08006419 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006420 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006421 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6422 GetCryptoOptions(), &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006423 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006424 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006425 }
Steve Anton75737c02017-11-06 10:37:17 -08006426 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6427 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006428 voice_channel->SignalSentPacket.connect(this,
6429 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006430 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006431
Steve Antoneda6ccd2017-12-04 10:21:55 -08006432 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006433}
6434
Steve Anton4171afb2017-11-20 10:20:22 -08006435// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006436cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006437 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006438 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006439 MediaTransportConfig media_transport_config =
6440 transport_controller_->GetMediaTransportConfig(mid);
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006441
Steve Anton75737c02017-11-06 10:37:17 -08006442 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006443 call_ptr_, configuration_.media_config, rtp_transport,
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006444 media_transport_config, signaling_thread(), mid, SrtpRequired(),
6445 GetCryptoOptions(), &ssrc_generator_, video_options_,
Anton Sukhanov4f08faa2019-05-21 11:12:57 -07006446 video_bitrate_allocator_factory_.get());
Steve Anton75737c02017-11-06 10:37:17 -08006447 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006448 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006449 }
Steve Anton75737c02017-11-06 10:37:17 -08006450 video_channel->SignalDtlsSrtpSetupFailure.connect(
6451 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006452 video_channel->SignalSentPacket.connect(this,
6453 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006454 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006455
Steve Antoneda6ccd2017-12-04 10:21:55 -08006456 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006457}
6458
Zhi Huange830e682018-03-30 10:48:35 -07006459bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006460 switch (data_channel_type_) {
6461 case cricket::DCT_MEDIA_TRANSPORT:
6462 if (network_thread()->Invoke<bool>(
6463 RTC_FROM_HERE,
6464 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6465 this, mid))) {
6466 for (const auto& channel : sctp_data_channels_) {
6467 channel->OnTransportChannelCreated();
6468 }
6469 return true;
6470 }
Steve Anton75737c02017-11-06 10:37:17 -08006471 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006472 case cricket::DCT_SCTP:
6473 if (!sctp_factory_) {
6474 RTC_LOG(LS_ERROR)
6475 << "Trying to create SCTP transport, but didn't compile with "
6476 "SCTP support (HAVE_SCTP)";
6477 return false;
6478 }
6479 if (!network_thread()->Invoke<bool>(
6480 RTC_FROM_HERE,
6481 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6482 return false;
6483 }
6484 for (const auto& channel : sctp_data_channels_) {
6485 channel->OnTransportChannelCreated();
6486 }
6487 return true;
6488 case cricket::DCT_RTP:
6489 default:
6490 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6491 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6492 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006493 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006494 if (!rtp_data_channel_) {
6495 return false;
6496 }
6497 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6498 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6499 rtp_data_channel_->SignalSentPacket.connect(
6500 this, &PeerConnection::OnSentPacket_w);
6501 rtp_data_channel_->SetRtpTransport(rtp_transport);
6502 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006503 }
6504
Steve Anton75737c02017-11-06 10:37:17 -08006505 return true;
6506}
6507
6508Call::Stats PeerConnection::GetCallStats() {
6509 if (!worker_thread()->IsCurrent()) {
6510 return worker_thread()->Invoke<Call::Stats>(
6511 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6512 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006513 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006514 if (call_) {
6515 return call_->GetStats();
6516 } else {
6517 return Call::Stats();
6518 }
6519}
6520
Zhi Huange830e682018-03-30 10:48:35 -07006521bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006522 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006523 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006524 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6525 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006526 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006527 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006528 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006529 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6530 sctp_factory_->CreateSctpTransport(dtls_transport);
6531 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006532 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006533 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006534 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006535 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006536 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006537 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6538 // another thread. Would be nice if there was a helper class similar to
6539 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6540 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006541 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006542 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006543 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006544 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006545 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006546 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6547 std::move(cricket_sctp_transport));
6548 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006549 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006550}
6551
6552void PeerConnection::DestroySctpTransport_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006553 RTC_DCHECK_RUN_ON(network_thread());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006554 sctp_transport_->Clear();
6555 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006556 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006557 sctp_invoker_.reset(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08006558}
6559
6560void PeerConnection::OnSctpTransportReadyToSendData_n() {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006561 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006562 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006563 // Note: Cannot use rtc::Bind here because it will grab a reference to
6564 // PeerConnection and potentially cause PeerConnection to live longer than
6565 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6566 // be destroyed before PeerConnection is destroyed, and at that point all
6567 // pending tasks will be cleared.
6568 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6569 OnSctpTransportReadyToSendData_s(true);
6570 });
6571}
6572
6573void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
Karl Wiberg2cc368f2019-04-02 11:31:56 +02006574 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006575 sctp_ready_to_send_data_ = ready;
6576 SignalSctpReadyToSendData(ready);
6577}
6578
6579void PeerConnection::OnSctpTransportDataReceived_n(
6580 const cricket::ReceiveDataParams& params,
6581 const rtc::CopyOnWriteBuffer& payload) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006582 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006583 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006584 // Note: Cannot use rtc::Bind here because it will grab a reference to
6585 // PeerConnection and potentially cause PeerConnection to live longer than
6586 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6587 // be destroyed before PeerConnection is destroyed, and at that point all
6588 // pending tasks will be cleared.
6589 sctp_invoker_->AsyncInvoke<void>(
6590 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6591 OnSctpTransportDataReceived_s(params, payload);
6592 });
6593}
6594
6595void PeerConnection::OnSctpTransportDataReceived_s(
6596 const cricket::ReceiveDataParams& params,
6597 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006598 RTC_DCHECK_RUN_ON(signaling_thread());
6599 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006600 SignalSctpDataReceived(params, payload);
6601 }
6602}
6603
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006604void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006605 RTC_DCHECK_RUN_ON(network_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006606 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Steve Anton75737c02017-11-06 10:37:17 -08006607 sctp_invoker_->AsyncInvoke<void>(
6608 RTC_FROM_HERE, signaling_thread(),
6609 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006610 &SignalSctpClosingProcedureStartedRemotely, sid));
6611}
6612
6613void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
Karl Wiberg7a651c6e2019-04-02 13:00:46 +02006614 RTC_DCHECK_RUN_ON(network_thread());
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006615 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006616 sctp_invoker_->AsyncInvoke<void>(
6617 RTC_FROM_HERE, signaling_thread(),
6618 rtc::Bind(&sigslot::signal1<int>::operator(),
6619 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006620}
6621
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006622bool PeerConnection::SetupMediaTransportForDataChannels_n(
6623 const std::string& mid) {
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006624 media_transport_ =
6625 transport_controller_->GetMediaTransportForDataChannel(mid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006626 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006627 RTC_LOG(LS_ERROR)
6628 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006629 return false;
6630 }
6631
6632 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6633 media_transport_->SetDataSink(this);
6634 media_transport_data_mid_ = mid;
6635 transport_controller_->SignalMediaTransportStateChanged.connect(
6636 this, &PeerConnection::OnMediaTransportStateChanged_n);
6637 // Check the initial state right away, in case transport is already writable.
6638 OnMediaTransportStateChanged_n();
6639 return true;
6640}
6641
6642void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6643 if (!media_transport_) {
6644 return;
6645 }
6646 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6647 media_transport_data_mid_.reset();
6648 media_transport_->SetDataSink(nullptr);
6649 media_transport_invoker_ = nullptr;
6650 media_transport_ = nullptr;
6651}
6652
6653void PeerConnection::OnMediaTransportStateChanged_n() {
6654 if (!media_transport_data_mid_ ||
6655 transport_controller_->GetMediaTransportState(
6656 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6657 return;
6658 }
6659 media_transport_invoker_->AsyncInvoke<void>(
6660 RTC_FROM_HERE, signaling_thread(), [this] {
6661 RTC_DCHECK_RUN_ON(signaling_thread());
6662 media_transport_ready_to_send_data_ = true;
6663 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6664 });
6665}
6666
Steve Anton75737c02017-11-06 10:37:17 -08006667// Returns false if bundle is enabled and rtcp_mux is disabled.
6668bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6669 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6670 if (!bundle_enabled)
6671 return true;
6672
6673 const cricket::ContentGroup* bundle_group =
6674 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6675 RTC_DCHECK(bundle_group != NULL);
6676
6677 const cricket::ContentInfos& contents = desc->contents();
6678 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6679 citer != contents.end(); ++citer) {
6680 const cricket::ContentInfo* content = (&*citer);
6681 RTC_DCHECK(content != NULL);
6682 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006683 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006684 if (!HasRtcpMuxEnabled(content))
6685 return false;
6686 }
6687 }
6688 // RTCP-MUX is enabled in all the contents.
6689 return true;
6690}
6691
6692bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006693 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006694}
6695
Steve Anton06817cd2018-12-18 15:55:30 -08006696static RTCError ValidateMids(const cricket::SessionDescription& description) {
6697 std::set<std::string> mids;
6698 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006699 if (content.name.empty()) {
6700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6701 "A media section is missing a MID attribute.");
6702 }
Steve Anton06817cd2018-12-18 15:55:30 -08006703 if (!mids.insert(content.name).second) {
6704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6705 "Duplicate a=mid value '" + content.name + "'.");
6706 }
6707 }
6708 return RTCError::OK();
6709}
6710
Steve Anton8a006912017-12-04 15:25:56 -08006711RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006712 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006713 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006714 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006715 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006716 }
6717
6718 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006719 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006720 }
6721
Steve Anton3828c062017-12-06 10:34:51 -08006722 SdpType type = sdesc->GetType();
6723 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6724 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006725 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006726 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006727 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006728 }
6729
Steve Anton06817cd2018-12-18 15:55:30 -08006730 RTCError error = ValidateMids(*sdesc->description());
6731 if (!error.ok()) {
6732 return error;
6733 }
6734
Steve Anton75737c02017-11-06 10:37:17 -08006735 // Verify crypto settings.
6736 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006737 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6738 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006739 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006740 if (!crypto_error.ok()) {
6741 return crypto_error;
6742 }
Steve Anton75737c02017-11-06 10:37:17 -08006743 }
6744
6745 // Verify ice-ufrag and ice-pwd.
6746 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006747 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6748 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006749 }
6750
6751 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006752 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6753 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006754 }
6755
6756 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6757 // m-lines that do not rtcp-mux enabled.
6758
6759 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006760 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006761 // With an answer we want to compare the new answer session description with
6762 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006763 const cricket::SessionDescription* offer_desc =
6764 (source == cricket::CS_LOCAL) ? remote_description()->description()
6765 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006766 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6767 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6768 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006769 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6770 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006771 }
6772 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006773 // The re-offers should respect the order of m= sections in current
6774 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006775 // With a re-offer, either the current local or current remote descriptions
6776 // could be the most up to date, so we would like to check against both of
6777 // them if they exist. It could be the case that one of them has a 0 port
6778 // for a media section, but the other does not. This is important to check
6779 // against in the case that we are recycling an m= section.
6780 const cricket::SessionDescription* current_desc = nullptr;
6781 const cricket::SessionDescription* secondary_current_desc = nullptr;
6782 if (local_description()) {
6783 current_desc = local_description()->description();
6784 if (remote_description()) {
6785 secondary_current_desc = remote_description()->description();
6786 }
6787 } else if (remote_description()) {
6788 current_desc = remote_description()->description();
6789 }
Steve Anton75737c02017-11-06 10:37:17 -08006790 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006791 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6792 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006793 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6794 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006795 }
6796 }
6797
Steve Antonba42e992018-04-09 14:10:01 -07006798 if (IsUnifiedPlan()) {
6799 // Ensure that each audio and video media section has at most one
6800 // "StreamParams". This will return an error if receiving a session
6801 // description from a "Plan B" endpoint which adds multiple tracks of the
6802 // same type. With Unified Plan, there can only be at most one track per
6803 // media section.
6804 for (const ContentInfo& content : sdesc->description()->contents()) {
Harald Alvestrand1716d392019-06-03 20:35:45 +02006805 const MediaContentDescription& desc = *content.media_description();
Steve Antonba42e992018-04-09 14:10:01 -07006806 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6807 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6808 desc.streams().size() > 1u) {
6809 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6810 "Media section has more than one track specified "
6811 "with a=ssrc lines which is not supported with "
6812 "Unified Plan.");
6813 }
6814 }
6815 }
6816
Steve Anton8a006912017-12-04 15:25:56 -08006817 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006818}
6819
Steve Anton3828c062017-12-06 10:34:51 -08006820bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006821 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006822 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006823 return (state == PeerConnectionInterface::kStable) ||
6824 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006825 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006826 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006827 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6828 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6829 }
6830}
6831
Steve Anton3828c062017-12-06 10:34:51 -08006832bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006833 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006834 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006835 return (state == PeerConnectionInterface::kStable) ||
6836 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006837 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006838 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006839 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6840 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6841 }
6842}
6843
Steve Antonf8470812017-12-04 10:46:21 -08006844const char* PeerConnection::SessionErrorToString(SessionError error) const {
6845 switch (error) {
6846 case SessionError::kNone:
6847 return "ERROR_NONE";
6848 case SessionError::kContent:
6849 return "ERROR_CONTENT";
6850 case SessionError::kTransport:
6851 return "ERROR_TRANSPORT";
6852 }
6853 RTC_NOTREACHED();
6854 return "";
6855}
6856
Steve Anton75737c02017-11-06 10:37:17 -08006857std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006858 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006859 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6860 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006861 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006862}
6863
Steve Anton8e20f172018-03-06 10:55:04 -08006864void PeerConnection::ReportSdpFormatReceived(
6865 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006866 int num_audio_mlines = 0;
6867 int num_video_mlines = 0;
6868 int num_audio_tracks = 0;
6869 int num_video_tracks = 0;
6870 for (const ContentInfo& content : remote_offer.description()->contents()) {
6871 cricket::MediaType media_type = content.media_description()->type();
6872 int num_tracks = std::max(
6873 1, static_cast<int>(content.media_description()->streams().size()));
6874 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6875 num_audio_mlines += 1;
6876 num_audio_tracks += num_tracks;
6877 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6878 num_video_mlines += 1;
6879 num_video_tracks += num_tracks;
6880 }
6881 }
6882 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6883 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6884 format = kSdpFormatReceivedComplexUnifiedPlan;
6885 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6886 format = kSdpFormatReceivedComplexPlanB;
6887 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6888 format = kSdpFormatReceivedSimple;
6889 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006890 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6891 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006892}
6893
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006894void PeerConnection::NoteUsageEvent(UsageEvent event) {
6895 RTC_DCHECK_RUN_ON(signaling_thread());
6896 usage_event_accumulator_ |= static_cast<int>(event);
6897}
6898
6899void PeerConnection::ReportUsagePattern() const {
6900 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006901 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6902 usage_event_accumulator_,
6903 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006904 const int bad_bits =
6905 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6906 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6907 const int good_bits =
6908 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6909 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6910 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6911 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6912 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006913 // If called after close(), we can't report, because observer may have
6914 // been deallocated, and therefore pointer is null. Write to log instead.
6915 if (observer_) {
6916 Observer()->OnInterestingUsage(usage_event_accumulator_);
6917 } else {
6918 RTC_LOG(LS_INFO) << "Interesting usage signature "
6919 << usage_event_accumulator_
6920 << " observed after observer shutdown";
6921 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006922 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006923}
6924
Steve Anton0ffaaa22018-02-23 10:31:30 -08006925void PeerConnection::ReportNegotiatedSdpSemantics(
6926 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006927 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006928 switch (answer.description()->msid_signaling()) {
6929 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006930 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006931 break;
6932 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006933 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006934 break;
6935 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006936 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006937 break;
6938 case cricket::kMsidSignalingMediaSection |
6939 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006940 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006941 break;
6942 default:
6943 RTC_NOTREACHED();
6944 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006945 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6946 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006947}
6948
Steve Anton75737c02017-11-06 10:37:17 -08006949// We need to check the local/remote description for the Transport instead of
6950// the session, because a new Transport added during renegotiation may have
6951// them unset while the session has them set from the previous negotiation.
6952// Not doing so may trigger the auto generation of transport description and
6953// mess up DTLS identity information, ICE credential, etc.
6954bool PeerConnection::ReadyToUseRemoteCandidate(
6955 const IceCandidateInterface* candidate,
6956 const SessionDescriptionInterface* remote_desc,
6957 bool* valid) {
6958 *valid = true;
6959
6960 const SessionDescriptionInterface* current_remote_desc =
6961 remote_desc ? remote_desc : remote_description();
6962
6963 if (!current_remote_desc) {
6964 return false;
6965 }
6966
Guido Urdaneta41633172019-05-23 20:12:29 +02006967 RTCErrorOr<const cricket::ContentInfo*> result =
6968 FindContentInfo(current_remote_desc, candidate);
6969 if (!result.ok()) {
6970 RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
6971 << result.error().message();
Steve Anton75737c02017-11-06 10:37:17 -08006972
6973 *valid = false;
6974 return false;
6975 }
6976
Guido Urdaneta41633172019-05-23 20:12:29 +02006977 std::string transport_name = GetTransportName(result.value()->name);
6978 return !transport_name.empty();
Steve Anton75737c02017-11-06 10:37:17 -08006979}
6980
6981bool PeerConnection::SrtpRequired() const {
Bjorn A Mellem5985a042019-06-28 14:19:38 -07006982 return !use_datagram_transport_ &&
Anton Sukhanov316f3ac2019-05-23 15:50:38 -07006983 (dtls_enabled_ ||
6984 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
Steve Anton75737c02017-11-06 10:37:17 -08006985}
6986
6987void PeerConnection::OnTransportControllerGatheringState(
6988 cricket::IceGatheringState state) {
6989 RTC_DCHECK(signaling_thread()->IsCurrent());
6990 if (state == cricket::kIceGatheringGathering) {
6991 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6992 } else if (state == cricket::kIceGatheringComplete) {
6993 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6994 }
6995}
6996
6997void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006998 std::map<std::string, std::set<cricket::MediaType>>
6999 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01007000 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007001 if (transceiver->internal()->channel()) {
7002 const std::string& transport_name =
7003 transceiver->internal()->channel()->transport_name();
7004 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08007005 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08007006 }
Steve Anton75737c02017-11-06 10:37:17 -08007007 }
7008 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007009 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
7010 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007011 }
Zhi Huange830e682018-03-30 10:48:35 -07007012
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02007013 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07007014 if (transport_name) {
7015 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08007016 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08007017 }
Zhi Huange830e682018-03-30 10:48:35 -07007018
Steve Antonc7b964c2018-02-01 14:39:45 -08007019 for (const auto& entry : media_types_by_transport_name) {
7020 const std::string& transport_name = entry.first;
7021 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08007022 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08007023 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08007024 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08007025 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08007026 }
7027 }
7028}
7029// Walk through the ConnectionInfos to gather best connection usage
7030// for IPv4 and IPv6.
7031void PeerConnection::ReportBestConnectionState(
7032 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08007033 for (const cricket::TransportChannelStats& channel_stats :
7034 stats.channel_stats) {
7035 for (const cricket::ConnectionInfo& connection_info :
7036 channel_stats.connection_infos) {
7037 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08007038 continue;
7039 }
7040
Steve Antonc7b964c2018-02-01 14:39:45 -08007041 const cricket::Candidate& local = connection_info.local_candidate;
7042 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08007043
7044 // Increment the counter for IceCandidatePairType.
7045 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
7046 (local.type() == RELAY_PORT_TYPE &&
7047 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007048 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
7049 GetIceCandidatePairCounter(local, remote),
7050 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007051 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007052 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
7053 GetIceCandidatePairCounter(local, remote),
7054 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08007055 } else {
7056 RTC_CHECK(0);
7057 }
Steve Anton75737c02017-11-06 10:37:17 -08007058
7059 // Increment the counter for IP type.
7060 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007061 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7062 kBestConnections_IPv4,
7063 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007064 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007065 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
7066 kBestConnections_IPv6,
7067 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08007068 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08007069 RTC_CHECK(!local.address().hostname().empty() &&
7070 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08007071 }
7072
7073 return;
7074 }
7075 }
7076}
7077
7078void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08007079 const cricket::TransportStats& stats,
7080 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08007081 if (!dtls_enabled_ || stats.channel_stats.empty()) {
7082 return;
7083 }
7084
7085 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
7086 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
7087 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
7088 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
7089 return;
7090 }
7091
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007092 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
7093 for (cricket::MediaType media_type : media_types) {
7094 switch (media_type) {
7095 case cricket::MEDIA_TYPE_AUDIO:
7096 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7097 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
7098 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7099 break;
7100 case cricket::MEDIA_TYPE_VIDEO:
7101 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7102 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
7103 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7104 break;
7105 case cricket::MEDIA_TYPE_DATA:
7106 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7107 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
7108 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
7109 break;
7110 default:
7111 RTC_NOTREACHED();
7112 continue;
7113 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007114 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07007115 }
7116
7117 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
7118 for (cricket::MediaType media_type : media_types) {
7119 switch (media_type) {
7120 case cricket::MEDIA_TYPE_AUDIO:
7121 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7122 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
7123 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7124 break;
7125 case cricket::MEDIA_TYPE_VIDEO:
7126 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7127 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
7128 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7129 break;
7130 case cricket::MEDIA_TYPE_DATA:
7131 RTC_HISTOGRAM_ENUMERATION_SPARSE(
7132 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
7133 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
7134 break;
7135 default:
7136 RTC_NOTREACHED();
7137 continue;
7138 }
Steve Antonc7b964c2018-02-01 14:39:45 -08007139 }
Steve Anton75737c02017-11-06 10:37:17 -08007140 }
7141}
7142
7143void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007144 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08007145 RTC_DCHECK(call_);
7146 call_->OnSentPacket(sent_packet);
7147}
7148
7149const std::string PeerConnection::GetTransportName(
7150 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007151 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08007152 if (channel) {
7153 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08007154 }
Steve Anton6fec8802017-12-04 10:37:29 -08007155 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07007156 RTC_DCHECK(sctp_mid_);
7157 if (content_name == *sctp_mid_) {
7158 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08007159 }
7160 }
7161 // Return an empty string if failed to retrieve the transport name.
7162 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007163}
7164
Steve Anton6fec8802017-12-04 10:37:29 -08007165void PeerConnection::DestroyTransceiverChannel(
7166 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7167 transceiver) {
7168 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007169
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007170 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007171 if (channel) {
7172 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007173 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007174 }
7175}
7176
7177void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007178 if (rtp_data_channel_) {
7179 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007180 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007181 rtp_data_channel_ = nullptr;
7182 }
7183
7184 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7185 // grab a reference to this PeerConnection. If this is called from the
7186 // PeerConnection destructor, the RefCountedObject vtable will have already
7187 // been destroyed (since it is a subclass of PeerConnection) and using
7188 // rtc::Bind will cause "Pure virtual function called" error to appear.
7189
7190 if (sctp_transport_) {
7191 OnDataChannelDestroyed();
7192 network_thread()->Invoke<void>(RTC_FROM_HERE,
7193 [this] { DestroySctpTransport_n(); });
Karl Wiberg2cc368f2019-04-02 11:31:56 +02007194 sctp_ready_to_send_data_ = false;
Steve Anton6fec8802017-12-04 10:37:29 -08007195 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007196
7197 if (media_transport_) {
7198 OnDataChannelDestroyed();
7199 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7200 RTC_DCHECK_RUN_ON(network_thread());
7201 TeardownMediaTransportForDataChannels_n();
7202 });
7203 }
Steve Anton6fec8802017-12-04 10:37:29 -08007204}
7205
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007206void PeerConnection::DestroyChannelInterface(
7207 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007208 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007209 switch (channel->media_type()) {
7210 case cricket::MEDIA_TYPE_AUDIO:
7211 channel_manager()->DestroyVoiceChannel(
7212 static_cast<cricket::VoiceChannel*>(channel));
7213 break;
7214 case cricket::MEDIA_TYPE_VIDEO:
7215 channel_manager()->DestroyVideoChannel(
7216 static_cast<cricket::VideoChannel*>(channel));
7217 break;
7218 case cricket::MEDIA_TYPE_DATA:
7219 channel_manager()->DestroyRtpDataChannel(
7220 static_cast<cricket::RtpDataChannel*>(channel));
7221 break;
7222 default:
7223 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7224 break;
7225 }
Zhi Huange830e682018-03-30 10:48:35 -07007226}
Steve Anton6fec8802017-12-04 10:37:29 -08007227
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007228bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007229 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007230 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007231 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007232 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007233 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007234 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007235 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007236 auto base_channel = GetChannel(mid);
7237 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007238 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007239 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007240 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007241 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007242 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007243
Karl Wiberg5966c502019-02-21 23:55:09 +01007244 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007245 // Only pass media transport to call object if media transport is used
7246 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007247 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007248 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007249
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007250 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007251}
7252
Guido Urdaneta1ff16c82019-05-20 19:31:53 +02007253void PeerConnection::OnSetStreams() {
7254 RTC_DCHECK_RUN_ON(signaling_thread());
7255 if (IsUnifiedPlan())
7256 UpdateNegotiationNeeded();
7257}
7258
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007259PeerConnectionObserver* PeerConnection::Observer() const {
7260 // In earlier production code, the pointer was not cleared on close,
7261 // which might have led to undefined behavior if the observer was not
7262 // deallocated, or strange crashes if it was.
7263 // We use CHECK in order to catch such behavior if it exists.
7264 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7265 RTC_CHECK(observer_);
7266 return observer_;
7267}
7268
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007269CryptoOptions PeerConnection::GetCryptoOptions() {
7270 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7271 // after it has been removed.
7272 return configuration_.crypto_options.has_value()
7273 ? *configuration_.crypto_options
7274 : factory_->options().crypto_options;
7275}
7276
Harald Alvestrand89061872018-01-02 14:08:34 +01007277void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007278 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007279 if (stats_collector_) {
7280 stats_collector_->ClearCachedStatsReport();
7281 }
7282}
7283
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007284void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007285 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7286 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007287}
7288
Guido Urdaneta70c2db12019-04-16 12:24:14 +02007289void PeerConnection::UpdateNegotiationNeeded() {
7290 RTC_DCHECK_RUN_ON(signaling_thread());
7291 if (!IsUnifiedPlan()) {
7292 Observer()->OnRenegotiationNeeded();
7293 return;
7294 }
7295
7296 // If connection's [[IsClosed]] slot is true, abort these steps.
7297 if (IsClosed())
7298 return;
7299
7300 // If connection's signaling state is not "stable", abort these steps.
7301 if (signaling_state() != kStable)
7302 return;
7303
7304 // NOTE
7305 // The negotiation-needed flag will be updated once the state transitions to
7306 // "stable", as part of the steps for setting an RTCSessionDescription.
7307
7308 // If the result of checking if negotiation is needed is false, clear the
7309 // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
7310 // to false, and abort these steps.
7311 bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
7312 if (!is_negotiation_needed) {
7313 is_negotiation_needed_ = false;
7314 return;
7315 }
7316
7317 // If connection's [[NegotiationNeeded]] slot is already true, abort these
7318 // steps.
7319 if (is_negotiation_needed_)
7320 return;
7321
7322 // Set connection's [[NegotiationNeeded]] slot to true.
7323 is_negotiation_needed_ = true;
7324
7325 // Queue a task that runs the following steps:
7326 // If connection's [[IsClosed]] slot is true, abort these steps.
7327 // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
7328 // Fire an event named negotiationneeded at connection.
7329 Observer()->OnRenegotiationNeeded();
7330}
7331
7332bool PeerConnection::CheckIfNegotiationIsNeeded() {
7333 RTC_DCHECK_RUN_ON(signaling_thread());
7334 // 1. If any implementation-specific negotiation is required, as described at
7335 // the start of this section, return true.
7336
7337 // 2. Let description be connection.[[CurrentLocalDescription]].
7338 const SessionDescriptionInterface* description = current_local_description();
7339 if (!description)
7340 return true;
7341
7342 // 3. If connection has created any RTCDataChannels, and no m= section in
7343 // description has been negotiated yet for data, return true.
7344 if (!sctp_data_channels_.empty()) {
7345 if (!cricket::GetFirstDataContent(description->description()->contents()))
7346 return true;
7347 }
7348
7349 // 4. For each transceiver in connection's set of transceivers, perform the
7350 // following checks:
7351 for (const auto& transceiver : transceivers_) {
7352 const ContentInfo* current_local_msection =
7353 FindTransceiverMSection(transceiver.get(), description);
7354
7355 const ContentInfo* current_remote_msection = FindTransceiverMSection(
7356 transceiver.get(), current_remote_description());
7357
7358 // 4.3 If transceiver is stopped and is associated with an m= section,
7359 // but the associated m= section is not yet rejected in
7360 // connection.[[CurrentLocalDescription]] or
7361 // connection.[[CurrentRemoteDescription]], return true.
7362 if (transceiver->stopped()) {
7363 if (current_local_msection && !current_local_msection->rejected &&
7364 ((current_remote_msection && !current_remote_msection->rejected) ||
7365 !current_remote_msection)) {
7366 return true;
7367 }
7368 continue;
7369 }
7370
7371 // 4.1 If transceiver isn't stopped and isn't yet associated with an m=
7372 // section in description, return true.
7373 if (!current_local_msection)
7374 return true;
7375
7376 const MediaContentDescription* current_local_media_description =
7377 current_local_msection->media_description();
7378 // 4.2 If transceiver isn't stopped and is associated with an m= section
7379 // in description then perform the following checks:
7380
7381 // 4.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
7382 // associated m= section in description either doesn't contain a single
7383 // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
7384 // m= section, or the MSID values themselves, differ from what is in
7385 // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
7386 if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
7387 if (current_local_media_description->streams().size() == 0)
7388 return true;
7389
7390 std::vector<std::string> msection_msids;
7391 for (const auto& stream : current_local_media_description->streams()) {
7392 for (const std::string& msid : stream.stream_ids())
7393 msection_msids.push_back(msid);
7394 }
7395
7396 std::vector<std::string> transceiver_msids =
7397 transceiver->sender()->stream_ids();
7398 if (msection_msids.size() != transceiver_msids.size())
7399 return true;
7400
7401 absl::c_sort(transceiver_msids);
7402 absl::c_sort(msection_msids);
7403 if (transceiver_msids != msection_msids)
7404 return true;
7405 }
7406
7407 // 4.2.2 If description is of type "offer", and the direction of the
7408 // associated m= section in neither connection.[[CurrentLocalDescription]]
7409 // nor connection.[[CurrentRemoteDescription]] matches
7410 // transceiver.[[Direction]], return true.
7411 if (description->GetType() == SdpType::kOffer) {
7412 if (!current_remote_description())
7413 return true;
7414
7415 if (!current_remote_msection)
7416 return true;
7417
7418 RtpTransceiverDirection current_local_direction =
7419 current_local_media_description->direction();
7420 RtpTransceiverDirection current_remote_direction =
7421 current_remote_msection->media_description()->direction();
7422 if (transceiver->direction() != current_local_direction &&
7423 transceiver->direction() !=
7424 RtpTransceiverDirectionReversed(current_remote_direction)) {
7425 return true;
7426 }
7427 }
7428
7429 // 4.2.3 If description is of type "answer", and the direction of the
7430 // associated m= section in the description does not match
7431 // transceiver.[[Direction]] intersected with the offered direction (as
7432 // described in [JSEP] (section 5.3.1.)), return true.
7433 if (description->GetType() == SdpType::kAnswer) {
7434 if (!remote_description())
7435 return true;
7436
7437 const ContentInfo* offered_remote_msection =
7438 FindTransceiverMSection(transceiver.get(), remote_description());
7439
7440 RtpTransceiverDirection offered_direction =
7441 offered_remote_msection
7442 ? offered_remote_msection->media_description()->direction()
7443 : RtpTransceiverDirection::kInactive;
7444
7445 if (current_local_media_description->direction() !=
7446 (RtpTransceiverDirectionIntersection(
7447 transceiver->direction(),
7448 RtpTransceiverDirectionReversed(offered_direction)))) {
7449 return true;
7450 }
7451 }
7452 }
7453
7454 // If all the preceding checks were performed and true was not returned,
7455 // nothing remains to be negotiated; return false.
7456 return false;
7457}
7458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007459} // namespace webrtc