blob: 15bea89869fc4ab64ef6226698c2a17d44e870c6 [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"
27#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020030#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "logging/rtc_event_log/rtc_event_log.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010033#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080035#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "pc/channel_manager.h"
37#include "pc/dtmf_sender.h"
38#include "pc/media_stream.h"
39#include "pc/media_stream_observer.h"
40#include "pc/remote_audio_source.h"
41#include "pc/rtp_media_utils.h"
42#include "pc/rtp_receiver.h"
43#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010044#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "pc/sctp_utils.h"
46#include "pc/sdp_utils.h"
47#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010048#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/bind.h"
51#include "rtc_base/checks.h"
52#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010053#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080054#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020055#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020056#include "rtc_base/trace_event.h"
57#include "system_wrappers/include/clock.h"
58#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070059#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::ContentInfo;
62using cricket::ContentInfos;
63using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080064using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080065using cricket::RidDescription;
66using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080067using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::SimulcastDescription;
69using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080072using cricket::TransportInfo;
73
74using cricket::LOCAL_PORT_TYPE;
75using cricket::STUN_PORT_TYPE;
76using cricket::RELAY_PORT_TYPE;
77using cricket::PRFLX_PORT_TYPE;
78
Steve Antonba818672017-11-06 10:21:57 -080079namespace webrtc {
80
Steve Anton75737c02017-11-06 10:37:17 -080081// Error messages
82const char kBundleWithoutRtcpMux[] =
83 "rtcp-mux must be enabled when BUNDLE "
84 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080085const char kInvalidCandidates[] = "Description contains invalid candidates.";
86const char kInvalidSdp[] = "Invalid session description.";
87const char kMlineMismatchInAnswer[] =
88 "The order of m-lines in answer doesn't match order in offer. Rejecting "
89 "answer.";
90const char kMlineMismatchInSubsequentOffer[] =
91 "The order of m-lines in subsequent offer doesn't match order from "
92 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080093const char kSdpWithoutDtlsFingerprint[] =
94 "Called with SDP without DTLS fingerprint.";
95const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
96const char kSdpWithoutIceUfragPwd[] =
97 "Called with SDP without ice-ufrag and ice-pwd.";
98const char kSessionError[] = "Session error code: ";
99const char kSessionErrorDesc[] = "Session error description: ";
100const char kDtlsSrtpSetupFailureRtp[] =
101 "Couldn't set up DTLS-SRTP on RTP channel.";
102const char kDtlsSrtpSetupFailureRtcp[] =
103 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104
Steve Anton75737c02017-11-06 10:37:17 -0800105namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800107// UMA metric names.
108const char kSimulcastVersionApplyLocalDescription[] =
109 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
110const char kSimulcastVersionApplyRemoteDescription[] =
111 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
112const char kSimulcastNumberOfEncodings[] =
113 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
114const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
115
Seth Hampson845e8782018-03-02 11:34:10 -0800116static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800117static const char kDefaultAudioSenderId[] = "defaulta0";
118static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700119
zhihuang8f65cdf2016-05-06 18:40:30 -0700120// The length of RTCP CNAMEs.
121static const int kRtcpCnameLength = 16;
122
Steve Antonad182762018-09-05 20:22:40 +0000123enum {
124 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
125 MSG_SET_SESSIONDESCRIPTION_FAILED,
126 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
127 MSG_GETSTATS,
128 MSG_FREE_DATACHANNELS,
129 MSG_REPORT_USAGE_PATTERN,
130};
131
Harald Alvestrand19793842018-06-25 12:03:50 +0200132static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
133
Steve Antonad182762018-09-05 20:22:40 +0000134struct SetSessionDescriptionMsg : public rtc::MessageData {
135 explicit SetSessionDescriptionMsg(
136 webrtc::SetSessionDescriptionObserver* observer)
137 : observer(observer) {}
138
139 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
140 RTCError error;
141};
142
143struct CreateSessionDescriptionMsg : public rtc::MessageData {
144 explicit CreateSessionDescriptionMsg(
145 webrtc::CreateSessionDescriptionObserver* observer)
146 : observer(observer) {}
147
148 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
149 RTCError error;
150};
151
152struct GetStatsMsg : public rtc::MessageData {
153 GetStatsMsg(webrtc::StatsObserver* observer,
154 webrtc::MediaStreamTrackInterface* track)
155 : observer(observer), track(track) {}
156 rtc::scoped_refptr<webrtc::StatsObserver> observer;
157 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
158};
159
deadbeefab9b2d12015-10-14 11:33:11 -0700160// Check if we can send |new_stream| on a PeerConnection.
161bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
162 webrtc::MediaStreamInterface* new_stream) {
163 if (!new_stream || !current_streams) {
164 return false;
165 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700166 if (current_streams->find(new_stream->id()) != nullptr) {
167 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100168 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700169 return false;
170 }
171 return true;
172}
173
deadbeef5e97fb52015-10-15 12:49:08 -0700174// If the direction is "recvonly" or "inactive", treat the description
175// as containing no streams.
176// See: https://code.google.com/p/webrtc/issues/detail?id=5054
177std::vector<cricket::StreamParams> GetActiveStreams(
178 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800179 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700180 ? desc->streams()
181 : std::vector<cricket::StreamParams>();
182}
183
deadbeefab9b2d12015-10-14 11:33:11 -0700184bool IsValidOfferToReceiveMedia(int value) {
185 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
186 return (value >= Options::kUndefined) &&
187 (value <= Options::kMaxOfferToReceiveMedia);
188}
189
zhihuang1c378ed2017-08-17 14:10:50 -0700190// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800191void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700192 const std::vector<rtc::scoped_refptr<
193 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700194 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200195 cricket::MediaDescriptionOptions* video_media_description_options,
196 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700197 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700198 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
199 if (audio_media_description_options) {
200 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700201 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700202 }
203 } else {
204 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
205 if (video_media_description_options) {
206 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800207 sender->id(), sender->internal()->stream_ids(), {},
208 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700209 }
210 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700211 }
zhihuang1c378ed2017-08-17 14:10:50 -0700212}
olka3c747662017-08-17 06:50:32 -0700213
zhihuang1c378ed2017-08-17 14:10:50 -0700214// Add options to |session_options| from |rtp_data_channels|.
215void AddRtpDataChannelOptions(
216 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
217 rtp_data_channels,
218 cricket::MediaDescriptionOptions* data_media_description_options) {
219 if (!data_media_description_options) {
220 return;
221 }
deadbeefab9b2d12015-10-14 11:33:11 -0700222 // Check for data channels.
223 for (const auto& kv : rtp_data_channels) {
224 const DataChannel* channel = kv.second;
225 if (channel->state() == DataChannel::kConnecting ||
226 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700227 // Legacy RTP data channels are signaled with the track/stream ID set to
228 // the data channel's label.
229 data_media_description_options->AddRtpDataChannel(channel->label(),
230 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700231 }
232 }
233}
234
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700235uint32_t ConvertIceTransportTypeToCandidateFilter(
236 PeerConnectionInterface::IceTransportsType type) {
237 switch (type) {
238 case PeerConnectionInterface::kNone:
239 return cricket::CF_NONE;
240 case PeerConnectionInterface::kRelay:
241 return cricket::CF_RELAY;
242 case PeerConnectionInterface::kNoHost:
243 return (cricket::CF_ALL & ~cricket::CF_HOST);
244 case PeerConnectionInterface::kAll:
245 return cricket::CF_ALL;
246 default:
nissec80e7412017-01-11 05:56:46 -0800247 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700248 }
249 return cricket::CF_NONE;
250}
251
deadbeef293e9262017-01-11 12:28:30 -0800252// Helper to set an error and return from a method.
253bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
254 if (error) {
255 error->set_type(type);
256 }
257 return type == webrtc::RTCErrorType::NONE;
258}
259
Steve Anton038834f2017-07-14 15:59:59 -0700260bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700261 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700262 if (error_out) {
263 *error_out = std::move(error);
264 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700265 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700266}
267
Steve Antonba818672017-11-06 10:21:57 -0800268std::string GetSignalingStateString(
269 PeerConnectionInterface::SignalingState state) {
270 switch (state) {
271 case PeerConnectionInterface::kStable:
272 return "kStable";
273 case PeerConnectionInterface::kHaveLocalOffer:
274 return "kHaveLocalOffer";
275 case PeerConnectionInterface::kHaveLocalPrAnswer:
276 return "kHavePrAnswer";
277 case PeerConnectionInterface::kHaveRemoteOffer:
278 return "kHaveRemoteOffer";
279 case PeerConnectionInterface::kHaveRemotePrAnswer:
280 return "kHaveRemotePrAnswer";
281 case PeerConnectionInterface::kClosed:
282 return "kClosed";
283 }
284 RTC_NOTREACHED();
285 return "";
286}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700287
Steve Anton75737c02017-11-06 10:37:17 -0800288IceCandidatePairType GetIceCandidatePairCounter(
289 const cricket::Candidate& local,
290 const cricket::Candidate& remote) {
291 const auto& l = local.type();
292 const auto& r = remote.type();
293 const auto& host = LOCAL_PORT_TYPE;
294 const auto& srflx = STUN_PORT_TYPE;
295 const auto& relay = RELAY_PORT_TYPE;
296 const auto& prflx = PRFLX_PORT_TYPE;
297 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800298 bool local_hostname =
299 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
300 bool remote_hostname = !remote.address().hostname().empty() &&
301 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800302 bool local_private = IPIsPrivate(local.address().ipaddr());
303 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800304 if (local_hostname) {
305 if (remote_hostname) {
306 return kIceCandidatePairHostNameHostName;
307 } else if (remote_private) {
308 return kIceCandidatePairHostNameHostPrivate;
309 } else {
310 return kIceCandidatePairHostNameHostPublic;
311 }
312 } else if (local_private) {
313 if (remote_hostname) {
314 return kIceCandidatePairHostPrivateHostName;
315 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800316 return kIceCandidatePairHostPrivateHostPrivate;
317 } else {
318 return kIceCandidatePairHostPrivateHostPublic;
319 }
320 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800321 if (remote_hostname) {
322 return kIceCandidatePairHostPublicHostName;
323 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800324 return kIceCandidatePairHostPublicHostPrivate;
325 } else {
326 return kIceCandidatePairHostPublicHostPublic;
327 }
328 }
329 }
330 if (l == host && r == srflx)
331 return kIceCandidatePairHostSrflx;
332 if (l == host && r == relay)
333 return kIceCandidatePairHostRelay;
334 if (l == host && r == prflx)
335 return kIceCandidatePairHostPrflx;
336 if (l == srflx && r == host)
337 return kIceCandidatePairSrflxHost;
338 if (l == srflx && r == srflx)
339 return kIceCandidatePairSrflxSrflx;
340 if (l == srflx && r == relay)
341 return kIceCandidatePairSrflxRelay;
342 if (l == srflx && r == prflx)
343 return kIceCandidatePairSrflxPrflx;
344 if (l == relay && r == host)
345 return kIceCandidatePairRelayHost;
346 if (l == relay && r == srflx)
347 return kIceCandidatePairRelaySrflx;
348 if (l == relay && r == relay)
349 return kIceCandidatePairRelayRelay;
350 if (l == relay && r == prflx)
351 return kIceCandidatePairRelayPrflx;
352 if (l == prflx && r == host)
353 return kIceCandidatePairPrflxHost;
354 if (l == prflx && r == srflx)
355 return kIceCandidatePairPrflxSrflx;
356 if (l == prflx && r == relay)
357 return kIceCandidatePairPrflxRelay;
358 return kIceCandidatePairMax;
359}
360
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800361// Logic to decide if an m= section can be recycled. This means that the new
362// m= section is not rejected, but the old local or remote m= section is
363// rejected. |old_content_one| and |old_content_two| refer to the m= section
364// of the old remote and old local descriptions in no particular order.
365// We need to check both the old local and remote because either
366// could be the most current from the latest negotation.
367bool IsMediaSectionBeingRecycled(SdpType type,
368 const ContentInfo& content,
369 const ContentInfo* old_content_one,
370 const ContentInfo* old_content_two) {
371 return type == SdpType::kOffer && !content.rejected &&
372 ((old_content_one && old_content_one->rejected) ||
373 (old_content_two && old_content_two->rejected));
374}
375
Steve Anton75737c02017-11-06 10:37:17 -0800376// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800377// |current_desc|. The number of m= sections in |new_desc| should be no
378// less than |current_desc|. In the case of checking an answer's
379// |new_desc|, the |current_desc| is the last offer that was set as the
380// local or remote. In the case of checking an offer's |new_desc| we
381// check against the local and remote descriptions stored from the last
382// negotiation, because either of these could be the most up to date for
383// possible rejected m sections. These are the |current_desc| and
384// |secondary_current_desc|.
385bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
386 const SessionDescription* secondary_current_desc,
387 const SessionDescription& new_desc,
388 const SdpType type) {
389 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800390 return false;
391 }
392
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800393 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
394 const cricket::ContentInfo* secondary_content_info = nullptr;
395 if (secondary_current_desc &&
396 i < secondary_current_desc->contents().size()) {
397 secondary_content_info = &secondary_current_desc->contents()[i];
398 }
399 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
400 &current_desc.contents()[i],
401 secondary_content_info)) {
402 // For new offer descriptions, if the media section can be recycled, it's
403 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800404 continue;
405 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800406 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800407 return false;
408 }
409 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800410 new_desc.contents()[i].media_description();
411 const MediaContentDescription* current_desc_mdesc =
412 current_desc.contents()[i].media_description();
413 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800414 return false;
415 }
416 }
417 return true;
418}
419
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800420bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
421 const SessionDescription& desc2) {
422 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800423}
424
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700425void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
426 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200427 // Array of structs needed to map {KeyExchangeProtocolType,
428 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
429 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
430 static constexpr struct {
431 KeyExchangeProtocolType protocol_type;
432 cricket::MediaType media_type;
433 KeyExchangeProtocolMedia protocol_media;
434 } kEnumCounterKeyProtocolMediaMap[] = {
435 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
436 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
437 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
438 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
439 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
440 kEnumCounterKeyProtocolMediaTypeDtlsData},
441 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
442 kEnumCounterKeyProtocolMediaTypeSdesAudio},
443 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
444 kEnumCounterKeyProtocolMediaTypeSdesVideo},
445 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
446 kEnumCounterKeyProtocolMediaTypeSdesData},
447 };
448
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
450 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100451
Mirko Bonadeiab499822018-09-11 10:43:20 +0200452 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
453 if (i.protocol_type == protocol_type && i.media_type == media_type) {
454 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
455 i.protocol_media,
456 kEnumCounterKeyProtocolMediaTypeMax);
457 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100458 }
459}
460
Harald Alvestrand76829d72018-07-18 23:24:36 +0200461void NoteAddIceCandidateResult(int result) {
462 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
463 kAddIceCandidateMax);
464}
465
Steve Anton75737c02017-11-06 10:37:17 -0800466// Checks that each non-rejected content has SDES crypto keys or a DTLS
467// fingerprint, unless it's in a BUNDLE group, in which case only the
468// BUNDLE-tag section (first media section/description in the BUNDLE group)
469// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
470// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
471// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700472RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800473 const cricket::ContentGroup* bundle =
474 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800475 for (const cricket::ContentInfo& content_info : desc->contents()) {
476 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800477 continue;
478 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100479 // Note what media is used with each crypto protocol, for all sections.
480 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
481 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700482 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 // This isn't the first media section in the BUNDLE group, so it's not
487 // required to have crypto attributes, since only the crypto attributes
488 // from the first section actually get used.
489 continue;
490 }
491
492 // If the content isn't rejected or bundled into another m= section, crypto
493 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800494 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!media || !tinfo) {
497 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800499 }
500 if (dtls_enabled) {
501 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_WARNING)
503 << "Session description must have DTLS fingerprint if "
504 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800505 return RTCError(RTCErrorType::INVALID_PARAMETER,
506 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800507 }
508 } else {
509 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100510 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800511 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800512 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800513 }
514 }
515 }
Steve Anton8a006912017-12-04 15:25:56 -0800516 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800517}
518
519// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
520// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
521// media section/description in the BUNDLE group) needs a ufrag and pwd.
522bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
523 const cricket::ContentGroup* bundle =
524 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800525 for (const cricket::ContentInfo& content_info : desc->contents()) {
526 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 continue;
528 }
Steve Anton8a006912017-12-04 15:25:56 -0800529 const std::string& mid = content_info.name;
530 if (bundle && bundle->HasContentName(mid) &&
531 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800532 // This isn't the first media section in the BUNDLE group, so it's not
533 // required to have ufrag/password, since only the ufrag/password from
534 // the first section actually get used.
535 continue;
536 }
537
538 // If the content isn't rejected or bundled into another m= section,
539 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800540 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800541 if (!tinfo) {
542 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 if (tinfo->description.ice_ufrag.empty() ||
547 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100548 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800549 return false;
550 }
551 }
552 return true;
553}
554
Steve Anton75737c02017-11-06 10:37:17 -0800555// Get the SCTP port out of a SessionDescription.
556// Return -1 if not found.
557int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800558 const cricket::DataContentDescription* data_desc =
559 GetFirstDataContentDescription(session_description);
560 RTC_DCHECK(data_desc);
561 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800562 return -1;
563 }
Steve Anton75737c02017-11-06 10:37:17 -0800564 std::string value;
565 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
566 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800567 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800568 if (!codec.Matches(match_pattern)) {
569 continue;
570 }
571 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
572 return rtc::FromString<int>(value);
573 }
574 }
575 return -1;
576}
577
Steve Anton75737c02017-11-06 10:37:17 -0800578// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
579bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
580 const SessionDescriptionInterface* new_desc,
581 const std::string& content_name) {
582 if (!old_desc) {
583 return false;
584 }
585 const SessionDescription* new_sd = new_desc->description();
586 const SessionDescription* old_sd = old_desc->description();
587 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
588 if (!cinfo || cinfo->rejected) {
589 return false;
590 }
591 // If the content isn't rejected, check if ufrag and password has changed.
592 const cricket::TransportDescription* new_transport_desc =
593 new_sd->GetTransportDescriptionByName(content_name);
594 const cricket::TransportDescription* old_transport_desc =
595 old_sd->GetTransportDescriptionByName(content_name);
596 if (!new_transport_desc || !old_transport_desc) {
597 // No transport description exists. This is not an ICE restart.
598 return false;
599 }
600 if (cricket::IceCredentialsChanged(
601 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
602 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100603 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
604 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800605 return true;
606 }
607 return false;
608}
609
Steve Anton80dd7b52018-02-16 17:08:42 -0800610// Generates a string error message for SetLocalDescription/SetRemoteDescription
611// from an RTCError.
612std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
613 SdpType type,
614 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200615 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800616 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
617 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200618 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800619}
620
Seth Hampson5b4f0752018-04-02 16:31:36 -0700621std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
622 std::string output = "streams=[";
623 const char* separator = "";
624 for (const auto& stream_id : stream_ids) {
625 output.append(separator).append(stream_id);
626 separator = ", ";
627 }
628 output.append("]");
629 return output;
630}
631
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200632absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700633 int rtc_configuration_parameter) {
634 if (rtc_configuration_parameter ==
635 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200636 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700637 }
638 return rtc_configuration_parameter;
639}
640
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800641cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
642 switch (type) {
643 case DataMessageType::kText:
644 return cricket::DMT_TEXT;
645 case DataMessageType::kBinary:
646 return cricket::DMT_BINARY;
647 case DataMessageType::kControl:
648 return cricket::DMT_CONTROL;
649 default:
650 return cricket::DMT_NONE;
651 }
652 return cricket::DMT_NONE;
653}
654
655DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
656 switch (type) {
657 case cricket::DMT_TEXT:
658 return DataMessageType::kText;
659 case cricket::DMT_BINARY:
660 return DataMessageType::kBinary;
661 case cricket::DMT_CONTROL:
662 return DataMessageType::kControl;
663 case cricket::DMT_NONE:
664 default:
665 RTC_NOTREACHED();
666 }
667 return DataMessageType::kControl;
668}
669
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800670void ReportSimulcastApiVersion(const char* name,
671 const SessionDescription& session) {
672 bool has_legacy = false;
673 bool has_spec_compliant = false;
674 for (const ContentInfo& content : session.contents()) {
675 if (!content.description) {
676 continue;
677 }
678 has_spec_compliant |= content.description->HasSimulcast();
679 for (const StreamParams& sp : content.description->streams()) {
680 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
681 }
682 }
683
684 if (has_legacy) {
685 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
686 kSimulcastApiVersionMax);
687 }
688 if (has_spec_compliant) {
689 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
690 kSimulcastApiVersionMax);
691 }
692 if (!has_legacy && !has_spec_compliant) {
693 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
694 kSimulcastApiVersionMax);
695 }
696}
697
Steve Anton75737c02017-11-06 10:37:17 -0800698} // namespace
699
Henrik Boström31638672017-11-23 17:48:32 +0100700// Upon completion, posts a task to execute the callback of the
701// SetSessionDescriptionObserver asynchronously on the same thread. At this
702// point, the state of the peer connection might no longer reflect the effects
703// of the SetRemoteDescription operation, as the peer connection could have been
704// modified during the post.
705// TODO(hbos): Remove this class once we remove the version of
706// PeerConnectionInterface::SetRemoteDescription() that takes a
707// SetSessionDescriptionObserver as an argument.
708class PeerConnection::SetRemoteDescriptionObserverAdapter
709 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
710 public:
711 SetRemoteDescriptionObserverAdapter(
712 rtc::scoped_refptr<PeerConnection> pc,
713 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
714 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
715
716 // SetRemoteDescriptionObserverInterface implementation.
717 void OnSetRemoteDescriptionComplete(RTCError error) override {
718 if (error.ok())
719 pc_->PostSetSessionDescriptionSuccess(wrapper_);
720 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100721 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100722 }
723
724 private:
725 rtc::scoped_refptr<PeerConnection> pc_;
726 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
727};
728
deadbeef293e9262017-01-11 12:28:30 -0800729bool PeerConnectionInterface::RTCConfiguration::operator==(
730 const PeerConnectionInterface::RTCConfiguration& o) const {
731 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700732 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800733 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000734 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700735 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800736 BundlePolicy bundle_policy;
737 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700738 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
739 int ice_candidate_pool_size;
740 bool disable_ipv6;
741 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700742 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100743 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700744 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200745 absl::optional<int> screencast_min_bitrate;
746 absl::optional<bool> combined_audio_video_bwe;
747 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800748 TcpCandidatePolicy tcp_candidate_policy;
749 CandidateNetworkPolicy candidate_network_policy;
750 int audio_jitter_buffer_max_packets;
751 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100752 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100753 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800754 int ice_connection_receiving_timeout;
755 int ice_backup_candidate_pair_ping_interval;
756 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800757 bool prioritize_most_likely_ice_candidate_pairs;
758 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800759 bool prune_turn_ports;
760 bool presume_writable_when_fully_relayed;
761 bool enable_ice_renomination;
762 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<int> ice_check_interval_strong_connectivity;
764 absl::optional<int> ice_check_interval_weak_connectivity;
765 absl::optional<int> ice_check_min_interval;
766 absl::optional<int> ice_unwritable_timeout;
767 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800768 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200769 absl::optional<int> stun_candidate_keepalive_interval;
770 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200771 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800772 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200773 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700774 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700775 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700776 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700777 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100778 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800779 };
780 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
781 "Did you add something to RTCConfiguration and forget to "
782 "update operator==?");
783 return type == o.type && servers == o.servers &&
784 bundle_policy == o.bundle_policy &&
785 rtcp_mux_policy == o.rtcp_mux_policy &&
786 tcp_candidate_policy == o.tcp_candidate_policy &&
787 candidate_network_policy == o.candidate_network_policy &&
788 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
789 audio_jitter_buffer_fast_accelerate ==
790 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100791 audio_jitter_buffer_min_delay_ms ==
792 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100793 audio_jitter_buffer_enable_rtx_handling ==
794 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800795 ice_connection_receiving_timeout ==
796 o.ice_connection_receiving_timeout &&
797 ice_backup_candidate_pair_ping_interval ==
798 o.ice_backup_candidate_pair_ping_interval &&
799 continual_gathering_policy == o.continual_gathering_policy &&
800 certificates == o.certificates &&
801 prioritize_most_likely_ice_candidate_pairs ==
802 o.prioritize_most_likely_ice_candidate_pairs &&
803 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800804 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700805 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100806 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800807 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800808 screencast_min_bitrate == o.screencast_min_bitrate &&
809 combined_audio_video_bwe == o.combined_audio_video_bwe &&
810 enable_dtls_srtp == o.enable_dtls_srtp &&
811 ice_candidate_pool_size == o.ice_candidate_pool_size &&
812 prune_turn_ports == o.prune_turn_ports &&
813 presume_writable_when_fully_relayed ==
814 o.presume_writable_when_fully_relayed &&
815 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800816 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800817 ice_check_interval_strong_connectivity ==
818 o.ice_check_interval_strong_connectivity &&
819 ice_check_interval_weak_connectivity ==
820 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700821 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700822 ice_unwritable_timeout == o.ice_unwritable_timeout &&
823 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800824 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800825 stun_candidate_keepalive_interval ==
826 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200827 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800828 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800829 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700830 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700831 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700832 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700833 use_media_transport_for_data_channels ==
834 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100835 crypto_options == o.crypto_options &&
836 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800837}
838
839bool PeerConnectionInterface::RTCConfiguration::operator!=(
840 const PeerConnectionInterface::RTCConfiguration& o) const {
841 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800842}
843
zhihuang8f65cdf2016-05-06 18:40:30 -0700844// Generate a RTCP CNAME when a PeerConnection is created.
845std::string GenerateRtcpCname() {
846 std::string cname;
847 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100848 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800849 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700850 }
851 return cname;
852}
853
zhihuang1c378ed2017-08-17 14:10:50 -0700854bool ValidateOfferAnswerOptions(
855 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
856 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
857 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700858}
859
zhihuang1c378ed2017-08-17 14:10:50 -0700860// From |rtc_options|, fill parts of |session_options| shared by all generated
861// m= sections (in other words, nothing that involves a map/array).
862void ExtractSharedMediaSessionOptions(
863 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
864 cricket::MediaSessionOptions* session_options) {
865 session_options->vad_enabled = rtc_options.voice_activity_detection;
866 session_options->bundle_enabled = rtc_options.use_rtp_mux;
867}
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()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700875 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700876 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700877 remote_streams_(StreamCollection::Create()),
878 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879
880PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100881 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800882 RTC_DCHECK_RUN_ON(signaling_thread());
883
Steve Anton8af21862017-12-15 11:20:13 -0800884 // Need to stop transceivers before destroying the stats collector because
885 // AudioRtpSender has a reference to the StatsCollector it will update when
886 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100887 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800888 transceiver->Stop();
889 }
Steve Anton4171afb2017-11-20 10:20:22 -0800890
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700891 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800892 if (stats_collector_) {
893 stats_collector_->WaitForPendingRequest();
894 stats_collector_ = nullptr;
895 }
Steve Anton75737c02017-11-06 10:37:17 -0800896
Steve Anton8af21862017-12-15 11:20:13 -0800897 // Don't destroy BaseChannels until after stats has been cleaned up so that
898 // the last stats request can still read from the channels.
899 DestroyAllChannels();
900
Mirko Bonadei675513b2017-11-09 11:09:25 +0100901 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800902
903 webrtc_session_desc_factory_.reset();
904 sctp_invoker_.reset();
905 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800906 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800907 transport_controller_.reset();
908
deadbeef91dd5672016-05-18 16:55:30 -0700909 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700910 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700911 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700912 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700913 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100914 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700915 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800916 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700917 event_log_.reset();
918 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919}
920
Steve Anton8af21862017-12-15 11:20:13 -0800921void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800922 // Destroy video channels first since they may have a pointer to a voice
923 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100924 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800925 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800926 DestroyTransceiverChannel(transceiver);
927 }
928 }
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_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800931 DestroyTransceiverChannel(transceiver);
932 }
933 }
934 DestroyDataChannel();
935}
936
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000938 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700939 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100940 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100941 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100942 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700943
944 RTCError config_error = ValidateConfiguration(configuration);
945 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100946 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700947 return false;
948 }
949
Benjamin Wrightcab58882018-05-02 15:12:47 -0700950 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100951 RTC_LOG(LS_ERROR)
952 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100953 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800954 return false;
955 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200956
Benjamin Wrightcab58882018-05-02 15:12:47 -0700957 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800958 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100959 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100960 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800961 return false;
962 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700963
Benjamin Wrightcab58882018-05-02 15:12:47 -0700964 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700965 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700966 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700967 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800968
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200969 cricket::ServerAddresses stun_servers;
970 std::vector<cricket::RelayServerConfig> turn_servers;
971
972 RTCErrorType parse_error =
973 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
974 if (parse_error != RTCErrorType::NONE) {
975 return false;
976 }
977
deadbeef91dd5672016-05-18 16:55:30 -0700978 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700979 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700980 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200981 RTC_FROM_HERE,
982 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
983 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 return false;
985 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200986 // If initialization was successful, note if STUN or TURN servers
987 // were supplied.
988 if (!stun_servers.empty()) {
989 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
990 }
991 if (!turn_servers.empty()) {
992 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
993 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700995 // Send information about IPv4/IPv6 status.
996 PeerConnectionAddressFamilyCounter address_family;
997 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
998 address_family = kPeerConnection_IPv6;
999 } else {
1000 address_family = kPeerConnection_IPv4;
1001 }
1002 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1003 kPeerConnectionAddressFamilyCounter_Max);
1004
Zhi Huange830e682018-03-30 10:48:35 -07001005 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1006
Steve Anton75737c02017-11-06 10:37:17 -08001007 // RFC 3264: The numeric value of the session id and version in the
1008 // o line MUST be representable with a "64 bit signed integer".
1009 // Due to this constraint session id |session_id_| is max limited to
1010 // LLONG_MAX.
1011 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001012 JsepTransportController::Config config;
1013 config.redetermine_role_on_ice_restart =
1014 configuration.redetermine_role_on_ice_restart;
1015 config.ssl_max_version = factory_->options().ssl_max_version;
1016 config.disable_encryption = options.disable_encryption;
1017 config.bundle_policy = configuration.bundle_policy;
1018 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001019 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1020 // stub.
1021 config.crypto_options = configuration.crypto_options.has_value()
1022 ? *configuration.crypto_options
1023 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001024 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001025 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001026#if defined(ENABLE_EXTERNAL_AUTH)
1027 config.enable_external_auth = true;
1028#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001029 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001030
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001031 if (configuration.use_media_transport ||
1032 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001033 if (!factory_->media_transport_factory()) {
1034 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001035 << "PeerConnecton is initialized with use_media_transport = true or "
1036 << "use_media_transport_for_data_channels = true "
1037 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001038 return false;
1039 }
1040
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001041 if (configuration.use_media_transport ||
1042 configuration.use_media_transport_for_data_channels) {
1043 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1044 // RTP media transport is introduced. But until then, we require SDES to
1045 // be enabled.
1046 if (configuration.enable_dtls_srtp.has_value() &&
1047 configuration.enable_dtls_srtp.value()) {
1048 RTC_LOG(LS_WARNING)
1049 << "When media transport is used, SDES must be enabled. Set "
1050 "configuration.enable_dtls_srtp to false. use_media_transport="
1051 << configuration.use_media_transport
1052 << ", use_media_transport_for_data_channels="
1053 << configuration.use_media_transport_for_data_channels;
1054 return false;
1055 }
1056 }
1057
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001058 config.use_media_transport_for_media = configuration.use_media_transport;
1059 config.use_media_transport_for_data_channels =
1060 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001061 config.media_transport_factory = factory_->media_transport_factory();
1062 }
1063
Zhi Huange830e682018-03-30 10:48:35 -07001064 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001065 signaling_thread(), network_thread(), port_allocator_.get(),
1066 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001067 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001068 this, &PeerConnection::OnTransportControllerConnectionState);
1069 transport_controller_->SignalStandardizedIceConnectionState.connect(
1070 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001071 transport_controller_->SignalConnectionState.connect(
1072 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001073 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001074 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001075 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001076 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001077 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001078 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1079 transport_controller_->SignalDtlsHandshakeError.connect(
1080 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1081
1082 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001083
deadbeefab9b2d12015-10-14 11:33:11 -07001084 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001085 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086
Steve Antonba818672017-11-06 10:21:57 -08001087 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001088 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001089
Steve Anton75737c02017-11-06 10:37:17 -08001090 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1091 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1092 if (!configuration.certificates.empty()) {
1093 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1094 // just picking the first one. The decision should be made based on the DTLS
1095 // handshake. The DTLS negotiations need to know about all certificates.
1096 certificate = configuration.certificates[0];
1097 }
1098
Steve Antond25da372017-11-06 14:50:29 -08001099 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001100
1101 if (options.disable_encryption) {
1102 dtls_enabled_ = false;
1103 } else {
1104 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001105 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001106 // |configuration| can override the default |dtls_enabled_| value.
1107 if (configuration.enable_dtls_srtp) {
1108 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1109 }
1110 }
1111
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001112 if (configuration.use_media_transport_for_data_channels) {
1113 if (configuration.enable_rtp_data_channel) {
1114 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1115 "use_media_transport_for_data_channels are "
1116 "incompatible and cannot both be set to true";
1117 return false;
1118 }
1119 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1120 } else if (configuration.enable_rtp_data_channel) {
1121 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1122 // set. It takes precendence over the disable_sctp_data_channels
1123 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001124 data_channel_type_ = cricket::DCT_RTP;
1125 } else {
1126 // DTLS has to be enabled to use SCTP.
1127 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1128 data_channel_type_ = cricket::DCT_SCTP;
1129 }
1130 }
1131
1132 video_options_.screencast_min_bitrate_kbps =
1133 configuration.screencast_min_bitrate;
1134 audio_options_.combined_audio_video_bwe =
1135 configuration.combined_audio_video_bwe;
1136
1137 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001138 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001139
1140 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001141 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001142
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001143 audio_options_.audio_jitter_buffer_min_delay_ms =
1144 configuration.audio_jitter_buffer_min_delay_ms;
1145
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001146 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1147 configuration.audio_jitter_buffer_enable_rtx_handling;
1148
Steve Anton75737c02017-11-06 10:37:17 -08001149 // Whether the certificate generator/certificate is null or not determines
1150 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1151 // the right instructions by clearing the variables if needed.
1152 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001153 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001154 certificate = nullptr;
1155 } else if (certificate) {
1156 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001157 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001158 }
1159
1160 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1161 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001162 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001163 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1164 this, &PeerConnection::OnCertificateReady);
1165
1166 if (options.disable_encryption) {
1167 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1168 }
1169
1170 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001171 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001172 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173
Steve Anton4171afb2017-11-20 10:20:22 -08001174 // Add default audio/video transceivers for Plan B SDP.
1175 if (!IsUnifiedPlan()) {
1176 transceivers_.push_back(
1177 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1178 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1179 transceivers_.push_back(
1180 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1181 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1182 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001183 int delay_ms =
1184 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001185 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1186 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 return true;
1188}
1189
Steve Anton038834f2017-07-14 15:59:59 -07001190RTCError PeerConnection::ValidateConfiguration(
1191 const RTCConfiguration& config) const {
1192 if (config.ice_regather_interval_range &&
1193 config.continual_gathering_policy == GATHER_ONCE) {
1194 return RTCError(RTCErrorType::INVALID_PARAMETER,
1195 "ice_regather_interval_range specified but continual "
1196 "gathering policy is GATHER_ONCE");
1197 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001198 auto result =
1199 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1200 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001201}
1202
Yves Gerey665174f2018-06-19 15:03:05 +02001203rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001204 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001205 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1206 "Plan SdpSemantics. Please use GetSenders "
1207 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001208 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209}
1210
Yves Gerey665174f2018-06-19 15:03:05 +02001211rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001212 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001213 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1214 "Plan SdpSemantics. Please use GetReceivers "
1215 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001216 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217}
1218
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001219bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001220 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001221 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1222 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001223 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001224 if (IsClosed()) {
1225 return false;
1226 }
deadbeefab9b2d12015-10-14 11:33:11 -07001227 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 return false;
1229 }
deadbeefab9b2d12015-10-14 11:33:11 -07001230
1231 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001232 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1233 observer->SignalAudioTrackAdded.connect(this,
1234 &PeerConnection::OnAudioTrackAdded);
1235 observer->SignalAudioTrackRemoved.connect(
1236 this, &PeerConnection::OnAudioTrackRemoved);
1237 observer->SignalVideoTrackAdded.connect(this,
1238 &PeerConnection::OnVideoTrackAdded);
1239 observer->SignalVideoTrackRemoved.connect(
1240 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001241 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001242
deadbeefab9b2d12015-10-14 11:33:11 -07001243 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001244 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001245 }
1246 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001247 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001248 }
1249
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001250 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001251 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001252 return true;
1253}
1254
1255void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001256 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001257 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1258 "Plan SdpSemantics. Please use RemoveTrack "
1259 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001260 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001261 if (!IsClosed()) {
1262 for (const auto& track : local_stream->GetAudioTracks()) {
1263 RemoveAudioTrack(track.get(), local_stream);
1264 }
1265 for (const auto& track : local_stream->GetVideoTracks()) {
1266 RemoveVideoTrack(track.get(), local_stream);
1267 }
deadbeefab9b2d12015-10-14 11:33:11 -07001268 }
deadbeefab9b2d12015-10-14 11:33:11 -07001269 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001270 stream_observers_.erase(
1271 std::remove_if(
1272 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001273 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001274 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001275 }),
1276 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001277
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 if (IsClosed()) {
1279 return;
1280 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001281 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282}
1283
Steve Anton2d6c76a2018-01-05 17:10:52 -08001284RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001285 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001286 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001287 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001288 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001289 if (!track) {
1290 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1291 }
1292 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1293 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1294 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1295 "Track has invalid kind: " + track->kind());
1296 }
Steve Antonf9381f02017-12-14 10:23:57 -08001297 if (IsClosed()) {
1298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1299 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001300 }
Steve Anton4171afb2017-11-20 10:20:22 -08001301 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001302 LOG_AND_RETURN_ERROR(
1303 RTCErrorType::INVALID_PARAMETER,
1304 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001305 }
Steve Antonf9381f02017-12-14 10:23:57 -08001306 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001307 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1308 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001309 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001310 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001311 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001312 }
1313 return sender_or_error;
1314}
deadbeefe1f9d832016-01-14 15:35:42 -08001315
Steve Antonf9381f02017-12-14 10:23:57 -08001316RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1317PeerConnection::AddTrackPlanB(
1318 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001319 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001320 if (stream_ids.size() > 1u) {
1321 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1322 "AddTrack with more than one stream is not "
1323 "supported with Plan B semantics.");
1324 }
1325 std::vector<std::string> adjusted_stream_ids = stream_ids;
1326 if (adjusted_stream_ids.empty()) {
1327 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1328 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001329 cricket::MediaType media_type =
1330 (track->kind() == MediaStreamTrackInterface::kAudioKind
1331 ? cricket::MEDIA_TYPE_AUDIO
1332 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001333 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001334 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001335 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001336 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001337 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001338 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001339 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001340 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001341 if (sender_info) {
1342 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001343 }
Steve Antonf9381f02017-12-14 10:23:57 -08001344 } else {
1345 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001346 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001347 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001348 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001349 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001350 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001351 if (sender_info) {
1352 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001353 }
deadbeefe1f9d832016-01-14 15:35:42 -08001354 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001355 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001356}
deadbeefe1f9d832016-01-14 15:35:42 -08001357
Steve Antonf9381f02017-12-14 10:23:57 -08001358RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1359PeerConnection::AddTrackUnifiedPlan(
1360 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001361 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001362 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1363 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001364 RTC_LOG(LS_INFO) << "Reusing an existing "
1365 << cricket::MediaTypeToString(transceiver->media_type())
1366 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001367 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001368 transceiver->internal()->set_direction(
1369 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001370 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001371 transceiver->internal()->set_direction(
1372 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001373 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001374 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001375 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001376 } else {
1377 cricket::MediaType media_type =
1378 (track->kind() == MediaStreamTrackInterface::kAudioKind
1379 ? cricket::MEDIA_TYPE_AUDIO
1380 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001381 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1382 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001383 std::string sender_id = track->id();
1384 // Avoid creating a sender with an existing ID by generating a random ID.
1385 // This can happen if this is the second time AddTrack has created a sender
1386 // for this track.
1387 if (FindSenderById(sender_id)) {
1388 sender_id = rtc::CreateRandomUuid();
1389 }
Florent Castelli892acf02018-10-01 22:47:20 +02001390 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001391 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1392 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001393 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001394 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001395 }
Steve Antonf9381f02017-12-14 10:23:57 -08001396 return transceiver->sender();
1397}
1398
1399rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1400PeerConnection::FindFirstTransceiverForAddedTrack(
1401 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1402 RTC_DCHECK(track);
1403 for (auto transceiver : transceivers_) {
1404 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001405 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001406 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001407 !transceiver->internal()->has_ever_been_used_to_send() &&
1408 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001409 return transceiver;
1410 }
1411 }
1412 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001413}
1414
1415bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1416 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001417 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001418}
1419
Steve Anton24db5732018-07-23 10:27:33 -07001420RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001421 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001422 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001423 if (!sender) {
1424 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1425 }
deadbeefe1f9d832016-01-14 15:35:42 -08001426 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1428 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001429 }
Steve Antonf9381f02017-12-14 10:23:57 -08001430 if (IsUnifiedPlan()) {
1431 auto transceiver = FindTransceiverBySender(sender);
1432 if (!transceiver || !sender->track()) {
1433 return RTCError::OK();
1434 }
1435 sender->SetTrack(nullptr);
1436 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001437 transceiver->internal()->set_direction(
1438 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001439 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001440 transceiver->internal()->set_direction(
1441 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001442 }
Steve Anton4171afb2017-11-20 10:20:22 -08001443 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001444 bool removed;
1445 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1446 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1447 } else {
1448 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1449 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1450 }
1451 if (!removed) {
1452 LOG_AND_RETURN_ERROR(
1453 RTCErrorType::INVALID_PARAMETER,
1454 "Couldn't find sender " + sender->id() + " to remove.");
1455 }
Steve Anton4171afb2017-11-20 10:20:22 -08001456 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001457 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001458 return RTCError::OK();
1459}
1460
1461rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1462PeerConnection::FindTransceiverBySender(
1463 rtc::scoped_refptr<RtpSenderInterface> sender) {
1464 for (auto transceiver : transceivers_) {
1465 if (transceiver->sender() == sender) {
1466 return transceiver;
1467 }
1468 }
1469 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001470}
1471
Steve Anton9158ef62017-11-27 13:01:52 -08001472RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1473PeerConnection::AddTransceiver(
1474 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1475 return AddTransceiver(track, RtpTransceiverInit());
1476}
1477
1478RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1479PeerConnection::AddTransceiver(
1480 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1481 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001482 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001483 RTC_CHECK(IsUnifiedPlan())
1484 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001485 if (!track) {
1486 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1487 }
1488 cricket::MediaType media_type;
1489 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1490 media_type = cricket::MEDIA_TYPE_AUDIO;
1491 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1492 media_type = cricket::MEDIA_TYPE_VIDEO;
1493 } else {
1494 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1495 "Track kind is not audio or video");
1496 }
1497 return AddTransceiver(media_type, track, init);
1498}
1499
1500RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1501PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1502 return AddTransceiver(media_type, RtpTransceiverInit());
1503}
1504
1505RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1506PeerConnection::AddTransceiver(cricket::MediaType media_type,
1507 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001508 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001509 RTC_CHECK(IsUnifiedPlan())
1510 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001511 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1512 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1514 "media type is not audio or video");
1515 }
1516 return AddTransceiver(media_type, nullptr, init);
1517}
1518
1519RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1520PeerConnection::AddTransceiver(
1521 cricket::MediaType media_type,
1522 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001523 const RtpTransceiverInit& init,
1524 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001525 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1526 media_type == cricket::MEDIA_TYPE_VIDEO));
1527 if (track) {
1528 RTC_DCHECK_EQ(media_type,
1529 (track->kind() == MediaStreamTrackInterface::kAudioKind
1530 ? cricket::MEDIA_TYPE_AUDIO
1531 : cricket::MEDIA_TYPE_VIDEO));
1532 }
1533
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001534 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1535 init.send_encodings.size(), 0, 7, 8);
1536
Amit Hilbuchaa584152019-02-06 17:09:52 -08001537 size_t num_rids = absl::c_count_if(init.send_encodings,
1538 [](const RtpEncodingParameters& encoding) {
1539 return !encoding.rid.empty();
1540 });
1541 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001542 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001543 RTCErrorType::INVALID_PARAMETER,
1544 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001545 }
1546
Amit Hilbuchaa584152019-02-06 17:09:52 -08001547 if (absl::c_any_of(init.send_encodings,
1548 [](const RtpEncodingParameters& encoding) {
1549 return encoding.ssrc.has_value();
1550 })) {
1551 LOG_AND_RETURN_ERROR(
1552 RTCErrorType::UNSUPPORTED_PARAMETER,
1553 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001554 }
1555
1556 RtpParameters parameters;
1557 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001558
1559 // Encodings are dropped from the tail if too many are provided.
1560 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1561 parameters.encodings.erase(
1562 parameters.encodings.begin() + kMaxSimulcastStreams,
1563 parameters.encodings.end());
1564 }
1565
1566 // Single RID should be removed.
1567 if (parameters.encodings.size() == 1 &&
1568 !parameters.encodings[0].rid.empty()) {
1569 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1570 parameters.encodings[0].rid.clear();
1571 }
1572
1573 // If RIDs were not provided, they are generated for simulcast scenario.
1574 if (parameters.encodings.size() > 1 && num_rids == 0) {
1575 rtc::UniqueStringGenerator rid_generator;
1576 for (RtpEncodingParameters& encoding : parameters.encodings) {
1577 encoding.rid = rid_generator();
1578 }
1579 }
1580
Florent Castelli892acf02018-10-01 22:47:20 +02001581 if (UnimplementedRtpParameterHasValue(parameters)) {
1582 LOG_AND_RETURN_ERROR(
1583 RTCErrorType::UNSUPPORTED_PARAMETER,
1584 "Attempted to set an unimplemented parameter of RtpParameters.");
1585 }
Steve Anton9158ef62017-11-27 13:01:52 -08001586
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001587 auto result = cricket::CheckRtpParametersValues(parameters);
1588 if (!result.ok()) {
1589 LOG_AND_RETURN_ERROR(result.type(), result.message());
1590 }
1591
Steve Anton3d954a62018-04-02 11:27:23 -07001592 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1593 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001594 // Set the sender ID equal to the track ID if the track is specified unless
1595 // that sender ID is already in use.
1596 std::string sender_id =
1597 (track && !FindSenderById(track->id()) ? track->id()
1598 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001599 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001600 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001601 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1602 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1603 transceiver->internal()->set_direction(init.direction);
1604
Steve Anton22da89f2018-01-25 13:58:07 -08001605 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001606 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001607 }
Steve Antonf9381f02017-12-14 10:23:57 -08001608
1609 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1610}
1611
Steve Anton02ee47c2018-01-10 16:26:06 -08001612rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1613PeerConnection::CreateSender(
1614 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001615 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001616 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001617 const std::vector<std::string>& stream_ids,
1618 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001619 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001620 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1621 RTC_DCHECK(!track ||
1622 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1623 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1624 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001625 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001626 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001627 } else {
1628 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1629 RTC_DCHECK(!track ||
1630 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1631 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001632 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001633 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001634 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001635 bool set_track_succeeded = sender->SetTrack(track);
1636 RTC_DCHECK(set_track_succeeded);
1637 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001638 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001639 return sender;
1640}
1641
1642rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1643PeerConnection::CreateReceiver(cricket::MediaType media_type,
1644 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001645 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1646 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001647 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001648 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001649 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1650 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001651 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001652 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001653 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001654 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001655 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1656 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001657 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001658 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001659 return receiver;
1660}
1661
1662rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1663PeerConnection::CreateAndAddTransceiver(
1664 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1665 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1666 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001667 // Ensure that the new sender does not have an ID that is already in use by
1668 // another sender.
1669 // Allow receiver IDs to conflict since those come from remote SDP (which
1670 // could be invalid, but should not cause a crash).
1671 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001672 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1673 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001674 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001675 transceiver->internal()->SignalNegotiationNeeded.connect(
1676 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001677 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001678}
1679
Steve Anton52d86772018-02-20 15:48:12 -08001680void PeerConnection::OnNegotiationNeeded() {
1681 RTC_DCHECK_RUN_ON(signaling_thread());
1682 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001683 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001684}
1685
deadbeeffac06552015-11-25 11:26:01 -08001686rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001687 const std::string& kind,
1688 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001689 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001690 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1691 "Plan SdpSemantics. Please use AddTransceiver "
1692 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001693 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001694 if (IsClosed()) {
1695 return nullptr;
1696 }
Steve Anton4171afb2017-11-20 10:20:22 -08001697
Seth Hampson5b4f0752018-04-02 16:31:36 -07001698 // Internally we need to have one stream with Plan B semantics, so we
1699 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001700 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001701 if (stream_id.empty()) {
1702 stream_ids.push_back(rtc::CreateRandomUuid());
1703 RTC_LOG(LS_INFO)
1704 << "No stream_id specified for sender. Generated stream ID: "
1705 << stream_ids[0];
1706 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001707 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001708 }
1709
Steve Anton4171afb2017-11-20 10:20:22 -08001710 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001711 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001712 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001713 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001714 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001715 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001716 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001717 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001718 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001719 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001720 auto video_sender =
1721 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001722 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001723 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001724 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001725 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001726 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001727 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001728 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001729 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001730 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001731
deadbeefe1f9d832016-01-14 15:35:42 -08001732 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001733}
1734
deadbeef70ab1a12015-09-28 16:53:55 -07001735std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1736 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001737 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001738 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001739 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001740 }
1741 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001742}
1743
Steve Anton4171afb2017-11-20 10:20:22 -08001744std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1745PeerConnection::GetSendersInternal() const {
1746 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1747 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001748 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001749 auto senders = transceiver->internal()->senders();
1750 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1751 }
1752 return all_senders;
1753}
1754
deadbeef70ab1a12015-09-28 16:53:55 -07001755std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1756PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001757 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001758 for (const auto& receiver : GetReceiversInternal()) {
1759 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001760 }
1761 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001762}
1763
Steve Anton4171afb2017-11-20 10:20:22 -08001764std::vector<
1765 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1766PeerConnection::GetReceiversInternal() const {
1767 std::vector<
1768 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1769 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001770 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001771 auto receivers = transceiver->internal()->receivers();
1772 all_receivers.insert(all_receivers.end(), receivers.begin(),
1773 receivers.end());
1774 }
1775 return all_receivers;
1776}
1777
Steve Anton9158ef62017-11-27 13:01:52 -08001778std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1779PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001780 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001781 RTC_CHECK(IsUnifiedPlan())
1782 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001783 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001784 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001785 all_transceivers.push_back(transceiver);
1786 }
1787 return all_transceivers;
1788}
1789
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001790bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001791 MediaStreamTrackInterface* track,
1792 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001793 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001794 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001795 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001796 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001797 return false;
1798 }
1799
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001800 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001801 // The StatsCollector is used to tell if a track is valid because it may
1802 // remember tracks that the PeerConnection previously removed.
1803 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001804 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1805 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001806 return false;
1807 }
Steve Antonad182762018-09-05 20:22:40 +00001808 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1809 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810 return true;
1811}
1812
hbos74e1a4f2016-09-15 23:33:01 -07001813void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001814 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001815 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001816 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001817 stats_collector_->GetStatsReport(callback);
1818}
1819
Henrik Boström1df1bf82018-03-20 13:24:20 +01001820void PeerConnection::GetStats(
1821 rtc::scoped_refptr<RtpSenderInterface> selector,
1822 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1823 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1824 RTC_DCHECK(callback);
1825 RTC_DCHECK(stats_collector_);
1826 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1827 if (selector) {
1828 for (const auto& proxy_transceiver : transceivers_) {
1829 for (const auto& proxy_sender :
1830 proxy_transceiver->internal()->senders()) {
1831 if (proxy_sender == selector) {
1832 internal_sender = proxy_sender->internal();
1833 break;
1834 }
1835 }
1836 if (internal_sender)
1837 break;
1838 }
1839 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001840 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001841 // belong to the PeerConnection (in Plan B, senders can be removed from the
1842 // PeerConnection). This means that "all the stats objects representing the
1843 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1844 // produces an empty stats report.
1845 stats_collector_->GetStatsReport(internal_sender, callback);
1846}
1847
1848void PeerConnection::GetStats(
1849 rtc::scoped_refptr<RtpReceiverInterface> selector,
1850 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1851 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1852 RTC_DCHECK(callback);
1853 RTC_DCHECK(stats_collector_);
1854 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1855 if (selector) {
1856 for (const auto& proxy_transceiver : transceivers_) {
1857 for (const auto& proxy_receiver :
1858 proxy_transceiver->internal()->receivers()) {
1859 if (proxy_receiver == selector) {
1860 internal_receiver = proxy_receiver->internal();
1861 break;
1862 }
1863 }
1864 if (internal_receiver)
1865 break;
1866 }
1867 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001868 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001869 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1870 // the PeerConnection). This means that "all the stats objects representing
1871 // the selector" is an empty set. Invoking GetStatsReport() with a null
1872 // selector produces an empty stats report.
1873 stats_collector_->GetStatsReport(internal_receiver, callback);
1874}
1875
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001876PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001877 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 return signaling_state_;
1879}
1880
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881PeerConnectionInterface::IceConnectionState
1882PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001883 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001884 return ice_connection_state_;
1885}
1886
Alex Loiko9289eda2018-11-23 16:18:59 +00001887PeerConnectionInterface::IceConnectionState
1888PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001889 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001890 return standardized_ice_connection_state_;
1891}
1892
Jonas Olsson635474e2018-10-18 15:58:17 +02001893PeerConnectionInterface::PeerConnectionState
1894PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001895 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001896 return connection_state_;
1897}
1898
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001899PeerConnectionInterface::IceGatheringState
1900PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001901 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902 return ice_gathering_state_;
1903}
1904
Yves Gerey665174f2018-06-19 15:03:05 +02001905rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001906 const std::string& label,
1907 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001908 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001909 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001910
deadbeefab9b2d12015-10-14 11:33:11 -07001911 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001912
kwibergd1fe2812016-04-27 06:47:29 -07001913 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001914 if (config) {
1915 internal_config.reset(new InternalDataChannelInit(*config));
1916 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001917 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001918 InternalCreateDataChannel(label, internal_config.get()));
1919 if (!channel.get()) {
1920 return nullptr;
1921 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001923 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1924 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001925 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001926 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001927 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001928 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001929 return DataChannelProxy::Create(signaling_thread(), channel.get());
1930}
1931
1932void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001933 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001934 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001935 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001936
nisse7ce109a2017-01-31 00:57:56 -08001937 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001938 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001939 return;
1940 }
deadbeefab9b2d12015-10-14 11:33:11 -07001941
Steve Anton8d3444d2017-10-20 15:30:51 -07001942 if (IsClosed()) {
1943 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001944 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001945 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001946 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001947 return;
1948 }
1949
zhihuang1c378ed2017-08-17 14:10:50 -07001950 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001951 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001952 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001953 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001954 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001955 return;
1956 }
1957
Steve Anton22da89f2018-01-25 13:58:07 -08001958 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1959 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1960 if (IsUnifiedPlan()) {
1961 RTCError error = HandleLegacyOfferOptions(options);
1962 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001963 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001964 return;
1965 }
1966 }
1967
zhihuang1c378ed2017-08-17 14:10:50 -07001968 cricket::MediaSessionOptions session_options;
1969 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001970 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001971}
1972
Steve Anton22da89f2018-01-25 13:58:07 -08001973RTCError PeerConnection::HandleLegacyOfferOptions(
1974 const RTCOfferAnswerOptions& options) {
1975 RTC_DCHECK(IsUnifiedPlan());
1976
1977 if (options.offer_to_receive_audio == 0) {
1978 RemoveRecvDirectionFromReceivingTransceiversOfType(
1979 cricket::MEDIA_TYPE_AUDIO);
1980 } else if (options.offer_to_receive_audio == 1) {
1981 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1982 } else if (options.offer_to_receive_audio > 1) {
1983 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1984 "offer_to_receive_audio > 1 is not supported.");
1985 }
1986
1987 if (options.offer_to_receive_video == 0) {
1988 RemoveRecvDirectionFromReceivingTransceiversOfType(
1989 cricket::MEDIA_TYPE_VIDEO);
1990 } else if (options.offer_to_receive_video == 1) {
1991 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1992 } else if (options.offer_to_receive_video > 1) {
1993 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1994 "offer_to_receive_video > 1 is not supported.");
1995 }
1996
1997 return RTCError::OK();
1998}
1999
2000void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2001 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002002 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002003 RtpTransceiverDirection new_direction =
2004 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2005 if (new_direction != transceiver->direction()) {
2006 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2007 << " transceiver (MID="
2008 << transceiver->mid().value_or("<not set>") << ") from "
2009 << RtpTransceiverDirectionToString(
2010 transceiver->direction())
2011 << " to "
2012 << RtpTransceiverDirectionToString(new_direction)
2013 << " since CreateOffer specified offer_to_receive=0";
2014 transceiver->internal()->set_direction(new_direction);
2015 }
Steve Anton22da89f2018-01-25 13:58:07 -08002016 }
2017}
2018
2019void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2020 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002021 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002022 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002023 RTC_LOG(LS_INFO)
2024 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2025 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002026 RtpTransceiverInit init;
2027 init.direction = RtpTransceiverDirection::kRecvOnly;
2028 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
2029 }
2030}
2031
2032std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2033PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2034 std::vector<
2035 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2036 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002037 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002038 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002039 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2040 receiving_transceivers.push_back(transceiver);
2041 }
2042 }
2043 return receiving_transceivers;
2044}
2045
htaa2a49d92016-03-04 02:51:39 -08002046void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2047 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002048 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002049 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002050 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002051 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002052 return;
2053 }
2054
Steve Antondffead82018-02-06 10:31:29 -08002055 if (!(signaling_state_ == kHaveRemoteOffer ||
2056 signaling_state_ == kHaveLocalPrAnswer)) {
2057 std::string error =
2058 "PeerConnection cannot create an answer in a state other than "
2059 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002060 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002061 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002062 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002063 return;
2064 }
2065
Steve Antondffead82018-02-06 10:31:29 -08002066 // The remote description should be set if we're in the right state.
2067 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002068
Steve Anton22da89f2018-01-25 13:58:07 -08002069 if (IsUnifiedPlan()) {
2070 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2071 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2072 "supported with Unified Plan semantics. Use the "
2073 "RtpTransceiver API instead.";
2074 }
2075 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2076 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2077 "supported with Unified Plan semantics. Use the "
2078 "RtpTransceiver API instead.";
2079 }
2080 }
2081
htaa2a49d92016-03-04 02:51:39 -08002082 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002083 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002084
Steve Antond25da372017-11-06 14:50:29 -08002085 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002086}
2087
2088void PeerConnection::SetLocalDescription(
2089 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002090 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002091 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002092 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002093
Steve Anton80dd7b52018-02-16 17:08:42 -08002094 // The SetLocalDescription contract is that we take ownership of the session
2095 // description regardless of the outcome, so wrap it in a unique_ptr right
2096 // away. Ideally, SetLocalDescription's signature will be changed to take the
2097 // description as a unique_ptr argument to formalize this agreement.
2098 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2099
nisse7ce109a2017-01-31 00:57:56 -08002100 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002101 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002102 return;
2103 }
Steve Anton8a006912017-12-04 15:25:56 -08002104
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002105 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002106 PostSetSessionDescriptionFailure(
2107 observer,
2108 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002109 return;
2110 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002111
Steve Anton80dd7b52018-02-16 17:08:42 -08002112 // If a session error has occurred the PeerConnection is in a possibly
2113 // inconsistent state so fail right away.
2114 if (session_error() != SessionError::kNone) {
2115 std::string error_message = GetSessionErrorMsg();
2116 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002117 PostSetSessionDescriptionFailure(
2118 observer,
2119 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002120 return;
2121 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002122
Steve Anton80dd7b52018-02-16 17:08:42 -08002123 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2124 if (!error.ok()) {
2125 std::string error_message = GetSetDescriptionErrorMessage(
2126 cricket::CS_LOCAL, desc->GetType(), error);
2127 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002128 PostSetSessionDescriptionFailure(
2129 observer,
2130 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002131 return;
2132 }
2133
2134 // Grab the description type before moving ownership to ApplyLocalDescription,
2135 // which may destroy it before returning.
2136 const SdpType type = desc->GetType();
2137
2138 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002139 // |desc| may be destroyed at this point.
2140
2141 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002142 // If ApplyLocalDescription fails, the PeerConnection could be in an
2143 // inconsistent state, so act conservatively here and set the session error
2144 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2145 SetSessionError(SessionError::kContent, error.message());
2146 std::string error_message =
2147 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2148 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002149 PostSetSessionDescriptionFailure(
2150 observer,
2151 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002152 return;
2153 }
Steve Anton8a006912017-12-04 15:25:56 -08002154 RTC_DCHECK(local_description());
2155
2156 PostSetSessionDescriptionSuccess(observer);
2157
Steve Antonad182762018-09-05 20:22:40 +00002158 // MaybeStartGathering needs to be called after posting
2159 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2160 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002161 transport_controller_->MaybeStartGathering();
2162
Steve Antona3a92c22017-12-07 10:27:41 -08002163 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002164 // TODO(deadbeef): We already had to hop to the network thread for
2165 // MaybeStartGathering...
2166 network_thread()->Invoke<void>(
2167 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2168 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002169 // Make UMA notes about what was agreed to.
2170 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002171 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002172 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002173}
2174
2175RTCError PeerConnection::ApplyLocalDescription(
2176 std::unique_ptr<SessionDescriptionInterface> desc) {
2177 RTC_DCHECK_RUN_ON(signaling_thread());
2178 RTC_DCHECK(desc);
2179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180 // Update stats here so that we have the most recent stats for tracks and
2181 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002182 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002183
Steve Antondcc3c022017-12-22 16:02:54 -08002184 // Take a reference to the old local description since it's used below to
2185 // compare against the new local description. When setting the new local
2186 // description, grab ownership of the replaced session description in case it
2187 // is the same as |old_local_description|, to keep it alive for the duration
2188 // of the method.
2189 const SessionDescriptionInterface* old_local_description =
2190 local_description();
2191 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002192 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002193 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002194 replaced_local_description = pending_local_description_
2195 ? std::move(pending_local_description_)
2196 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002197 current_local_description_ = std::move(desc);
2198 pending_local_description_ = nullptr;
2199 current_remote_description_ = std::move(pending_remote_description_);
2200 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002201 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002202 pending_local_description_ = std::move(desc);
2203 }
2204 // The session description to apply now must be accessed by
2205 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002206 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002207
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002208 // Report statistics about any use of simulcast.
2209 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2210 *local_description()->description());
2211
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002212 if (!is_caller_) {
2213 if (remote_description()) {
2214 // Remote description was applied first, so this PC is the callee.
2215 is_caller_ = false;
2216 } else {
2217 // Local description is applied first, so this PC is the caller.
2218 is_caller_ = true;
2219 }
2220 }
2221
Zhi Huange830e682018-03-30 10:48:35 -07002222 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2223 if (!error.ok()) {
2224 return error;
2225 }
2226
Steve Antondcc3c022017-12-22 16:02:54 -08002227 if (IsUnifiedPlan()) {
2228 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002229 cricket::CS_LOCAL, *local_description(), old_local_description,
2230 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002231 if (!error.ok()) {
2232 return error;
2233 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002234 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2235 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002236 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002237 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2238 // Note that code paths that don't set MID won't be able to use
2239 // information about DTLS transports.
2240 if (transceiver->mid()) {
2241 auto dtls_transport =
2242 LookupDtlsTransportByMidInternal(*transceiver->mid());
2243 transceiver->internal()->sender_internal()->set_transport(
2244 dtls_transport);
2245 transceiver->internal()->receiver_internal()->set_transport(
2246 dtls_transport);
2247 }
2248
Steve Antondcc3c022017-12-22 16:02:54 -08002249 const ContentInfo* content =
2250 FindMediaSectionForTransceiver(transceiver, local_description());
2251 if (!content) {
2252 continue;
2253 }
2254 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002255 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2256 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002257 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002258 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2259 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2260 // "recvonly", process the removal of a remote track for the media
2261 // description, given transceiver, removeList, and muteTracks.
2262 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2263 (transceiver->internal()->fired_direction() &&
2264 RtpTransceiverDirectionHasRecv(
2265 *transceiver->internal()->fired_direction()))) {
2266 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2267 &removed_streams);
2268 }
2269 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2270 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002271 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002272 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002273 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002274 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002275 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002276 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002277 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002278 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002279 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002280 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002281 }
2282 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002283 // Media channels will be created only when offer is set. These may use new
2284 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002285 if (type == SdpType::kOffer) {
2286 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2287 // description is applied. Restore back to old description.
2288 RTCError error = CreateChannels(*local_description()->description());
2289 if (!error.ok()) {
2290 return error;
2291 }
2292 }
Steve Antondcc3c022017-12-22 16:02:54 -08002293 // Remove unused channels if MediaContentDescription is rejected.
2294 RemoveUnusedChannels(local_description()->description());
2295 }
Steve Anton8a006912017-12-04 15:25:56 -08002296
Zhi Huange830e682018-03-30 10:48:35 -07002297 error = UpdateSessionState(type, cricket::CS_LOCAL,
2298 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002299 if (!error.ok()) {
2300 return error;
2301 }
Steve Antondcc3c022017-12-22 16:02:54 -08002302
Steve Anton8a006912017-12-04 15:25:56 -08002303 if (remote_description()) {
2304 // Now that we have a local description, we can push down remote candidates.
2305 UseCandidatesInSessionDescription(remote_description());
2306 }
2307
2308 pending_ice_restarts_.clear();
2309 if (session_error() != SessionError::kNone) {
2310 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2311 }
2312
deadbeefab9b2d12015-10-14 11:33:11 -07002313 // If setting the description decided our SSL role, allocate any necessary
2314 // SCTP sids.
2315 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002316 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002317 AllocateSctpSids(role);
2318 }
2319
Steve Antond3679212018-01-17 17:41:02 -08002320 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002321 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002322 const ContentInfo* content =
2323 FindMediaSectionForTransceiver(transceiver, local_description());
2324 if (!content) {
2325 continue;
2326 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002327 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2328 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002329 // 0 is a special value meaning "this sender has no associated send
2330 // stream". Need to call this so the sender won't attempt to configure
2331 // a no longer existing stream and run into DCHECKs in the lower
2332 // layers.
2333 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002334 } else {
2335 // Get the StreamParams from the channel which could generate SSRCs.
2336 const std::vector<StreamParams>& streams = channel->local_streams();
2337 transceiver->internal()->sender_internal()->set_stream_ids(
2338 streams[0].stream_ids());
2339 transceiver->internal()->sender_internal()->SetSsrc(
2340 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002341 }
2342 }
2343 } else {
2344 // Plan B semantics.
2345
Steve Antondcc3c022017-12-22 16:02:54 -08002346 // Update state and SSRC of local MediaStreams and DataChannels based on the
2347 // local session description.
2348 const cricket::ContentInfo* audio_content =
2349 GetFirstAudioContent(local_description()->description());
2350 if (audio_content) {
2351 if (audio_content->rejected) {
2352 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2353 } else {
2354 const cricket::AudioContentDescription* audio_desc =
2355 audio_content->media_description()->as_audio();
2356 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2357 }
deadbeeffaac4972015-11-12 15:33:07 -08002358 }
deadbeefab9b2d12015-10-14 11:33:11 -07002359
Steve Antondcc3c022017-12-22 16:02:54 -08002360 const cricket::ContentInfo* video_content =
2361 GetFirstVideoContent(local_description()->description());
2362 if (video_content) {
2363 if (video_content->rejected) {
2364 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2365 } else {
2366 const cricket::VideoContentDescription* video_desc =
2367 video_content->media_description()->as_video();
2368 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2369 }
deadbeeffaac4972015-11-12 15:33:07 -08002370 }
deadbeefab9b2d12015-10-14 11:33:11 -07002371 }
2372
2373 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002374 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002375 if (data_content) {
2376 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002377 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002378 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002379 cricket::kMediaProtocolRtpPrefix)) {
2380 UpdateLocalRtpDataChannels(data_desc->streams());
2381 }
2382 }
2383
Steve Anton8a006912017-12-04 15:25:56 -08002384 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385}
2386
Steve Anton06817cd2018-12-18 15:55:30 -08002387// The SDP parser used to populate these values by default for the 'content
2388// name' if an a=mid line was absent.
2389static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2390 switch (media_type) {
2391 case cricket::MEDIA_TYPE_AUDIO:
2392 return cricket::CN_AUDIO;
2393 case cricket::MEDIA_TYPE_VIDEO:
2394 return cricket::CN_VIDEO;
2395 case cricket::MEDIA_TYPE_DATA:
2396 return cricket::CN_DATA;
2397 }
2398 RTC_NOTREACHED();
2399 return "";
2400}
2401
2402void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002403 cricket::SessionDescription* new_remote_description) {
2404 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002405 const cricket::ContentInfos& local_contents =
2406 (local_description() ? local_description()->description()->contents()
2407 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002408 const cricket::ContentInfos& remote_contents =
2409 (remote_description() ? remote_description()->description()->contents()
2410 : cricket::ContentInfos());
2411 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2412 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002413 if (!content.name.empty()) {
2414 continue;
2415 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002416 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002417 absl::string_view source_explanation;
2418 if (IsUnifiedPlan()) {
2419 if (i < local_contents.size()) {
2420 new_mid = local_contents[i].name;
2421 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002422 } else if (i < remote_contents.size()) {
2423 new_mid = remote_contents[i].name;
2424 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002425 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002426 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002427 source_explanation = "generated just now";
2428 }
2429 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002430 new_mid = std::string(
2431 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002432 source_explanation = "to match pre-existing behavior";
2433 }
Steve Antond7180cc2019-02-07 10:44:53 -08002434 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002435 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002436 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002437 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2438 << " is missing an a=mid line. Filling in the value '"
2439 << new_mid << "' " << source_explanation << ".";
2440 }
2441}
2442
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002443void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002444 SetSessionDescriptionObserver* observer,
2445 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002446 SetRemoteDescription(
2447 std::unique_ptr<SessionDescriptionInterface>(desc),
2448 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2449 new SetRemoteDescriptionObserverAdapter(this, observer)));
2450}
2451
2452void PeerConnection::SetRemoteDescription(
2453 std::unique_ptr<SessionDescriptionInterface> desc,
2454 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002455 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002456 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002457
nisse7ce109a2017-01-31 00:57:56 -08002458 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002459 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460 return;
2461 }
Steve Anton8a006912017-12-04 15:25:56 -08002462
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002464 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002465 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466 return;
2467 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002468
Steve Anton80dd7b52018-02-16 17:08:42 -08002469 // If a session error has occurred the PeerConnection is in a possibly
2470 // inconsistent state so fail right away.
2471 if (session_error() != SessionError::kNone) {
2472 std::string error_message = GetSessionErrorMsg();
2473 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2474 observer->OnSetRemoteDescriptionComplete(
2475 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2476 return;
2477 }
Steve Anton71439a62018-02-15 11:53:06 -08002478
Steve Antonba42e992018-04-09 14:10:01 -07002479 if (desc->GetType() == SdpType::kOffer) {
2480 // Report to UMA the format of the received offer.
2481 ReportSdpFormatReceived(*desc);
2482 }
2483
Steve Anton06817cd2018-12-18 15:55:30 -08002484 // Handle remote descriptions missing a=mid lines for interop with legacy end
2485 // points.
2486 FillInMissingRemoteMids(desc->description());
2487
Steve Anton80dd7b52018-02-16 17:08:42 -08002488 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002489 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002490 std::string error_message = GetSetDescriptionErrorMessage(
2491 cricket::CS_REMOTE, desc->GetType(), error);
2492 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002493 observer->OnSetRemoteDescriptionComplete(
2494 RTCError(error.type(), std::move(error_message)));
2495 return;
2496 }
Steve Anton71439a62018-02-15 11:53:06 -08002497
Steve Anton80dd7b52018-02-16 17:08:42 -08002498 // Grab the description type before moving ownership to
2499 // ApplyRemoteDescription, which may destroy it before returning.
2500 const SdpType type = desc->GetType();
2501
2502 error = ApplyRemoteDescription(std::move(desc));
2503 // |desc| may be destroyed at this point.
2504
2505 if (!error.ok()) {
2506 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2507 // inconsistent state, so act conservatively here and set the session error
2508 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2509 SetSessionError(SessionError::kContent, error.message());
2510 std::string error_message =
2511 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2512 RTC_LOG(LS_ERROR) << error_message;
2513 observer->OnSetRemoteDescriptionComplete(
2514 RTCError(error.type(), std::move(error_message)));
2515 return;
2516 }
2517 RTC_DCHECK(remote_description());
2518
2519 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002520 // TODO(deadbeef): We already had to hop to the network thread for
2521 // MaybeStartGathering...
2522 network_thread()->Invoke<void>(
2523 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2524 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002525 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002526 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002527 }
2528
2529 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002530 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002531}
2532
2533RTCError PeerConnection::ApplyRemoteDescription(
2534 std::unique_ptr<SessionDescriptionInterface> desc) {
2535 RTC_DCHECK_RUN_ON(signaling_thread());
2536 RTC_DCHECK(desc);
2537
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002538 // Update stats here so that we have the most recent stats for tracks and
2539 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002540 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002541
Steve Antondcc3c022017-12-22 16:02:54 -08002542 // Take a reference to the old remote description since it's used below to
2543 // compare against the new remote description. When setting the new remote
2544 // description, grab ownership of the replaced session description in case it
2545 // is the same as |old_remote_description|, to keep it alive for the duration
2546 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002547 const SessionDescriptionInterface* old_remote_description =
2548 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002549 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002550 SdpType type = desc->GetType();
2551 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002552 replaced_remote_description = pending_remote_description_
2553 ? std::move(pending_remote_description_)
2554 : std::move(current_remote_description_);
2555 current_remote_description_ = std::move(desc);
2556 pending_remote_description_ = nullptr;
2557 current_local_description_ = std::move(pending_local_description_);
2558 } else {
2559 replaced_remote_description = std::move(pending_remote_description_);
2560 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002561 }
Steve Anton8a006912017-12-04 15:25:56 -08002562 // The session description to apply now must be accessed by
2563 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002564 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002565
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002566 // Report statistics about any use of simulcast.
2567 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2568 *remote_description()->description());
2569
Zhi Huange830e682018-03-30 10:48:35 -07002570 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2571 if (!error.ok()) {
2572 return error;
2573 }
Steve Anton8a006912017-12-04 15:25:56 -08002574 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002575 if (IsUnifiedPlan()) {
2576 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002577 cricket::CS_REMOTE, *remote_description(), local_description(),
2578 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002579 if (!error.ok()) {
2580 return error;
2581 }
Steve Antondcc3c022017-12-22 16:02:54 -08002582 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002583 // Media channels will be created only when offer is set. These may use new
2584 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002585 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002586 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002587 // description is applied. Restore back to old description.
2588 RTCError error = CreateChannels(*remote_description()->description());
2589 if (!error.ok()) {
2590 return error;
2591 }
2592 }
Steve Antondcc3c022017-12-22 16:02:54 -08002593 // Remove unused channels if MediaContentDescription is rejected.
2594 RemoveUnusedChannels(remote_description()->description());
2595 }
Steve Anton8a006912017-12-04 15:25:56 -08002596
Zhi Huange830e682018-03-30 10:48:35 -07002597 // NOTE: Candidates allocation will be initiated only when
2598 // SetLocalDescription is called.
2599 error = UpdateSessionState(type, cricket::CS_REMOTE,
2600 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002601 if (!error.ok()) {
2602 return error;
2603 }
2604
2605 if (local_description() &&
2606 !UseCandidatesInSessionDescription(remote_description())) {
2607 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2608 }
2609
2610 if (old_remote_description) {
2611 for (const cricket::ContentInfo& content :
2612 old_remote_description->description()->contents()) {
2613 // Check if this new SessionDescription contains new ICE ufrag and
2614 // password that indicates the remote peer requests an ICE restart.
2615 // TODO(deadbeef): When we start storing both the current and pending
2616 // remote description, this should reset pending_ice_restarts and compare
2617 // against the current description.
2618 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2619 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002620 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002621 pending_ice_restarts_.insert(content.name);
2622 }
2623 } else {
2624 // We retain all received candidates only if ICE is not restarted.
2625 // When ICE is restarted, all previous candidates belong to an old
2626 // generation and should not be kept.
2627 // TODO(deadbeef): This goes against the W3C spec which says the remote
2628 // description should only contain candidates from the last set remote
2629 // description plus any candidates added since then. We should remove
2630 // this once we're sure it won't break anything.
2631 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2632 old_remote_description, content.name, mutable_remote_description());
2633 }
2634 }
2635 }
2636
2637 if (session_error() != SessionError::kNone) {
2638 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2639 }
2640
2641 // Set the the ICE connection state to connecting since the connection may
2642 // become writable with peer reflexive candidates before any remote candidate
2643 // is signaled.
2644 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2645 // is to have a new signal the indicates a change in checking state from the
2646 // transport and expose a new checking() member from transport that can be
2647 // read to determine the current checking state. The existing SignalConnecting
2648 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002649 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002650 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002651 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2652 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2653 }
2654
deadbeefab9b2d12015-10-14 11:33:11 -07002655 // If setting the description decided our SSL role, allocate any necessary
2656 // SCTP sids.
2657 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002658 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002659 AllocateSctpSids(role);
2660 }
2661
Steve Antondcc3c022017-12-22 16:02:54 -08002662 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002663 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002664 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002665 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002666 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002667 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002668 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002669 const ContentInfo* content =
2670 FindMediaSectionForTransceiver(transceiver, remote_description());
2671 if (!content) {
2672 continue;
2673 }
2674 const MediaContentDescription* media_desc = content->media_description();
2675 RtpTransceiverDirection local_direction =
2676 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002677 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2678 // RTCSessionDescription: Set the associated remote streams given
2679 // transceiver.[[Receiver]], msids, addList, and removeList".
2680 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2681 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2682 std::vector<std::string> stream_ids;
2683 if (!media_desc->streams().empty()) {
2684 // The remote description has signaled the stream IDs.
2685 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002686 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002687 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2688 << " (" << GetStreamIdsString(stream_ids) << ").";
2689 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2690 stream_ids, &added_streams,
2691 &removed_streams);
2692 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2693 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2694 // and transceiver's current direction is neither sendrecv nor recvonly,
2695 // process the addition of a remote track for the media description.
2696 if (!transceiver->fired_direction() ||
2697 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2698 RTC_LOG(LS_INFO)
2699 << "Processing the addition of a remote track for MID="
2700 << content->name << ".";
2701 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002702 }
Steve Antondcc3c022017-12-22 16:02:54 -08002703 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002704 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002705 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2706 // removal of a remote track for the media description, given transceiver,
2707 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002708 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002709 (transceiver->fired_direction() &&
2710 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2711 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2712 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002713 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002714 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002715 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002716 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002717 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002718 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002719 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002720 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002721 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002722 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2723 if (transceiver->mid()) {
2724 auto dtls_transport =
2725 LookupDtlsTransportByMidInternal(*transceiver->mid());
2726 transceiver->internal()->sender_internal()->set_transport(
2727 dtls_transport);
2728 transceiver->internal()->receiver_internal()->set_transport(
2729 dtls_transport);
2730 }
Steve Antondcc3c022017-12-22 16:02:54 -08002731 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002732 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002733 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002734 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002735 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2736 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002737 transceiver->Stop();
2738 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002739 if (!content->rejected &&
2740 RtpTransceiverDirectionHasRecv(local_direction)) {
2741 // Set ssrc to 0 in the case of an unsignalled ssrc.
2742 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002743 if (!media_desc->streams().empty() &&
2744 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002745 ssrc = media_desc->streams()[0].first_ssrc();
2746 }
2747 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002748 }
Steve Antondcc3c022017-12-22 16:02:54 -08002749 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002750 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002751 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002752 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002753 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002754 observer->OnTrack(transceiver);
2755 observer->OnAddTrack(transceiver->receiver(),
2756 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002757 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002758 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002759 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002760 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002761 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002762 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002763 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002764 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002765 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002766 }
Steve Antondcc3c022017-12-22 16:02:54 -08002767 }
2768
Henrik Boströmfdb92012017-11-09 19:55:44 +01002769 const cricket::ContentInfo* audio_content =
2770 GetFirstAudioContent(remote_description()->description());
2771 const cricket::ContentInfo* video_content =
2772 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002773 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002774 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002775 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002776 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002777 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002778 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002779
2780 // Check if the descriptions include streams, just in case the peer supports
2781 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002782 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002783 (audio_desc && !audio_desc->streams().empty()) ||
2784 (video_desc && !video_desc->streams().empty())) {
2785 remote_peer_supports_msid_ = true;
2786 }
deadbeefab9b2d12015-10-14 11:33:11 -07002787
2788 // We wait to signal new streams until we finish processing the description,
2789 // since only at that point will new streams have all their tracks.
2790 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2791
Steve Antondcc3c022017-12-22 16:02:54 -08002792 if (!IsUnifiedPlan()) {
2793 // TODO(steveanton): When removing RTP senders/receivers in response to a
2794 // rejected media section, there is some cleanup logic that expects the
2795 // voice/ video channel to still be set. But in this method the voice/video
2796 // channel would have been destroyed by the SetRemoteDescription caller
2797 // above so the cleanup that relies on them fails to run. The RemoveSenders
2798 // calls should be moved to right before the DestroyChannel calls to fix
2799 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002800
Steve Antondcc3c022017-12-22 16:02:54 -08002801 // Find all audio rtp streams and create corresponding remote AudioTracks
2802 // and MediaStreams.
2803 if (audio_content) {
2804 if (audio_content->rejected) {
2805 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2806 } else {
2807 bool default_audio_track_needed =
2808 !remote_peer_supports_msid_ &&
2809 RtpTransceiverDirectionHasSend(audio_desc->direction());
2810 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2811 default_audio_track_needed, audio_desc->type(),
2812 new_streams);
2813 }
deadbeeffaac4972015-11-12 15:33:07 -08002814 }
deadbeefab9b2d12015-10-14 11:33:11 -07002815
Steve Antondcc3c022017-12-22 16:02:54 -08002816 // Find all video rtp streams and create corresponding remote VideoTracks
2817 // and MediaStreams.
2818 if (video_content) {
2819 if (video_content->rejected) {
2820 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2821 } else {
2822 bool default_video_track_needed =
2823 !remote_peer_supports_msid_ &&
2824 RtpTransceiverDirectionHasSend(video_desc->direction());
2825 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2826 default_video_track_needed, video_desc->type(),
2827 new_streams);
2828 }
deadbeeffaac4972015-11-12 15:33:07 -08002829 }
deadbeefab9b2d12015-10-14 11:33:11 -07002830
Steve Antondcc3c022017-12-22 16:02:54 -08002831 // Update the DataChannels with the information from the remote peer.
2832 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002833 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002834 cricket::kMediaProtocolRtpPrefix)) {
2835 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2836 }
deadbeefab9b2d12015-10-14 11:33:11 -07002837 }
deadbeefab9b2d12015-10-14 11:33:11 -07002838
Steve Antondcc3c022017-12-22 16:02:54 -08002839 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002840 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002841 for (size_t i = 0; i < new_streams->count(); ++i) {
2842 MediaStreamInterface* new_stream = new_streams->at(i);
2843 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002844 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002845 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2846 }
deadbeefab9b2d12015-10-14 11:33:11 -07002847
Steve Antondcc3c022017-12-22 16:02:54 -08002848 UpdateEndedRemoteMediaStreams();
2849 }
deadbeefab9b2d12015-10-14 11:33:11 -07002850
Steve Anton8a006912017-12-04 15:25:56 -08002851 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002852}
2853
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002854void PeerConnection::SetAssociatedRemoteStreams(
2855 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2856 const std::vector<std::string>& stream_ids,
2857 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2858 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2859 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2860 for (const std::string& stream_id : stream_ids) {
2861 rtc::scoped_refptr<MediaStreamInterface> stream =
2862 remote_streams_->find(stream_id);
2863 if (!stream) {
2864 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2865 MediaStream::Create(stream_id));
2866 remote_streams_->AddStream(stream);
2867 added_streams->push_back(stream);
2868 }
2869 media_streams.push_back(stream);
2870 }
2871 // Special case: "a=msid" missing, use random stream ID.
2872 if (media_streams.empty() &&
2873 !(remote_description()->description()->msid_signaling() &
2874 cricket::kMsidSignalingMediaSection)) {
2875 if (!missing_msid_default_stream_) {
2876 missing_msid_default_stream_ = MediaStreamProxy::Create(
2877 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2878 added_streams->push_back(missing_msid_default_stream_);
2879 }
2880 media_streams.push_back(missing_msid_default_stream_);
2881 }
2882 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2883 receiver->streams();
2884 // SetStreams() will add/remove the receiver's track to/from the streams. This
2885 // differs from the spec - the spec uses an "addList" and "removeList" to
2886 // update the stream-track relationships in a later step. We do this earlier,
2887 // changing the order of things, but the end-result is the same.
2888 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2889 // instead. https://crbug.com/webrtc/9480
2890 receiver->SetStreams(media_streams);
2891 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2892}
2893
Steve Anton0f5400a2018-07-17 14:25:36 -07002894void PeerConnection::ProcessRemovalOfRemoteTrack(
2895 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2896 transceiver,
2897 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2898 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2899 RTC_DCHECK(transceiver->mid());
2900 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2901 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002902 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002903 transceiver->internal()->receiver_internal()->streams();
2904 // This will remove the remote track from the streams.
2905 transceiver->internal()->receiver_internal()->set_stream_ids({});
2906 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002907 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2908}
2909
2910void PeerConnection::RemoveRemoteStreamsIfEmpty(
2911 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2912 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2913 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2914 // streams, see if the stream was removed by checking if this was the last
2915 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002916 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002917 if (remote_stream->GetAudioTracks().empty() &&
2918 remote_stream->GetVideoTracks().empty()) {
2919 remote_streams_->RemoveStream(remote_stream);
2920 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002921 }
2922 }
2923}
2924
Steve Antondcc3c022017-12-22 16:02:54 -08002925RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2926 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002927 const SessionDescriptionInterface& new_session,
2928 const SessionDescriptionInterface* old_local_description,
2929 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002930 RTC_DCHECK(IsUnifiedPlan());
2931
Steve Anton7464fca2018-01-19 11:10:37 -08002932 const cricket::ContentGroup* bundle_group = nullptr;
2933 if (new_session.GetType() == SdpType::kOffer) {
2934 auto bundle_group_or_error =
2935 GetEarlyBundleGroup(*new_session.description());
2936 if (!bundle_group_or_error.ok()) {
2937 return bundle_group_or_error.MoveError();
2938 }
2939 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002940 }
Steve Antondcc3c022017-12-22 16:02:54 -08002941
Steve Antondcc3c022017-12-22 16:02:54 -08002942 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002943 for (size_t i = 0; i < new_contents.size(); ++i) {
2944 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002945 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002946 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002947 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2948 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002949 const cricket::ContentInfo* old_local_content = nullptr;
2950 if (old_local_description &&
2951 i < old_local_description->description()->contents().size()) {
2952 old_local_content =
2953 &old_local_description->description()->contents()[i];
2954 }
2955 const cricket::ContentInfo* old_remote_content = nullptr;
2956 if (old_remote_description &&
2957 i < old_remote_description->description()->contents().size()) {
2958 old_remote_content =
2959 &old_remote_description->description()->contents()[i];
2960 }
Steve Antondcc3c022017-12-22 16:02:54 -08002961 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002962 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2963 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002964 if (!transceiver_or_error.ok()) {
2965 return transceiver_or_error.MoveError();
2966 }
2967 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002968 RTCError error =
2969 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2970 if (!error.ok()) {
2971 return error;
2972 }
2973 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002974 if (GetDataMid() && new_content.name != *GetDataMid()) {
2975 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002976 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2977 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002978 continue;
2979 }
2980 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2981 if (!error.ok()) {
2982 return error;
2983 }
Steve Antondcc3c022017-12-22 16:02:54 -08002984 } else {
2985 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2986 "Unknown section type.");
2987 }
2988 }
2989
2990 return RTCError::OK();
2991}
2992
2993RTCError PeerConnection::UpdateTransceiverChannel(
2994 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2995 transceiver,
2996 const cricket::ContentInfo& content,
2997 const cricket::ContentGroup* bundle_group) {
2998 RTC_DCHECK(IsUnifiedPlan());
2999 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003000 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003001 if (content.rejected) {
3002 if (channel) {
3003 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003004 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003005 }
3006 } else {
3007 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003008 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003009 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003010 } else {
Steve Anton69470252018-02-09 11:43:08 -08003011 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003012 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003013 }
3014 if (!channel) {
3015 LOG_AND_RETURN_ERROR(
3016 RTCErrorType::INTERNAL_ERROR,
3017 "Failed to create channel for mid=" + content.name);
3018 }
3019 transceiver->internal()->SetChannel(channel);
3020 }
3021 }
3022 return RTCError::OK();
3023}
3024
Steve Antonfa2260d2017-12-28 16:38:23 -08003025RTCError PeerConnection::UpdateDataChannel(
3026 cricket::ContentSource source,
3027 const cricket::ContentInfo& content,
3028 const cricket::ContentGroup* bundle_group) {
3029 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003030 // If data channels are disabled, ignore this media section. CreateAnswer
3031 // will take care of rejecting it.
3032 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003033 }
3034 if (content.rejected) {
3035 DestroyDataChannel();
3036 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003037 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003038 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003039 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3040 "Failed to create data channel.");
3041 }
3042 }
3043 if (source == cricket::CS_REMOTE) {
3044 const MediaContentDescription* data_desc = content.media_description();
3045 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3046 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3047 }
3048 }
3049 }
3050 return RTCError::OK();
3051}
3052
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003053// This method will extract any send encodings that were sent by the remote
3054// connection. This is currently only relevant for Simulcast scenario (where
3055// the number of layers may be communicated by the server).
3056static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3057 const MediaContentDescription& desc) {
3058 if (!desc.HasSimulcast()) {
3059 return {};
3060 }
3061 std::vector<RtpEncodingParameters> result;
3062 const SimulcastDescription& simulcast = desc.simulcast_description();
3063
3064 // This is a remote description, the parameters we are after should appear
3065 // as receive streams.
3066 for (const auto& alternatives : simulcast.receive_layers()) {
3067 RTC_DCHECK(!alternatives.empty());
3068 // There is currently no way to specify or choose from alternatives.
3069 // We will always use the first alternative, which is the most preferred.
3070 const SimulcastLayer& layer = alternatives[0];
3071 RtpEncodingParameters parameters;
3072 parameters.rid = layer.rid;
3073 parameters.active = !layer.is_paused;
3074 result.push_back(parameters);
3075 }
3076
3077 return result;
3078}
3079
3080static RTCError UpdateSimulcastLayerStatusInSender(
3081 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003082 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003083 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003084 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003085 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003086
3087 // The simulcast envelope cannot be changed, only the status of the streams.
3088 // So we will iterate over the send encodings rather than the layers.
3089 for (RtpEncodingParameters& encoding : parameters.encodings) {
3090 auto iter = std::find_if(layers.begin(), layers.end(),
3091 [&encoding](const SimulcastLayer& layer) {
3092 return layer.rid == encoding.rid;
3093 });
3094 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003095 if (iter == layers.end()) {
3096 disabled_layers.push_back(encoding.rid);
3097 continue;
3098 }
3099
3100 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003101 }
3102
Amit Hilbuch619b2942019-02-26 15:55:19 -08003103 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003104 if (result.ok()) {
3105 result = sender->DisableEncodingLayers(disabled_layers);
3106 }
3107
3108 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003109}
3110
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003111static bool SimulcastIsRejected(
3112 const ContentInfo* local_content,
3113 const MediaContentDescription& answer_media_desc) {
3114 bool simulcast_offered = local_content &&
3115 local_content->media_description() &&
3116 local_content->media_description()->HasSimulcast();
3117 bool simulcast_answered = answer_media_desc.HasSimulcast();
3118 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3119 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3120 return simulcast_offered && (!simulcast_answered || !rids_supported);
3121}
3122
Amit Hilbuch2297d332019-02-19 12:49:22 -08003123static RTCError DisableSimulcastInSender(
3124 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003125 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003126 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003127 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003128 return RTCError::OK();
3129 }
3130
Amit Hilbuch2297d332019-02-19 12:49:22 -08003131 std::vector<std::string> disabled_layers;
3132 std::transform(
3133 parameters.encodings.begin() + 1, parameters.encodings.end(),
3134 std::back_inserter(disabled_layers),
3135 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3136 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003137}
3138
Steve Antondcc3c022017-12-22 16:02:54 -08003139RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3140PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003141 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003142 size_t mline_index,
3143 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003144 const ContentInfo* old_local_content,
3145 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003146 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003147 // If this is an offer then the m= section might be recycled. If the m=
3148 // section is being recycled (defined as: rejected in the current local or
3149 // remote description and not rejected in new description), dissociate the
3150 // currently associated RtpTransceiver by setting its mid property to null,
3151 // and discard the mapping between the transceiver and its m= section index.
3152 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3153 old_remote_content)) {
3154 // We want to dissociate the transceiver that has the rejected mid.
3155 const std::string& old_mid =
3156 (old_local_content && old_local_content->rejected)
3157 ? old_local_content->name
3158 : old_remote_content->name;
3159 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003160 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003161 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3162 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003163 old_transceiver->internal()->set_mid(absl::nullopt);
3164 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003165 }
3166 }
3167 const MediaContentDescription* media_desc = content.media_description();
3168 auto transceiver = GetAssociatedTransceiver(content.name);
3169 if (source == cricket::CS_LOCAL) {
3170 // Find the RtpTransceiver that corresponds to this m= section, using the
3171 // mapping between transceivers and m= section indices established when
3172 // creating the offer.
3173 if (!transceiver) {
3174 transceiver = GetTransceiverByMLineIndex(mline_index);
3175 }
3176 if (!transceiver) {
3177 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3178 "Unknown transceiver");
3179 }
3180 } else {
3181 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3182 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3183 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003184 // When simulcast is requested, a transceiver cannot be associated because
3185 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003186 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003187 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3188 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003189 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3190 }
3191 // If no RtpTransceiver was found in the previous step, create one with a
3192 // recvonly direction.
3193 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003194 RTC_LOG(LS_INFO) << "Adding "
3195 << cricket::MediaTypeToString(media_desc->type())
3196 << " transceiver for MID=" << content.name
3197 << " at i=" << mline_index
3198 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003199 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003200 std::vector<RtpEncodingParameters> send_encodings =
3201 GetSendEncodingsFromRemoteDescription(*media_desc);
3202 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3203 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003204 std::string receiver_id;
3205 if (!media_desc->streams().empty()) {
3206 receiver_id = media_desc->streams()[0].id;
3207 } else {
3208 receiver_id = rtc::CreateRandomUuid();
3209 }
3210 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003211 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003212 transceiver->internal()->set_direction(
3213 RtpTransceiverDirection::kRecvOnly);
3214 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003215
3216 // Check if the offer indicated simulcast but the answer rejected it.
3217 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003218 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003219 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003220 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003221 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003222 if (!error.ok()) {
3223 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3224 return std::move(error);
3225 }
3226 }
Steve Antondcc3c022017-12-22 16:02:54 -08003227 }
3228 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003229 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003230 LOG_AND_RETURN_ERROR(
3231 RTCErrorType::INVALID_PARAMETER,
3232 "Transceiver type does not match media description type.");
3233 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003234 if (media_desc->HasSimulcast()) {
3235 std::vector<SimulcastLayer> layers =
3236 source == cricket::CS_LOCAL
3237 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3238 : media_desc->simulcast_description()
3239 .receive_layers()
3240 .GetAllLayers();
3241 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003242 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003243 if (!error.ok()) {
3244 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3245 return std::move(error);
3246 }
3247 }
Steve Antondcc3c022017-12-22 16:02:54 -08003248 // Associate the found or created RtpTransceiver with the m= section by
3249 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3250 // section, and establish a mapping between the transceiver and the index of
3251 // the m= section.
3252 transceiver->internal()->set_mid(content.name);
3253 transceiver->internal()->set_mline_index(mline_index);
3254 return std::move(transceiver);
3255}
3256
3257rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3258PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3259 RTC_DCHECK(IsUnifiedPlan());
3260 for (auto transceiver : transceivers_) {
3261 if (transceiver->mid() == mid) {
3262 return transceiver;
3263 }
3264 }
3265 return nullptr;
3266}
3267
3268rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3269PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3270 RTC_DCHECK(IsUnifiedPlan());
3271 for (auto transceiver : transceivers_) {
3272 if (transceiver->internal()->mline_index() == mline_index) {
3273 return transceiver;
3274 }
3275 }
3276 return nullptr;
3277}
3278
3279rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3280PeerConnection::FindAvailableTransceiverToReceive(
3281 cricket::MediaType media_type) const {
3282 RTC_DCHECK(IsUnifiedPlan());
3283 // From JSEP section 5.10 (Applying a Remote Description):
3284 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3285 // the same type that were added to the PeerConnection by addTrack and are not
3286 // associated with any m= section and are not stopped, find the first such
3287 // RtpTransceiver.
3288 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003289 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003290 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3291 !transceiver->stopped()) {
3292 return transceiver;
3293 }
3294 }
3295 return nullptr;
3296}
3297
Steve Antoned10bd92017-12-05 10:52:59 -08003298const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3299 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3300 transceiver,
3301 const SessionDescriptionInterface* sdesc) const {
3302 RTC_DCHECK(transceiver);
3303 RTC_DCHECK(sdesc);
3304 if (IsUnifiedPlan()) {
3305 if (!transceiver->internal()->mid()) {
3306 // This transceiver is not associated with a media section yet.
3307 return nullptr;
3308 }
3309 return sdesc->description()->GetContentByName(
3310 *transceiver->internal()->mid());
3311 } else {
3312 // Plan B only allows at most one audio and one video section, so use the
3313 // first media section of that type.
3314 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003315 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003316 }
3317}
3318
deadbeef46c73892016-11-16 19:42:04 -08003319PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003320 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003321 return configuration_;
3322}
3323
deadbeef293e9262017-01-11 12:28:30 -08003324bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3325 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003326 RTC_DCHECK_RUN_ON(signaling_thread());
3327 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003328 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003329 if (IsClosed()) {
3330 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3331 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3332 }
3333
Qingsi Wanga2d60672018-04-11 16:57:45 -07003334 // According to JSEP, after setLocalDescription, changing the candidate pool
3335 // size is not allowed, and changing the set of ICE servers will not result
3336 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003337 if (local_description() && configuration.ice_candidate_pool_size !=
3338 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003339 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3340 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003341 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003342 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003343
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003344 if (local_description() &&
3345 configuration.use_media_transport != configuration_.use_media_transport) {
3346 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3347 "SetLocalDescription.";
3348 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3349 }
3350
3351 if (remote_description() &&
3352 configuration.use_media_transport != configuration_.use_media_transport) {
3353 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3354 "SetRemoteDescription.";
3355 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3356 }
3357
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003358 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003359 configuration.use_media_transport_for_data_channels !=
3360 configuration_.use_media_transport_for_data_channels) {
3361 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3362 "after calling SetLocalDescription.";
3363 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3364 }
3365
3366 if (remote_description() &&
3367 configuration.use_media_transport_for_data_channels !=
3368 configuration_.use_media_transport_for_data_channels) {
3369 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3370 "after calling SetRemoteDescription.";
3371 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3372 }
3373
3374 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003375 configuration.crypto_options != configuration_.crypto_options) {
3376 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3377 "SetLocalDescription.";
3378 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3379 }
3380
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003381 if (configuration.use_media_transport_for_data_channels ||
3382 configuration.use_media_transport) {
3383 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3384 << "Media transport requires MaxBundle policy.";
3385 }
3386
deadbeef293e9262017-01-11 12:28:30 -08003387 // The simplest (and most future-compatible) way to tell if the config was
3388 // modified in an invalid way is to copy each property we do support
3389 // modifying, then use operator==. There are far more properties we don't
3390 // support modifying than those we do, and more could be added.
3391 RTCConfiguration modified_config = configuration_;
3392 modified_config.servers = configuration.servers;
3393 modified_config.type = configuration.type;
3394 modified_config.ice_candidate_pool_size =
3395 configuration.ice_candidate_pool_size;
3396 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003397 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003398 modified_config.ice_check_interval_strong_connectivity =
3399 configuration.ice_check_interval_strong_connectivity;
3400 modified_config.ice_check_interval_weak_connectivity =
3401 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003402 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3403 modified_config.ice_unwritable_min_checks =
3404 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003405 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003406 modified_config.stun_candidate_keepalive_interval =
3407 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003408 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003409 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003410 modified_config.active_reset_srtp_params =
3411 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003412 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003413 modified_config.use_media_transport_for_data_channels =
3414 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003415 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003416 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003417 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3418 }
3419
Steve Anton038834f2017-07-14 15:59:59 -07003420 // Validate the modified configuration.
3421 RTCError validate_error = ValidateConfiguration(modified_config);
3422 if (!validate_error.ok()) {
3423 return SafeSetError(std::move(validate_error), error);
3424 }
3425
deadbeef293e9262017-01-11 12:28:30 -08003426 // Note that this isn't possible through chromium, since it's an unsigned
3427 // short in WebIDL.
3428 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003429 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003430 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3431 }
3432
3433 // Parse ICE servers before hopping to network thread.
3434 cricket::ServerAddresses stun_servers;
3435 std::vector<cricket::RelayServerConfig> turn_servers;
3436 RTCErrorType parse_error =
3437 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3438 if (parse_error != RTCErrorType::NONE) {
3439 return SafeSetError(parse_error, error);
3440 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003441 // Note if STUN or TURN servers were supplied.
3442 if (!stun_servers.empty()) {
3443 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3444 }
3445 if (!turn_servers.empty()) {
3446 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3447 }
deadbeef293e9262017-01-11 12:28:30 -08003448
3449 // In theory this shouldn't fail.
3450 if (!network_thread()->Invoke<bool>(
3451 RTC_FROM_HERE,
3452 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3453 stun_servers, turn_servers, modified_config.type,
3454 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003455 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003456 modified_config.turn_customizer,
3457 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003458 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003459 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3460 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003461
deadbeefd1a38b52016-12-10 13:15:33 -08003462 // As described in JSEP, calling setConfiguration with new ICE servers or
3463 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3464 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003465 if (modified_config.servers != configuration_.servers ||
3466 modified_config.type != configuration_.type ||
3467 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003468 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003469 }
skvladd1f5fda2017-02-03 16:54:05 -08003470
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003471 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003472 transport_controller_->SetMediaTransportSettings(
3473 modified_config.use_media_transport,
3474 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003475
Zhi Huangb57e1692018-06-12 11:41:11 -07003476 if (configuration_.active_reset_srtp_params !=
3477 modified_config.active_reset_srtp_params) {
3478 transport_controller_->SetActiveResetSrtpParams(
3479 modified_config.active_reset_srtp_params);
3480 }
3481
deadbeef293e9262017-01-11 12:28:30 -08003482 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003483 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003484 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003485}
3486
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003487bool PeerConnection::AddIceCandidate(
3488 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003489 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003490 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003491 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003492 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003493 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003494 return false;
3495 }
Steve Antond25da372017-11-06 14:50:29 -08003496
3497 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003498 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003499 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003500 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003501 return false;
3502 }
3503
3504 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003505 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003506 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003507 return false;
3508 }
3509
3510 bool valid = false;
3511 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3512 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003513 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003514 return false;
3515 }
3516
3517 // Add this candidate to the remote session description.
3518 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003519 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003520 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003521 return false;
3522 }
3523
3524 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003525 bool result = UseCandidate(ice_candidate);
3526 if (result) {
3527 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3528 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3529 } else {
3530 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3531 }
3532 return result;
Steve Antond25da372017-11-06 14:50:29 -08003533 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003534 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003535 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003536 return true;
3537 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538}
3539
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003540bool PeerConnection::RemoveIceCandidates(
3541 const std::vector<cricket::Candidate>& candidates) {
3542 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003543 if (IsClosed()) {
3544 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3545 return false;
3546 }
3547
Steve Antond25da372017-11-06 14:50:29 -08003548 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003549 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3550 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003551 return false;
3552 }
3553
3554 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003555 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003556 return false;
3557 }
3558
3559 size_t number_removed =
3560 mutable_remote_description()->RemoveCandidates(candidates);
3561 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003562 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003563 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003564 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003565 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003566 }
3567
3568 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003569 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3570 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003571 RTC_LOG(LS_ERROR)
3572 << "RemoveIceCandidates: Error when removing remote candidates: "
3573 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003574 }
3575 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003576}
3577
Niels Möller0c4f7be2018-05-07 14:01:37 +02003578RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003579 if (!worker_thread()->IsCurrent()) {
3580 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003581 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003582 }
3583
Niels Möller0c4f7be2018-05-07 14:01:37 +02003584 const bool has_min = bitrate.min_bitrate_bps.has_value();
3585 const bool has_start = bitrate.start_bitrate_bps.has_value();
3586 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003587 if (has_min && *bitrate.min_bitrate_bps < 0) {
3588 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3589 "min_bitrate_bps <= 0");
3590 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003591 if (has_start) {
3592 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003593 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003594 "start_bitrate_bps < min_bitrate_bps");
3595 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003596 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3597 "curent_bitrate_bps < 0");
3598 }
3599 }
3600 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003601 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003602 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003603 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003604 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3605 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3606 "max_bitrate_bps < min_bitrate_bps");
3607 } else if (*bitrate.max_bitrate_bps < 0) {
3608 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3609 "max_bitrate_bps < 0");
3610 }
3611 }
3612
zstein4b979802017-06-02 14:37:37 -07003613 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003614 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003615
3616 return RTCError::OK();
3617}
3618
Alex Narest78609d52017-10-20 10:37:47 +02003619void PeerConnection::SetBitrateAllocationStrategy(
3620 std::unique_ptr<rtc::BitrateAllocationStrategy>
3621 bitrate_allocation_strategy) {
3622 rtc::Thread* worker_thread = factory_->worker_thread();
3623 if (!worker_thread->IsCurrent()) {
3624 rtc::BitrateAllocationStrategy* strategy_raw =
3625 bitrate_allocation_strategy.release();
3626 auto functor = [this, strategy_raw]() {
3627 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003628 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003629 };
3630 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3631 return;
3632 }
3633 RTC_DCHECK(call_.get());
3634 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3635}
3636
henrika5f6bf242017-11-01 11:06:56 +01003637void PeerConnection::SetAudioPlayout(bool playout) {
3638 if (!worker_thread()->IsCurrent()) {
3639 worker_thread()->Invoke<void>(
3640 RTC_FROM_HERE,
3641 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3642 return;
3643 }
3644 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003645 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003646 audio_state->SetPlayout(playout);
3647}
3648
3649void PeerConnection::SetAudioRecording(bool recording) {
3650 if (!worker_thread()->IsCurrent()) {
3651 worker_thread()->Invoke<void>(
3652 RTC_FROM_HERE,
3653 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3654 return;
3655 }
3656 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003657 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003658 audio_state->SetRecording(recording);
3659}
3660
Steve Anton8c0f7a72017-10-03 10:03:10 -07003661std::unique_ptr<rtc::SSLCertificate>
3662PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003663 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3664 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003665 return nullptr;
3666 }
Steve Antonf25303e2018-10-16 15:23:31 -07003667 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003668}
3669
Zhi Huang70b820f2018-01-27 14:16:15 -08003670std::unique_ptr<rtc::SSLCertChain>
3671PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003672 auto audio_transceiver = GetFirstAudioTransceiver();
3673 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003674 return nullptr;
3675 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003676 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003677 audio_transceiver->internal()->channel()->transport_name());
3678}
3679
3680rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3681PeerConnection::GetFirstAudioTransceiver() const {
3682 for (auto transceiver : transceivers_) {
3683 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3684 return transceiver;
3685 }
3686 }
3687 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003688}
3689
ivoc14d5dbe2016-07-04 07:06:55 -07003690bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3691 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003692 // TODO(eladalon): It would be better to not allow negative values into PC.
3693 const size_t max_size = (max_size_bytes < 0)
3694 ? RtcEventLog::kUnlimitedOutput
3695 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003696 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3697 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3698 output_period_ms = 5000;
3699 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003700 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003701 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003702 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003703}
3704
Bjorn Tereliusde939432017-11-20 17:38:14 +01003705bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3706 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003707 // TODO(eladalon): In C++14, this can be done with a lambda.
3708 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003709 bool operator()() {
3710 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3711 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003712 PeerConnection* const pc;
3713 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003714 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003715 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003716 return worker_thread()->Invoke<bool>(
3717 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003718}
3719
3720void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003721 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003722 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3723}
3724
Harald Alvestrandad88c882018-11-28 16:47:46 +01003725rtc::scoped_refptr<DtlsTransportInterface>
3726PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3727 return transport_controller_->LookupDtlsTransportByMid(mid);
3728}
3729
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003730rtc::scoped_refptr<DtlsTransport>
3731PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3732 return transport_controller_->LookupDtlsTransportByMid(mid);
3733}
3734
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003735rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3736 const {
3737 return sctp_transport_;
3738}
3739
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003740const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003741 return pending_local_description_ ? pending_local_description_.get()
3742 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003743}
3744
3745const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003746 return pending_remote_description_ ? pending_remote_description_.get()
3747 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003748}
3749
deadbeeffe4a8a42016-12-20 17:56:17 -08003750const SessionDescriptionInterface* PeerConnection::current_local_description()
3751 const {
Steve Anton75737c02017-11-06 10:37:17 -08003752 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003753}
3754
3755const SessionDescriptionInterface* PeerConnection::current_remote_description()
3756 const {
Steve Anton75737c02017-11-06 10:37:17 -08003757 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003758}
3759
3760const SessionDescriptionInterface* PeerConnection::pending_local_description()
3761 const {
Steve Anton75737c02017-11-06 10:37:17 -08003762 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003763}
3764
3765const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3766 const {
Steve Anton75737c02017-11-06 10:37:17 -08003767 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003768}
3769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003770void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003771 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003772 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003773 // Update stats here so that we have the most recent stats for tracks and
3774 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003775 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003776
Steve Anton75737c02017-11-06 10:37:17 -08003777 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003778 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003779
Mirko Bonadei739baf02019-01-27 17:29:42 +01003780 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003781 transceiver->Stop();
3782 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003783
3784 // Ensure that all asynchronous stats requests are completed before destroying
3785 // the transport controller below.
3786 if (stats_collector_) {
3787 stats_collector_->WaitForPendingRequest();
3788 }
3789
3790 // Don't destroy BaseChannels until after stats has been cleaned up so that
3791 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003792 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003793
Qingsi Wang93a84392018-01-30 17:13:09 -08003794 // The event log is used in the transport controller, which must be outlived
3795 // by the former. CreateOffer by the peer connection is implemented
3796 // asynchronously and if the peer connection is closed without resetting the
3797 // WebRTC session description factory, the session description factory would
3798 // call the transport controller.
3799 webrtc_session_desc_factory_.reset();
3800 transport_controller_.reset();
3801
deadbeef42a42632017-03-10 15:18:00 -08003802 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003803 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3804 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003805
Steve Anton978b8762017-09-29 12:15:02 -07003806 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003807 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003808 call_.reset();
3809 // The event log must outlive call (and any other object that uses it).
3810 event_log_.reset();
3811 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003812 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003813 // The .h file says that observer can be discarded after close() returns.
3814 // Make sure this is true.
3815 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003816}
3817
Steve Antonad182762018-09-05 20:22:40 +00003818void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003819 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003820 switch (msg->message_id) {
3821 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3822 SetSessionDescriptionMsg* param =
3823 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3824 param->observer->OnSuccess();
3825 delete param;
3826 break;
3827 }
3828 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3829 SetSessionDescriptionMsg* param =
3830 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3831 param->observer->OnFailure(std::move(param->error));
3832 delete param;
3833 break;
3834 }
3835 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3836 CreateSessionDescriptionMsg* param =
3837 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3838 param->observer->OnFailure(std::move(param->error));
3839 delete param;
3840 break;
3841 }
3842 case MSG_GETSTATS: {
3843 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3844 StatsReports reports;
3845 stats_->GetStats(param->track, &reports);
3846 param->observer->OnComplete(reports);
3847 delete param;
3848 break;
3849 }
3850 case MSG_FREE_DATACHANNELS: {
3851 sctp_data_channels_to_free_.clear();
3852 break;
3853 }
3854 case MSG_REPORT_USAGE_PATTERN: {
3855 ReportUsagePattern();
3856 break;
3857 }
3858 default:
3859 RTC_NOTREACHED() << "Not implemented";
3860 break;
3861 }
3862}
3863
Steve Antonafb0bb72018-02-20 11:35:37 -08003864cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3865 RTC_DCHECK(!IsUnifiedPlan());
3866 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3867 GetAudioTransceiver()->internal()->channel());
3868 if (voice_channel) {
3869 return voice_channel->media_channel();
3870 } else {
3871 return nullptr;
3872 }
3873}
3874
3875cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3876 RTC_DCHECK(!IsUnifiedPlan());
3877 auto* video_channel = static_cast<cricket::VideoChannel*>(
3878 GetVideoTransceiver()->internal()->channel());
3879 if (video_channel) {
3880 return video_channel->media_channel();
3881 } else {
3882 return nullptr;
3883 }
3884}
3885
Steve Anton4171afb2017-11-20 10:20:22 -08003886void PeerConnection::CreateAudioReceiver(
3887 MediaStreamInterface* stream,
3888 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003889 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3890 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003891 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3892 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003893 auto* audio_receiver = new AudioRtpReceiver(
3894 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003895 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003896 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3897 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3898 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003899 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003900 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003901 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003902}
3903
Steve Anton4171afb2017-11-20 10:20:22 -08003904void PeerConnection::CreateVideoReceiver(
3905 MediaStreamInterface* stream,
3906 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003907 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3908 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003909 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3910 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003911 auto* video_receiver = new VideoRtpReceiver(
3912 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003913 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003914 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3915 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3916 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003917 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003918 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003919 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003920}
3921
deadbeef70ab1a12015-09-28 16:53:55 -07003922// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3923// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003924rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003925 const RtpSenderInfo& remote_sender_info) {
3926 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3927 if (!receiver) {
3928 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3929 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003930 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003931 }
Steve Anton4171afb2017-11-20 10:20:22 -08003932 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3933 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3934 } else {
3935 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3936 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003937 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003938}
3939
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003940void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3941 MediaStreamInterface* stream) {
3942 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003943 RTC_DCHECK(track);
3944 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003945 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003946 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003947 // We already have a sender for this track, so just change the stream_id
3948 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003949 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003950 return;
3951 }
3952
3953 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003954 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003955 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003956 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003957 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003958 // If the sender has already been configured in SDP, we call SetSsrc,
3959 // which will connect the sender to the underlying transport. This can
3960 // occur if a local session description that contains the ID of the sender
3961 // is set before AddStream is called. It can also occur if the local
3962 // session description is not changed and RemoveStream is called, and
3963 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003964 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003965 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003966 if (sender_info) {
3967 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003968 }
3969}
3970
3971// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3972// indefinitely, when we have unified plan SDP.
3973void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3974 MediaStreamInterface* stream) {
3975 RTC_DCHECK(!IsClosed());
3976 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003977 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003978 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3979 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003980 return;
3981 }
Steve Anton4171afb2017-11-20 10:20:22 -08003982 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003983}
3984
3985void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3986 MediaStreamInterface* stream) {
3987 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003988 RTC_DCHECK(track);
3989 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003990 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003991 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003992 // We already have a sender for this track, so just change the stream_id
3993 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003994 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003995 return;
3996 }
3997
3998 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003999 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004000 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004001 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004002 GetVideoTransceiver()->internal()->AddSender(new_sender);
4003 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004004 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004005 if (sender_info) {
4006 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004007 }
4008}
4009
4010void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4011 MediaStreamInterface* stream) {
4012 RTC_DCHECK(!IsClosed());
4013 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004014 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004015 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4016 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004017 return;
4018 }
Steve Anton4171afb2017-11-20 10:20:22 -08004019 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004020}
4021
Steve Antonba818672017-11-06 10:21:57 -08004022void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004023 if (ice_connection_state_ == new_state) {
4024 return;
4025 }
4026
deadbeefcbecd352015-09-23 11:50:27 -07004027 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004028 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004029 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004030 return;
4031 }
Steve Antonba818672017-11-06 10:21:57 -08004032
Mirko Bonadei675513b2017-11-09 11:09:25 +01004033 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4034 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004035 RTC_DCHECK(ice_connection_state_ !=
4036 PeerConnectionInterface::kIceConnectionClosed);
4037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004038 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004039 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004040}
4041
Alex Loiko9289eda2018-11-23 16:18:59 +00004042void PeerConnection::SetStandardizedIceConnectionState(
4043 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004044 if (standardized_ice_connection_state_ == new_state)
4045 return;
4046 if (IsClosed())
4047 return;
4048 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004049 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004050}
4051
Jonas Olsson635474e2018-10-18 15:58:17 +02004052void PeerConnection::SetConnectionState(
4053 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004054 if (connection_state_ == new_state)
4055 return;
4056 if (IsClosed())
4057 return;
4058 connection_state_ = new_state;
4059 Observer()->OnConnectionChange(new_state);
4060}
4061
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004062void PeerConnection::OnIceGatheringChange(
4063 PeerConnectionInterface::IceGatheringState new_state) {
4064 if (IsClosed()) {
4065 return;
4066 }
4067 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004068 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004069}
4070
jbauch81bf7b02017-03-25 08:31:12 -07004071void PeerConnection::OnIceCandidate(
4072 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004073 if (IsClosed()) {
4074 return;
4075 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004076 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004077 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4078 candidate->candidate().address().IsPrivateIP()) {
4079 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4080 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004081 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004082}
4083
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004084void PeerConnection::OnIceCandidatesRemoved(
4085 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004086 if (IsClosed()) {
4087 return;
4088 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004089 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004090}
4091
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004092void PeerConnection::ChangeSignalingState(
4093 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004094 if (signaling_state_ == signaling_state) {
4095 return;
4096 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004097 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4098 << GetSignalingStateString(signaling_state_)
4099 << " New state: "
4100 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004101 signaling_state_ = signaling_state;
4102 if (signaling_state == kClosed) {
4103 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004104 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004105 standardized_ice_connection_state_ =
4106 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004107 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4108 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004109 if (ice_gathering_state_ != kIceGatheringComplete) {
4110 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004111 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004112 }
4113 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004114 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004115}
4116
deadbeefeb459812015-12-15 19:24:43 -08004117void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4118 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004119 if (IsClosed()) {
4120 return;
4121 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004122 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004123 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004124}
4125
deadbeefeb459812015-12-15 19:24:43 -08004126void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4127 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004128 if (IsClosed()) {
4129 return;
4130 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004131 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004132 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004133}
4134
4135void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4136 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004137 if (IsClosed()) {
4138 return;
4139 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004140 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004141 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004142}
4143
4144void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4145 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004146 if (IsClosed()) {
4147 return;
4148 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004149 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004150 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004151}
4152
Henrik Boström31638672017-11-23 17:48:32 +01004153void PeerConnection::PostSetSessionDescriptionSuccess(
4154 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004155 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4156 signaling_thread()->Post(RTC_FROM_HERE, this,
4157 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004158}
4159
deadbeefab9b2d12015-10-14 11:33:11 -07004160void PeerConnection::PostSetSessionDescriptionFailure(
4161 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004162 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004163 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004164 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4165 msg->error = std::move(error);
4166 signaling_thread()->Post(RTC_FROM_HERE, this,
4167 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004168}
4169
4170void PeerConnection::PostCreateSessionDescriptionFailure(
4171 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004172 RTCError error) {
4173 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004174 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4175 msg->error = std::move(error);
4176 signaling_thread()->Post(RTC_FROM_HERE, this,
4177 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004178}
4179
zhihuang1c378ed2017-08-17 14:10:50 -07004180void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004181 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004182 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004183 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004184
Steve Antondcc3c022017-12-22 16:02:54 -08004185 if (IsUnifiedPlan()) {
4186 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4187 } else {
4188 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4189 }
4190
Steve Antonfa2260d2017-12-28 16:38:23 -08004191 // Intentionally unset the data channel type for RTP data channel with the
4192 // second condition. Otherwise the RTP data channels would be successfully
4193 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4194 // when building with chromium. We want to leave RTP data channels broken, so
4195 // people won't try to use them.
4196 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4197 session_options->data_channel_type = data_channel_type();
4198 }
4199
Steve Antondcc3c022017-12-22 16:02:54 -08004200 // Apply ICE restart flag and renomination flag.
4201 for (auto& options : session_options->media_description_options) {
4202 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4203 options.transport_options.enable_ice_renomination =
4204 configuration_.enable_ice_renomination;
4205 }
4206
4207 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004208 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004209 session_options->pooled_ice_credentials =
4210 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4211 RTC_FROM_HERE,
4212 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4213 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004214 session_options->offer_extmap_allow_mixed =
4215 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004216
4217 if (configuration_.enable_dtls_srtp &&
4218 !configuration_.enable_dtls_srtp.value()) {
4219 session_options->media_transport_settings =
4220 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4221 }
Steve Antondcc3c022017-12-22 16:02:54 -08004222}
4223
4224void PeerConnection::GetOptionsForPlanBOffer(
4225 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4226 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004227 // Figure out transceiver directional preferences.
4228 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4229 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4230
4231 // By default, generate sendrecv/recvonly m= sections.
4232 bool recv_audio = true;
4233 bool recv_video = true;
4234
4235 // By default, only offer a new m= section if we have media to send with it.
4236 bool offer_new_audio_description = send_audio;
4237 bool offer_new_video_description = send_video;
4238 bool offer_new_data_description = HasDataChannels();
4239
4240 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004241 if (offer_answer_options.offer_to_receive_audio !=
4242 RTCOfferAnswerOptions::kUndefined) {
4243 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004244 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004245 offer_new_audio_description ||
4246 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004247 }
Steve Antondcc3c022017-12-22 16:02:54 -08004248 if (offer_answer_options.offer_to_receive_video !=
4249 RTCOfferAnswerOptions::kUndefined) {
4250 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004251 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004252 offer_new_video_description ||
4253 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004254 }
4255
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004256 absl::optional<size_t> audio_index;
4257 absl::optional<size_t> video_index;
4258 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004259 // If a current description exists, generate m= sections in the same order,
4260 // using the first audio/video/data section that appears and rejecting
4261 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004262 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004263 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004264 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004265 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4266 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4267 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004268 }
4269
zhihuang1c378ed2017-08-17 14:10:50 -07004270 // Add audio/video/data m= sections to the end if needed.
4271 if (!audio_index && offer_new_audio_description) {
4272 session_options->media_description_options.push_back(
4273 cricket::MediaDescriptionOptions(
4274 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004275 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4276 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004277 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004278 }
zhihuang1c378ed2017-08-17 14:10:50 -07004279 if (!video_index && offer_new_video_description) {
4280 session_options->media_description_options.push_back(
4281 cricket::MediaDescriptionOptions(
4282 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004283 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4284 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004285 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004286 }
zhihuang1c378ed2017-08-17 14:10:50 -07004287 if (!data_index && offer_new_data_description) {
4288 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004289 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004290 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004291 }
4292
4293 cricket::MediaDescriptionOptions* audio_media_description_options =
4294 !audio_index ? nullptr
4295 : &session_options->media_description_options[*audio_index];
4296 cricket::MediaDescriptionOptions* video_media_description_options =
4297 !video_index ? nullptr
4298 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004299
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004300 AddPlanBRtpSenderOptions(GetSendersInternal(),
4301 audio_media_description_options,
4302 video_media_description_options,
4303 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004304}
4305
Steve Antondcc3c022017-12-22 16:02:54 -08004306static cricket::MediaDescriptionOptions
4307GetMediaDescriptionOptionsForTransceiver(
4308 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4309 transceiver,
4310 const std::string& mid) {
4311 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004312 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004313 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004314 // This behavior is specified in JSEP. The gist is that:
4315 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4316 // sendrecv.
4317 // 2. If the MSID is included, then it must be included in any subsequent
4318 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004319 if (transceiver->stopped() ||
4320 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4321 !transceiver->internal()->has_ever_been_used_to_send())) {
4322 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004323 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004324
4325 cricket::SenderOptions sender_options;
4326 sender_options.track_id = transceiver->sender()->id();
4327 sender_options.stream_ids = transceiver->sender()->stream_ids();
4328
4329 // The following sets up RIDs and Simulcast.
4330 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004331 RtpParameters send_parameters =
4332 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004333 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4334 send_parameters.encodings.end(),
4335 [](const RtpEncodingParameters& encoding) {
4336 return !encoding.rid.empty();
4337 });
4338
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004339 std::vector<RidDescription> send_rids;
4340 SimulcastLayerList send_layers;
4341 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4342 if (encoding.rid.empty()) {
4343 continue;
4344 }
4345 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4346 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4347 }
4348
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004349 if (has_rids) {
4350 sender_options.rids = send_rids;
4351 }
4352
4353 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004354 // When RIDs are configured, we must set num_sim_layers to 0 to.
4355 // Otherwise, num_sim_layers must be 1 because either there is no
4356 // simulcast, or simulcast is acheived by munging the SDP.
4357 sender_options.num_sim_layers = has_rids ? 0 : 1;
4358 media_description_options.sender_options.push_back(sender_options);
4359
Steve Antondcc3c022017-12-22 16:02:54 -08004360 return media_description_options;
4361}
4362
Steve Anton5c72e712018-12-10 14:25:30 -08004363// Returns the ContentInfo at mline index |i|, or null if none exists.
4364static const ContentInfo* GetContentByIndex(
4365 const SessionDescriptionInterface* sdesc,
4366 size_t i) {
4367 if (!sdesc) {
4368 return nullptr;
4369 }
4370 const ContentInfos& contents = sdesc->description()->contents();
4371 return (i < contents.size() ? &contents[i] : nullptr);
4372}
4373
Steve Antondcc3c022017-12-22 16:02:54 -08004374void PeerConnection::GetOptionsForUnifiedPlanOffer(
4375 const RTCOfferAnswerOptions& offer_answer_options,
4376 cricket::MediaSessionOptions* session_options) {
4377 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4378 // Offers) and 5.2.2 (Subsequent Offers).
4379 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4380 const ContentInfos& local_contents =
4381 (local_description() ? local_description()->description()->contents()
4382 : ContentInfos());
4383 const ContentInfos& remote_contents =
4384 (remote_description() ? remote_description()->description()->contents()
4385 : ContentInfos());
4386 // The mline indices that can be recycled. New transceivers should reuse these
4387 // slots first.
4388 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004389 // First, go through each media section that exists in either the local or
4390 // remote description and generate a media section in this offer for the
4391 // associated transceiver. If a media section can be recycled, generate a
4392 // default, rejected media section here that can be later overwritten.
4393 for (size_t i = 0;
4394 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4395 // Either |local_content| or |remote_content| is non-null.
4396 const ContentInfo* local_content =
4397 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004398 const ContentInfo* current_local_content =
4399 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004400 const ContentInfo* remote_content =
4401 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004402 const ContentInfo* current_remote_content =
4403 GetContentByIndex(current_remote_description(), i);
4404 bool had_been_rejected =
4405 (current_local_content && current_local_content->rejected) ||
4406 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004407 const std::string& mid =
4408 (local_content ? local_content->name : remote_content->name);
4409 cricket::MediaType media_type =
4410 (local_content ? local_content->media_description()->type()
4411 : remote_content->media_description()->type());
4412 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4413 media_type == cricket::MEDIA_TYPE_VIDEO) {
4414 auto transceiver = GetAssociatedTransceiver(mid);
4415 RTC_CHECK(transceiver);
4416 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004417 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004418 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004419 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004420 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4421 RtpTransceiverDirection::kInactive,
4422 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004423 recycleable_mline_indices.push(i);
4424 } else {
4425 session_options->media_description_options.push_back(
4426 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4427 // CreateOffer shouldn't really cause any state changes in
4428 // PeerConnection, but we need a way to match new transceivers to new
4429 // media sections in SetLocalDescription and JSEP specifies this is done
4430 // by recording the index of the media section generated for the
4431 // transceiver in the offer.
4432 transceiver->internal()->set_mline_index(i);
4433 }
4434 } else {
4435 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004436 RTC_CHECK(GetDataMid());
4437 if (had_been_rejected || mid != *GetDataMid()) {
4438 session_options->media_description_options.push_back(
4439 GetMediaDescriptionOptionsForRejectedData(mid));
4440 } else {
4441 session_options->media_description_options.push_back(
4442 GetMediaDescriptionOptionsForActiveData(mid));
4443 }
Steve Antondcc3c022017-12-22 16:02:54 -08004444 }
4445 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004446
Steve Antondcc3c022017-12-22 16:02:54 -08004447 // Next, look for transceivers that are newly added (that is, are not stopped
4448 // and not associated). Reuse media sections marked as recyclable first,
4449 // otherwise append to the end of the offer. New media sections should be
4450 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004451 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004452 if (transceiver->mid() || transceiver->stopped()) {
4453 continue;
4454 }
4455 size_t mline_index;
4456 if (!recycleable_mline_indices.empty()) {
4457 mline_index = recycleable_mline_indices.front();
4458 recycleable_mline_indices.pop();
4459 session_options->media_description_options[mline_index] =
4460 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004461 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004462 } else {
4463 mline_index = session_options->media_description_options.size();
4464 session_options->media_description_options.push_back(
4465 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004466 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004467 }
4468 // See comment above for why CreateOffer changes the transceiver's state.
4469 transceiver->internal()->set_mline_index(mline_index);
4470 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004471 // Lastly, add a m-section if we have local data channels and an m section
4472 // does not already exist.
4473 if (!GetDataMid() && HasDataChannels()) {
4474 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004475 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004476 }
Steve Antondcc3c022017-12-22 16:02:54 -08004477}
4478
4479void PeerConnection::GetOptionsForAnswer(
4480 const RTCOfferAnswerOptions& offer_answer_options,
4481 cricket::MediaSessionOptions* session_options) {
4482 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4483
4484 if (IsUnifiedPlan()) {
4485 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4486 } else {
4487 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4488 }
4489
Steve Antonfa2260d2017-12-28 16:38:23 -08004490 // Intentionally unset the data channel type for RTP data channel. Otherwise
4491 // the RTP data channels would be successfully negotiated by default and the
4492 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4493 // We want to leave RTP data channels broken, so people won't try to use them.
4494 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4495 session_options->data_channel_type = data_channel_type();
4496 }
4497
Steve Antondcc3c022017-12-22 16:02:54 -08004498 // Apply ICE renomination flag.
4499 for (auto& options : session_options->media_description_options) {
4500 options.transport_options.enable_ice_renomination =
4501 configuration_.enable_ice_renomination;
4502 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004503
4504 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004505 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004506 session_options->pooled_ice_credentials =
4507 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4508 RTC_FROM_HERE,
4509 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4510 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004511}
4512
Steve Antondcc3c022017-12-22 16:02:54 -08004513void PeerConnection::GetOptionsForPlanBAnswer(
4514 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004515 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004516 // Figure out transceiver directional preferences.
4517 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4518 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4519
4520 // By default, generate sendrecv/recvonly m= sections. The direction is also
4521 // restricted by the direction in the offer.
4522 bool recv_audio = true;
4523 bool recv_video = true;
4524
4525 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004526 if (offer_answer_options.offer_to_receive_audio !=
4527 RTCOfferAnswerOptions::kUndefined) {
4528 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004529 }
Steve Antondcc3c022017-12-22 16:02:54 -08004530 if (offer_answer_options.offer_to_receive_video !=
4531 RTCOfferAnswerOptions::kUndefined) {
4532 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004533 }
4534
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004535 absl::optional<size_t> audio_index;
4536 absl::optional<size_t> video_index;
4537 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004538
4539 // Generate m= sections that match those in the offer.
4540 // Note that mediasession.cc will handle intersection our preferred
4541 // direction with the offered direction.
4542 GenerateMediaDescriptionOptions(
4543 remote_description(),
4544 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4545 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4546 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004547
4548 cricket::MediaDescriptionOptions* audio_media_description_options =
4549 !audio_index ? nullptr
4550 : &session_options->media_description_options[*audio_index];
4551 cricket::MediaDescriptionOptions* video_media_description_options =
4552 !video_index ? nullptr
4553 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004554
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004555 AddPlanBRtpSenderOptions(GetSendersInternal(),
4556 audio_media_description_options,
4557 video_media_description_options,
4558 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004559}
zhihuangaf388472016-11-02 16:49:48 -07004560
Steve Antondcc3c022017-12-22 16:02:54 -08004561void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4562 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4563 cricket::MediaSessionOptions* session_options) {
4564 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4565 // Answers) and 5.3.2 (Subsequent Answers).
4566 RTC_DCHECK(remote_description());
4567 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4568 for (const ContentInfo& content :
4569 remote_description()->description()->contents()) {
4570 cricket::MediaType media_type = content.media_description()->type();
4571 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4572 media_type == cricket::MEDIA_TYPE_VIDEO) {
4573 auto transceiver = GetAssociatedTransceiver(content.name);
4574 RTC_CHECK(transceiver);
4575 session_options->media_description_options.push_back(
4576 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4577 } else {
4578 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004579 // Reject all data sections if data channels are disabled.
4580 // Reject a data section if it has already been rejected.
4581 // Reject all data sections except for the first one.
4582 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4583 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004584 session_options->media_description_options.push_back(
4585 GetMediaDescriptionOptionsForRejectedData(content.name));
4586 } else {
4587 session_options->media_description_options.push_back(
4588 GetMediaDescriptionOptionsForActiveData(content.name));
4589 }
Steve Antondcc3c022017-12-22 16:02:54 -08004590 }
4591 }
htaa2a49d92016-03-04 02:51:39 -08004592}
4593
zhihuang1c378ed2017-08-17 14:10:50 -07004594void PeerConnection::GenerateMediaDescriptionOptions(
4595 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004596 RtpTransceiverDirection audio_direction,
4597 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004598 absl::optional<size_t>* audio_index,
4599 absl::optional<size_t>* video_index,
4600 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004601 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004602 for (const cricket::ContentInfo& content :
4603 session_desc->description()->contents()) {
4604 if (IsAudioContent(&content)) {
4605 // If we already have an audio m= section, reject this extra one.
4606 if (*audio_index) {
4607 session_options->media_description_options.push_back(
4608 cricket::MediaDescriptionOptions(
4609 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004610 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004611 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004612 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004613 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004614 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4615 content.name, audio_direction,
4616 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004617 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004618 }
4619 } else if (IsVideoContent(&content)) {
4620 // If we already have an video m= section, reject this extra one.
4621 if (*video_index) {
4622 session_options->media_description_options.push_back(
4623 cricket::MediaDescriptionOptions(
4624 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004625 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004626 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004627 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004628 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004629 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4630 content.name, video_direction,
4631 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004632 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004633 }
4634 } else {
4635 RTC_DCHECK(IsDataContent(&content));
4636 // If we already have an data m= section, reject this extra one.
4637 if (*data_index) {
4638 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004639 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004640 } else {
4641 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004642 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004643 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004644 }
4645 }
htaa2a49d92016-03-04 02:51:39 -08004646 }
deadbeefab9b2d12015-10-14 11:33:11 -07004647}
4648
Steve Antonfa2260d2017-12-28 16:38:23 -08004649cricket::MediaDescriptionOptions
4650PeerConnection::GetMediaDescriptionOptionsForActiveData(
4651 const std::string& mid) const {
4652 // Direction for data sections is meaningless, but legacy endpoints might
4653 // expect sendrecv.
4654 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4655 RtpTransceiverDirection::kSendRecv,
4656 /*stopped=*/false);
4657 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4658 return options;
4659}
4660
4661cricket::MediaDescriptionOptions
4662PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4663 const std::string& mid) const {
4664 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4665 RtpTransceiverDirection::kInactive,
4666 /*stopped=*/true);
4667 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4668 return options;
4669}
4670
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004671absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004672 switch (data_channel_type_) {
4673 case cricket::DCT_RTP:
4674 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004675 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004676 }
4677 return rtp_data_channel_->content_name();
4678 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004679 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004680 case cricket::DCT_MEDIA_TRANSPORT:
4681 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004682 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004683 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004684 }
4685}
4686
Steve Anton4171afb2017-11-20 10:20:22 -08004687void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4688 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4689 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004690 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004691}
4692
Steve Anton4171afb2017-11-20 10:20:22 -08004693void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004694 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004695 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004696 cricket::MediaType media_type,
4697 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004698 RTC_DCHECK(!IsUnifiedPlan());
4699
Steve Anton4171afb2017-11-20 10:20:22 -08004700 std::vector<RtpSenderInfo>* current_senders =
4701 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004702
Steve Anton4171afb2017-11-20 10:20:22 -08004703 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004704 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004705 for (auto sender_it = current_senders->begin();
4706 sender_it != current_senders->end();
4707 /* incremented manually */) {
4708 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004709 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004710 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004711 std::string params_stream_id;
4712 if (params) {
4713 params_stream_id =
4714 (!params->first_stream_id().empty() ? params->first_stream_id()
4715 : kDefaultStreamId);
4716 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004717 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004718 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004719 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004720 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004721 sender_exists) {
4722 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004723 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004724 OnRemoteSenderRemoved(info, media_type);
4725 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004726 }
4727 }
4728
Steve Anton4171afb2017-11-20 10:20:22 -08004729 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004730 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004731 if (!params.has_ssrcs()) {
4732 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4733 // sender, this means it is coming from a Unified Plan endpoint,so we just
4734 // create a default.
4735 default_sender_needed = true;
4736 break;
4737 }
4738
Seth Hampson845e8782018-03-02 11:34:10 -08004739 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004740 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004741 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4742 // not supported in Plan B, we just take the first here and create the
4743 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004744 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004745 (!params.first_stream_id().empty() ? params.first_stream_id()
4746 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004747 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004748 uint32_t ssrc = params.first_ssrc();
4749
4750 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004751 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004752 if (!stream) {
4753 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004754 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004755 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004756 remote_streams_->AddStream(stream);
4757 new_streams->AddStream(stream);
4758 }
4759
Steve Anton4171afb2017-11-20 10:20:22 -08004760 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004761 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004762 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004763 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004764 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004765 }
4766 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004767
Steve Anton4171afb2017-11-20 10:20:22 -08004768 // Add default sender if necessary.
4769 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004770 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004771 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004772 if (!default_stream) {
4773 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004774 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004775 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004776 remote_streams_->AddStream(default_stream);
4777 new_streams->AddStream(default_stream);
4778 }
Steve Anton4171afb2017-11-20 10:20:22 -08004779 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4780 ? kDefaultAudioSenderId
4781 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004782 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004783 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004784 if (!default_sender_info) {
4785 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004786 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004787 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004788 }
4789 }
deadbeefab9b2d12015-10-14 11:33:11 -07004790}
4791
Steve Anton4171afb2017-11-20 10:20:22 -08004792void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4793 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004794 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4795 << " receiver for track_id=" << sender_info.sender_id
4796 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004797
Steve Anton3d954a62018-04-02 11:27:23 -07004798 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004799 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004800 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004801 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004802 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004803 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004804 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004805 }
4806}
4807
Steve Anton4171afb2017-11-20 10:20:22 -08004808void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4809 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004810 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4811 << " receiver for track_id=" << sender_info.sender_id
4812 << " and stream_id=" << sender_info.stream_id;
4813
Seth Hampson845e8782018-03-02 11:34:10 -08004814 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004815
Henrik Boström933d8b02017-10-10 10:05:16 -07004816 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004817 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004818 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4819 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004820 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004821 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004822 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004823 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004824 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004825 }
4826 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004827 // Stopping or destroying a VideoRtpReceiver will end the
4828 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004829 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004830 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004831 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004832 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004833 // There's no guarantee the track is still available, e.g. the track may
4834 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004835 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004836 }
4837 } else {
nisseede5da42017-01-12 05:15:36 -08004838 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004839 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004840 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004841 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004842 }
deadbeefab9b2d12015-10-14 11:33:11 -07004843}
4844
4845void PeerConnection::UpdateEndedRemoteMediaStreams() {
4846 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4847 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4848 MediaStreamInterface* stream = remote_streams_->at(i);
4849 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4850 streams_to_remove.push_back(stream);
4851 }
4852 }
4853
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004854 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004855 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004856 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004857 }
4858}
4859
Steve Anton4171afb2017-11-20 10:20:22 -08004860void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004861 const std::vector<cricket::StreamParams>& streams,
4862 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004863 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004864
Seth Hampson845e8782018-03-02 11:34:10 -08004865 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004866 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004867 for (auto sender_it = current_senders->begin();
4868 sender_it != current_senders->end();
4869 /* incremented manually */) {
4870 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004871 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004872 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4873 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004874 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004875 OnLocalSenderRemoved(info, media_type);
4876 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004877 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004878 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004879 }
4880 }
4881
Steve Anton4171afb2017-11-20 10:20:22 -08004882 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004883 for (const cricket::StreamParams& params : streams) {
4884 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004885 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004886 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004887 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004888 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004889 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004890 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004891 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004892 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004893 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004894 }
4895 }
4896}
4897
Steve Anton4171afb2017-11-20 10:20:22 -08004898void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4899 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004900 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004901 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004902 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004903 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4904 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004905 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004906 return;
4907 }
4908
deadbeeffac06552015-11-25 11:26:01 -08004909 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004910 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004911 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004912 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004913 }
deadbeeffac06552015-11-25 11:26:01 -08004914
Seth Hampson5b4f0752018-04-02 16:31:36 -07004915 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004916 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004917}
4918
Steve Anton4171afb2017-11-20 10:20:22 -08004919void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4920 cricket::MediaType media_type) {
4921 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004922 if (!sender) {
4923 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004924 // SessionDescriptions has been renegotiated.
4925 return;
4926 }
deadbeeffac06552015-11-25 11:26:01 -08004927
4928 // A sender has been removed from the SessionDescription but it's still
4929 // associated with the PeerConnection. This only occurs if the SDP doesn't
4930 // match with the calls to CreateSender, AddStream and RemoveStream.
4931 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004932 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004933 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004934 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004935 }
deadbeeffac06552015-11-25 11:26:01 -08004936
Steve Anton4171afb2017-11-20 10:20:22 -08004937 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004938}
4939
4940void PeerConnection::UpdateLocalRtpDataChannels(
4941 const cricket::StreamParamsVec& streams) {
4942 std::vector<std::string> existing_channels;
4943
4944 // Find new and active data channels.
4945 for (const cricket::StreamParams& params : streams) {
4946 // |it->sync_label| is actually the data channel label. The reason is that
4947 // we use the same naming of data channels as we do for
4948 // MediaStreams and Tracks.
4949 // For MediaStreams, the sync_label is the MediaStream label and the
4950 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004951 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004952 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004953 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004954 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004955 continue;
4956 }
4957 // Set the SSRC the data channel should use for sending.
4958 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4959 existing_channels.push_back(data_channel_it->first);
4960 }
4961
4962 UpdateClosingRtpDataChannels(existing_channels, true);
4963}
4964
4965void PeerConnection::UpdateRemoteRtpDataChannels(
4966 const cricket::StreamParamsVec& streams) {
4967 std::vector<std::string> existing_channels;
4968
4969 // Find new and active data channels.
4970 for (const cricket::StreamParams& params : streams) {
4971 // The data channel label is either the mslabel or the SSRC if the mslabel
4972 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004973 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004974 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004975 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004976 auto data_channel_it = rtp_data_channels_.find(label);
4977 if (data_channel_it == rtp_data_channels_.end()) {
4978 // This is a new data channel.
4979 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4980 } else {
4981 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4982 }
4983 existing_channels.push_back(label);
4984 }
4985
4986 UpdateClosingRtpDataChannels(existing_channels, false);
4987}
4988
4989void PeerConnection::UpdateClosingRtpDataChannels(
4990 const std::vector<std::string>& active_channels,
4991 bool is_local_update) {
4992 auto it = rtp_data_channels_.begin();
4993 while (it != rtp_data_channels_.end()) {
4994 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004995 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004996 ++it;
4997 continue;
4998 }
4999
5000 if (is_local_update) {
5001 data_channel->SetSendSsrc(0);
5002 } else {
5003 data_channel->RemotePeerRequestClose();
5004 }
5005
5006 if (data_channel->state() == DataChannel::kClosed) {
5007 rtp_data_channels_.erase(it);
5008 it = rtp_data_channels_.begin();
5009 } else {
5010 ++it;
5011 }
5012 }
5013}
5014
5015void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5016 uint32_t remote_ssrc) {
5017 rtc::scoped_refptr<DataChannel> channel(
5018 InternalCreateDataChannel(label, nullptr));
5019 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005020 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005021 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005022 return;
5023 }
5024 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005025 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5026 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005027 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005028}
5029
5030rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5031 const std::string& label,
5032 const InternalDataChannelInit* config) {
5033 if (IsClosed()) {
5034 return nullptr;
5035 }
Steve Anton75737c02017-11-06 10:37:17 -08005036 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005037 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005038 << "InternalCreateDataChannel: Data is not supported in this call.";
5039 return nullptr;
5040 }
5041 InternalDataChannelInit new_config =
5042 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005043 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005044 if (new_config.id < 0) {
5045 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005046 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005047 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005048 RTC_LOG(LS_ERROR)
5049 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005050 return nullptr;
5051 }
5052 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005053 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005054 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005055 return nullptr;
5056 }
5057 }
5058
Steve Anton75737c02017-11-06 10:37:17 -08005059 rtc::scoped_refptr<DataChannel> channel(
5060 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005061 if (!channel) {
5062 sid_allocator_.ReleaseSid(new_config.id);
5063 return nullptr;
5064 }
5065
5066 if (channel->data_channel_type() == cricket::DCT_RTP) {
5067 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005068 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5069 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005070 return nullptr;
5071 }
5072 rtp_data_channels_[channel->label()] = channel;
5073 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005074 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005075 sctp_data_channels_.push_back(channel);
5076 channel->SignalClosed.connect(this,
5077 &PeerConnection::OnSctpDataChannelClosed);
5078 }
5079
Steve Anton2d8609c2018-01-23 16:38:46 -08005080 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005081 return channel;
5082}
5083
5084bool PeerConnection::HasDataChannels() const {
5085 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5086}
5087
5088void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
5089 for (const auto& channel : sctp_data_channels_) {
5090 if (channel->id() < 0) {
5091 int sid;
5092 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005093 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07005094 continue;
5095 }
5096 channel->SetSctpSid(sid);
5097 }
5098 }
5099}
5100
5101void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005102 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005103 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5104 ++it) {
5105 if (it->get() == channel) {
5106 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005107 // After the closing procedure is done, it's safe to use this ID for
5108 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005109 sid_allocator_.ReleaseSid(channel->id());
5110 }
deadbeefbd292462015-12-14 18:15:29 -08005111 // Since this method is triggered by a signal from the DataChannel,
5112 // we can't free it directly here; we need to free it asynchronously.
5113 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005114 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005115 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5116 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005117 return;
5118 }
5119 }
5120}
5121
deadbeefab9b2d12015-10-14 11:33:11 -07005122void PeerConnection::OnDataChannelDestroyed() {
5123 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5124 // DataChannel may callback to us and try to modify the list.
5125 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5126 temp_rtp_dcs.swap(rtp_data_channels_);
5127 for (const auto& kv : temp_rtp_dcs) {
5128 kv.second->OnTransportChannelDestroyed();
5129 }
5130
5131 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5132 temp_sctp_dcs.swap(sctp_data_channels_);
5133 for (const auto& channel : temp_sctp_dcs) {
5134 channel->OnTransportChannelDestroyed();
5135 }
5136}
5137
5138void PeerConnection::OnDataChannelOpenMessage(
5139 const std::string& label,
5140 const InternalDataChannelInit& config) {
5141 rtc::scoped_refptr<DataChannel> channel(
5142 InternalCreateDataChannel(label, &config));
5143 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005144 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005145 return;
5146 }
5147
deadbeefa601f5c2016-06-06 14:27:39 -07005148 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5149 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005150 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005151 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005152}
5153
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005154bool PeerConnection::HandleOpenMessage_s(
5155 const cricket::ReceiveDataParams& params,
5156 const rtc::CopyOnWriteBuffer& buffer) {
5157 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5158 // Received OPEN message; parse and signal that a new data channel should
5159 // be created.
5160 std::string label;
5161 InternalDataChannelInit config;
5162 config.id = params.ssrc;
5163 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5164 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5165 << params.ssrc;
5166 return true;
5167 }
5168 config.open_handshake_role = InternalDataChannelInit::kAcker;
5169 OnDataChannelOpenMessage(label, config);
5170 return true;
5171 }
5172 return false;
5173}
5174
Steve Anton4171afb2017-11-20 10:20:22 -08005175rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5176PeerConnection::GetAudioTransceiver() const {
5177 // This method only works with Plan B SDP, where there is a single
5178 // audio/video transceiver.
5179 RTC_DCHECK(!IsUnifiedPlan());
5180 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005181 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005182 return transceiver;
5183 }
5184 }
5185 RTC_NOTREACHED();
5186 return nullptr;
5187}
5188
5189rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5190PeerConnection::GetVideoTransceiver() const {
5191 // This method only works with Plan B SDP, where there is a single
5192 // audio/video transceiver.
5193 RTC_DCHECK(!IsUnifiedPlan());
5194 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005195 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005196 return transceiver;
5197 }
5198 }
5199 RTC_NOTREACHED();
5200 return nullptr;
5201}
5202
5203// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5204// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005205bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005206 switch (type) {
5207 case cricket::MEDIA_TYPE_AUDIO:
5208 return !GetAudioTransceiver()->internal()->senders().empty();
5209 case cricket::MEDIA_TYPE_VIDEO:
5210 return !GetVideoTransceiver()->internal()->senders().empty();
5211 case cricket::MEDIA_TYPE_DATA:
5212 return false;
5213 }
5214 RTC_NOTREACHED();
5215 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005216}
5217
Steve Anton4171afb2017-11-20 10:20:22 -08005218rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5219PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005220 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005221 for (auto sender : transceiver->internal()->senders()) {
5222 if (sender->track() == track) {
5223 return sender;
5224 }
5225 }
5226 }
5227 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005228}
5229
Steve Anton4171afb2017-11-20 10:20:22 -08005230rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5231PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005232 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005233 for (auto sender : transceiver->internal()->senders()) {
5234 if (sender->id() == sender_id) {
5235 return sender;
5236 }
5237 }
5238 }
5239 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005240}
5241
Steve Anton4171afb2017-11-20 10:20:22 -08005242rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5243PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005244 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005245 for (auto receiver : transceiver->internal()->receivers()) {
5246 if (receiver->id() == receiver_id) {
5247 return receiver;
5248 }
5249 }
5250 }
5251 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005252}
5253
Steve Anton4171afb2017-11-20 10:20:22 -08005254std::vector<PeerConnection::RtpSenderInfo>*
5255PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5256 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5257 media_type == cricket::MEDIA_TYPE_VIDEO);
5258 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5259 ? &remote_audio_sender_infos_
5260 : &remote_video_sender_infos_;
5261}
5262
5263std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005264 cricket::MediaType media_type) {
5265 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5266 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005267 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5268 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005269}
5270
Steve Anton4171afb2017-11-20 10:20:22 -08005271const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5272 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005273 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005274 const std::string sender_id) const {
5275 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005276 if (sender_info.stream_id == stream_id &&
5277 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005278 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005279 }
5280 }
5281 return nullptr;
5282}
5283
5284DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5285 for (const auto& channel : sctp_data_channels_) {
5286 if (channel->id() == sid) {
5287 return channel;
5288 }
5289 }
5290 return nullptr;
5291}
5292
deadbeef91dd5672016-05-18 16:55:30 -07005293bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005294 const cricket::ServerAddresses& stun_servers,
5295 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005296 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005297 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005298 // To handle both internal and externally created port allocator, we will
5299 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005300 port_allocator_flags_ = port_allocator_->flags();
5301 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5302 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5303 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005304 // If the disable-IPv6 flag was specified, we'll not override it
5305 // by experiment.
5306 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005307 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005308 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5309 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005310 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005311 }
5312
zhihuangb09b3f92017-03-07 14:40:51 -08005313 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005314 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005315 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005316 }
5317
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005318 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005319 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005320 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005321 }
5322
honghaiz60347052016-05-31 18:29:12 -07005323 if (configuration.candidate_network_policy ==
5324 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005325 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005326 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005327 }
5328
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005329 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005330 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005331 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5332 }
5333
Qingsi Wanga2d60672018-04-11 16:57:45 -07005334 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005335 // No step delay is used while allocating ports.
5336 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5337 port_allocator_->set_candidate_filter(
5338 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005339 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005340
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005341 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005342 for (auto& turn_server : turn_servers_copy) {
5343 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005344 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005345 // Call this last since it may create pooled allocator sessions using the
5346 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005347 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005348 stun_servers, std::move(turn_servers_copy),
5349 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5350 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005351 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005352 return true;
5353}
5354
deadbeef91dd5672016-05-18 16:55:30 -07005355bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005356 const cricket::ServerAddresses& stun_servers,
5357 const std::vector<cricket::RelayServerConfig>& turn_servers,
5358 IceTransportsType type,
5359 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005360 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005361 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005362 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005363 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005364 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005365 // According to JSEP, after setLocalDescription, changing the candidate pool
5366 // size is not allowed, and changing the set of ICE servers will not result
5367 // in new candidates being gathered.
5368 if (local_description()) {
5369 port_allocator_->FreezeCandidatePool();
5370 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005371 // Add the custom tls turn servers if they exist.
5372 auto turn_servers_copy = turn_servers;
5373 for (auto& turn_server : turn_servers_copy) {
5374 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5375 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005376 // Call this last since it may create pooled allocator sessions using the
5377 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005378 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005379 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5380 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005381}
5382
Steve Antonba818672017-11-06 10:21:57 -08005383cricket::ChannelManager* PeerConnection::channel_manager() const {
5384 return factory_->channel_manager();
5385}
5386
Elad Alon99c3fe52017-10-13 16:29:40 +02005387bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005388 std::unique_ptr<RtcEventLogOutput> output,
5389 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005390 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005391 if (!event_log_) {
5392 return false;
5393 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005394 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005395}
5396
5397void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005398 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005399 if (event_log_) {
5400 event_log_->StopLogging();
5401 }
ivoc14d5dbe2016-07-04 07:06:55 -07005402}
nisseeaabdf62017-05-05 02:23:02 -07005403
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005404cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005405 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005406 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005407 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005408 if (channel && channel->content_name() == content_name) {
5409 return channel;
5410 }
Steve Anton75737c02017-11-06 10:37:17 -08005411 }
5412 if (rtp_data_channel() &&
5413 rtp_data_channel()->content_name() == content_name) {
5414 return rtp_data_channel();
5415 }
5416 return nullptr;
5417}
5418
5419bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005420 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005421 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005422 RTC_LOG(LS_INFO)
5423 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005424 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005425 return false;
5426 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005427 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005428 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005429 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005430 return false;
5431 }
5432
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005433 absl::optional<rtc::SSLRole> dtls_role;
5434 if (sctp_mid_) {
5435 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5436 } else if (is_caller_) {
5437 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5438 }
Zhi Huange830e682018-03-30 10:48:35 -07005439 if (dtls_role) {
5440 *role = *dtls_role;
5441 return true;
5442 }
5443 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005444}
5445
5446bool PeerConnection::GetSslRole(const std::string& content_name,
5447 rtc::SSLRole* role) {
5448 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005449 RTC_LOG(LS_INFO)
5450 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005451 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005452 return false;
5453 }
5454
Zhi Huange830e682018-03-30 10:48:35 -07005455 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5456 if (dtls_role) {
5457 *role = *dtls_role;
5458 return true;
5459 }
5460 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005461}
5462
Steve Antonf8470812017-12-04 10:46:21 -08005463void PeerConnection::SetSessionError(SessionError error,
5464 const std::string& error_desc) {
5465 RTC_DCHECK_RUN_ON(signaling_thread());
5466 if (error != session_error_) {
5467 session_error_ = error;
5468 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005469 }
5470}
5471
Zhi Huange830e682018-03-30 10:48:35 -07005472RTCError PeerConnection::UpdateSessionState(
5473 SdpType type,
5474 cricket::ContentSource source,
5475 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005476 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005477
5478 // If there's already a pending error then no state transition should happen.
5479 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005480 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005481
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005482 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005483 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005484 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005485 }
5486
5487 // Update the signaling state according to the specified state machine (see
5488 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005489 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005490 ChangeSignalingState(source == cricket::CS_LOCAL
5491 ? PeerConnectionInterface::kHaveLocalOffer
5492 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005493 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005494 ChangeSignalingState(source == cricket::CS_LOCAL
5495 ? PeerConnectionInterface::kHaveLocalPrAnswer
5496 : PeerConnectionInterface::kHaveRemotePrAnswer);
5497 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005498 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005499 ChangeSignalingState(PeerConnectionInterface::kStable);
5500 }
5501
5502 // Update internal objects according to the session description's media
5503 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005504 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005505 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005506 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005507 }
5508
Steve Anton8a006912017-12-04 15:25:56 -08005509 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005510}
5511
Steve Anton8a006912017-12-04 15:25:56 -08005512RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005513 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005514 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005515 const SessionDescriptionInterface* sdesc =
5516 (source == cricket::CS_LOCAL ? local_description()
5517 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005518 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005519
5520 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005521 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005522 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005523 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005524 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005525 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005526 continue;
5527 }
5528 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005529 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005530 if (!content_desc) {
5531 continue;
5532 }
5533 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005534 bool success = (source == cricket::CS_LOCAL)
5535 ? channel->SetLocalContent(content_desc, type, &error)
5536 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005537 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005538 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005539 }
5540 }
5541
5542 // If using the RtpDataChannel, push down the new SDP section for it too.
5543 if (rtp_data_channel_) {
5544 const ContentInfo* data_content =
5545 cricket::GetFirstDataContent(sdesc->description());
5546 if (data_content && !data_content->rejected) {
5547 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005548 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005549 if (data_desc) {
5550 std::string error;
5551 bool success =
5552 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005553 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005554 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005555 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005556 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005557 }
Steve Anton75737c02017-11-06 10:37:17 -08005558 }
5559 }
5560 }
Steve Antoned10bd92017-12-05 10:52:59 -08005561
Steve Anton75737c02017-11-06 10:37:17 -08005562 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5563 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5564 if (sctp_transport_ && local_description() && remote_description() &&
5565 cricket::GetFirstDataContent(local_description()->description()) &&
5566 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005567 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005568 RTC_FROM_HERE,
5569 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005570 if (!success) {
5571 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5572 "Failed to push down SCTP parameters.");
5573 }
Steve Anton75737c02017-11-06 10:37:17 -08005574 }
Steve Antoned10bd92017-12-05 10:52:59 -08005575
Steve Anton8a006912017-12-04 15:25:56 -08005576 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005577}
5578
5579bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5580 RTC_DCHECK(network_thread()->IsCurrent());
5581 RTC_DCHECK(local_description());
5582 RTC_DCHECK(remote_description());
5583 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5584 // When we support "max-message-size", that would also be pushed down here.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005585 return cricket_sctp_transport()->Start(
Steve Anton75737c02017-11-06 10:37:17 -08005586 GetSctpPort(local_description()->description()),
5587 GetSctpPort(remote_description()->description()));
5588}
5589
Steve Anton8a006912017-12-04 15:25:56 -08005590RTCError PeerConnection::PushdownTransportDescription(
5591 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005592 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005593 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005594
Zhi Huange830e682018-03-30 10:48:35 -07005595 if (source == cricket::CS_LOCAL) {
5596 const SessionDescriptionInterface* sdesc = local_description();
5597 RTC_DCHECK(sdesc);
5598 return transport_controller_->SetLocalDescription(type,
5599 sdesc->description());
5600 } else {
5601 const SessionDescriptionInterface* sdesc = remote_description();
5602 RTC_DCHECK(sdesc);
5603 return transport_controller_->SetRemoteDescription(type,
5604 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005605 }
Steve Anton75737c02017-11-06 10:37:17 -08005606}
5607
5608bool PeerConnection::GetTransportDescription(
5609 const SessionDescription* description,
5610 const std::string& content_name,
5611 cricket::TransportDescription* tdesc) {
5612 if (!description || !tdesc) {
5613 return false;
5614 }
5615 const TransportInfo* transport_info =
5616 description->GetTransportInfoByName(content_name);
5617 if (!transport_info) {
5618 return false;
5619 }
5620 *tdesc = transport_info->description;
5621 return true;
5622}
5623
Steve Anton75737c02017-11-06 10:37:17 -08005624cricket::IceConfig PeerConnection::ParseIceConfig(
5625 const PeerConnectionInterface::RTCConfiguration& config) const {
5626 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005627 switch (config.continual_gathering_policy) {
5628 case PeerConnectionInterface::GATHER_ONCE:
5629 gathering_policy = cricket::GATHER_ONCE;
5630 break;
5631 case PeerConnectionInterface::GATHER_CONTINUALLY:
5632 gathering_policy = cricket::GATHER_CONTINUALLY;
5633 break;
5634 default:
5635 RTC_NOTREACHED();
5636 gathering_policy = cricket::GATHER_ONCE;
5637 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005638
Steve Anton75737c02017-11-06 10:37:17 -08005639 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005640 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5641 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005642 ice_config.prioritize_most_likely_candidate_pairs =
5643 config.prioritize_most_likely_ice_candidate_pairs;
5644 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005645 RTCConfigurationToIceConfigOptionalInt(
5646 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005647 ice_config.continual_gathering_policy = gathering_policy;
5648 ice_config.presume_writable_when_fully_relayed =
5649 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005650 ice_config.ice_check_interval_strong_connectivity =
5651 config.ice_check_interval_strong_connectivity;
5652 ice_config.ice_check_interval_weak_connectivity =
5653 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005654 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005655 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5656 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005657 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005658 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005659 ice_config.regather_all_networks_interval_range =
5660 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005661 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005662 return ice_config;
5663}
5664
Steve Antona41959e2018-11-28 11:15:33 -08005665static absl::string_view GetTrackIdBySsrc(
5666 const SessionDescriptionInterface* session_description,
5667 uint32_t ssrc) {
5668 if (!session_description) {
5669 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005670 }
Steve Antona41959e2018-11-28 11:15:33 -08005671 for (const cricket::ContentInfo& content :
5672 session_description->description()->contents()) {
5673 const cricket::MediaContentDescription& media =
5674 *content.media_description();
5675 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5676 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5677 const cricket::StreamParams* stream_params =
5678 cricket::GetStreamBySsrc(media.streams(), ssrc);
5679 if (stream_params) {
5680 return stream_params->id;
5681 }
5682 }
5683 }
5684 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005685}
5686
Steve Antona41959e2018-11-28 11:15:33 -08005687absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5688 return GetTrackIdBySsrc(local_description(), ssrc);
5689}
5690
5691absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5692 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005693}
5694
5695bool PeerConnection::SendData(const cricket::SendDataParams& params,
5696 const rtc::CopyOnWriteBuffer& payload,
5697 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005698 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5699 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5700 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005701 return false;
5702 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005703 if (media_transport_) {
5704 SendDataParams send_params;
5705 send_params.type = ToWebrtcDataMessageType(params.type);
5706 send_params.ordered = params.ordered;
5707 if (params.max_rtx_count >= 0) {
5708 send_params.max_rtx_count = params.max_rtx_count;
5709 } else if (params.max_rtx_ms >= 0) {
5710 send_params.max_rtx_ms = params.max_rtx_ms;
5711 }
5712 return media_transport_->SendData(params.sid, send_params, payload).ok();
5713 }
Steve Anton75737c02017-11-06 10:37:17 -08005714 return rtp_data_channel_
5715 ? rtp_data_channel_->SendData(params, payload, result)
5716 : network_thread()->Invoke<bool>(
5717 RTC_FROM_HERE,
5718 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005719 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005720}
5721
5722bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005723 RTC_DCHECK_RUN_ON(signaling_thread());
5724 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005725 // Don't log an error here, because DataChannels are expected to call
5726 // ConnectDataChannel in this state. It's the only way to initially tell
5727 // whether or not the underlying transport is ready.
5728 return false;
5729 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005730 if (media_transport_) {
5731 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5732 &DataChannel::OnChannelReady);
5733 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5734 &DataChannel::OnDataReceived);
5735 SignalMediaTransportChannelClosing_s.connect(
5736 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5737 SignalMediaTransportChannelClosed_s.connect(
5738 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5739 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005740 rtp_data_channel_->SignalReadyToSendData.connect(
5741 webrtc_data_channel, &DataChannel::OnChannelReady);
5742 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5743 &DataChannel::OnDataReceived);
5744 } else {
5745 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5746 &DataChannel::OnChannelReady);
5747 SignalSctpDataReceived.connect(webrtc_data_channel,
5748 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005749 SignalSctpClosingProcedureStartedRemotely.connect(
5750 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5751 SignalSctpClosingProcedureComplete.connect(
5752 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005753 }
5754 return true;
5755}
5756
5757void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005758 RTC_DCHECK_RUN_ON(signaling_thread());
5759 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005760 RTC_LOG(LS_ERROR)
5761 << "DisconnectDataChannel called when rtp_data_channel_ and "
5762 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005763 return;
5764 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005765 if (media_transport_) {
5766 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5767 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5768 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5769 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5770 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005771 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5772 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5773 } else {
5774 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5775 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005776 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5777 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005778 }
5779}
5780
5781void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005782 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005783 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005784 return;
5785 }
Steve Anton75737c02017-11-06 10:37:17 -08005786 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005787 RTC_LOG(LS_ERROR)
5788 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005789 return;
5790 }
5791 network_thread()->Invoke<void>(
5792 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005793 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005794}
5795
5796void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005797 if (media_transport_) {
5798 media_transport_->CloseChannel(sid);
5799 return;
5800 }
Steve Anton75737c02017-11-06 10:37:17 -08005801 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005802 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005803 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005804 return;
5805 }
5806 network_thread()->Invoke<void>(
5807 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005808 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005809}
5810
5811bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005812 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005813 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005814 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005815 sctp_ready_to_send_data_;
5816}
5817
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005818void PeerConnection::OnDataReceived(int channel_id,
5819 DataMessageType type,
5820 const rtc::CopyOnWriteBuffer& buffer) {
5821 cricket::ReceiveDataParams params;
5822 params.sid = channel_id;
5823 params.type = ToCricketDataMessageType(type);
5824 media_transport_invoker_->AsyncInvoke<void>(
5825 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5826 RTC_DCHECK_RUN_ON(signaling_thread());
5827 if (!HandleOpenMessage_s(params, buffer)) {
5828 SignalMediaTransportReceivedData_s(params, buffer);
5829 }
5830 });
5831}
5832
5833void PeerConnection::OnChannelClosing(int channel_id) {
5834 media_transport_invoker_->AsyncInvoke<void>(
5835 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5836 RTC_DCHECK_RUN_ON(signaling_thread());
5837 SignalMediaTransportChannelClosing_s(channel_id);
5838 });
5839}
5840
5841void PeerConnection::OnChannelClosed(int channel_id) {
5842 media_transport_invoker_->AsyncInvoke<void>(
5843 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5844 RTC_DCHECK_RUN_ON(signaling_thread());
5845 SignalMediaTransportChannelClosed_s(channel_id);
5846 });
5847}
5848
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005849absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005850 if (sctp_mid_ && transport_controller_) {
5851 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5852 if (dtls_transport) {
5853 return dtls_transport->transport_name();
5854 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005855 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005856 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005857 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005858}
5859
Qingsi Wang72a43a12018-02-20 16:03:18 -08005860cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5861 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005862 network_thread()->Invoke<void>(
5863 RTC_FROM_HERE,
5864 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5865 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005866 return candidate_states_list;
5867}
5868
Steve Anton5dfde182018-02-06 10:34:40 -08005869std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5870 const {
5871 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005872 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005873 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005874 if (channel) {
5875 transport_names_by_mid[channel->content_name()] =
5876 channel->transport_name();
5877 }
Steve Anton75737c02017-11-06 10:37:17 -08005878 }
Steve Anton5dfde182018-02-06 10:34:40 -08005879 if (rtp_data_channel_) {
5880 transport_names_by_mid[rtp_data_channel_->content_name()] =
5881 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005882 }
5883 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005884 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005885 RTC_DCHECK(transport_name);
5886 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005887 }
Steve Anton5dfde182018-02-06 10:34:40 -08005888 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005889}
5890
Steve Anton5dfde182018-02-06 10:34:40 -08005891std::map<std::string, cricket::TransportStats>
5892PeerConnection::GetTransportStatsByNames(
5893 const std::set<std::string>& transport_names) {
5894 if (!network_thread()->IsCurrent()) {
5895 return network_thread()
5896 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5897 RTC_FROM_HERE,
5898 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005899 }
Steve Anton5dfde182018-02-06 10:34:40 -08005900 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5901 for (const std::string& transport_name : transport_names) {
5902 cricket::TransportStats transport_stats;
5903 bool success =
5904 transport_controller_->GetStats(transport_name, &transport_stats);
5905 if (success) {
5906 transport_stats_by_name[transport_name] = std::move(transport_stats);
5907 } else {
5908 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5909 << transport_name;
5910 }
5911 }
5912 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005913}
5914
5915bool PeerConnection::GetLocalCertificate(
5916 const std::string& transport_name,
5917 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005918 if (!certificate) {
5919 return false;
5920 }
5921 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5922 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005923}
5924
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005925std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005926 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005927 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005928}
5929
5930cricket::DataChannelType PeerConnection::data_channel_type() const {
5931 return data_channel_type_;
5932}
5933
5934bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5935 return pending_ice_restarts_.find(content_name) !=
5936 pending_ice_restarts_.end();
5937}
5938
Steve Anton75737c02017-11-06 10:37:17 -08005939bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5940 return transport_controller_->NeedsIceRestart(content_name);
5941}
5942
5943void PeerConnection::OnCertificateReady(
5944 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5945 transport_controller_->SetLocalCertificate(certificate);
5946}
5947
5948void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005949 SetSessionError(SessionError::kTransport,
5950 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005951}
5952
Alex Loiko9289eda2018-11-23 16:18:59 +00005953void PeerConnection::OnTransportControllerConnectionState(
5954 cricket::IceConnectionState state) {
5955 switch (state) {
5956 case cricket::kIceConnectionConnecting:
5957 // If the current state is Connected or Completed, then there were
5958 // writable channels but now there are not, so the next state must
5959 // be Disconnected.
5960 // kIceConnectionConnecting is currently used as the default,
5961 // un-connected state by the TransportController, so its only use is
5962 // detecting disconnections.
5963 if (ice_connection_state_ ==
5964 PeerConnectionInterface::kIceConnectionConnected ||
5965 ice_connection_state_ ==
5966 PeerConnectionInterface::kIceConnectionCompleted) {
5967 SetIceConnectionState(
5968 PeerConnectionInterface::kIceConnectionDisconnected);
5969 }
5970 break;
5971 case cricket::kIceConnectionFailed:
5972 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5973 break;
5974 case cricket::kIceConnectionConnected:
5975 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5976 "all transports are writable.";
5977 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5978 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5979 break;
5980 case cricket::kIceConnectionCompleted:
5981 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5982 "all transports are complete.";
5983 if (ice_connection_state_ !=
5984 PeerConnectionInterface::kIceConnectionConnected) {
5985 // If jumping directly from "checking" to "connected",
5986 // signal "connected" first.
5987 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5988 }
5989 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5990 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5991 ReportTransportStats();
5992 break;
5993 default:
5994 RTC_NOTREACHED();
5995 }
5996}
5997
Steve Anton75737c02017-11-06 10:37:17 -08005998void PeerConnection::OnTransportControllerCandidatesGathered(
5999 const std::string& transport_name,
6000 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006001 int sdp_mline_index;
6002 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006003 RTC_LOG(LS_ERROR)
6004 << "OnTransportControllerCandidatesGathered: content name "
6005 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006006 return;
6007 }
6008
6009 for (cricket::Candidates::const_iterator citer = candidates.begin();
6010 citer != candidates.end(); ++citer) {
6011 // Use transport_name as the candidate media id.
6012 std::unique_ptr<JsepIceCandidate> candidate(
6013 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6014 if (local_description()) {
6015 mutable_local_description()->AddCandidate(candidate.get());
6016 }
6017 OnIceCandidate(std::move(candidate));
6018 }
6019}
6020
6021void PeerConnection::OnTransportControllerCandidatesRemoved(
6022 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006023 // Sanity check.
6024 for (const cricket::Candidate& candidate : candidates) {
6025 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006026 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006027 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006028 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006029 return;
6030 }
6031 }
6032
6033 if (local_description()) {
6034 mutable_local_description()->RemoveCandidates(candidates);
6035 }
6036 OnIceCandidatesRemoved(candidates);
6037}
6038
6039void PeerConnection::OnTransportControllerDtlsHandshakeError(
6040 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006041 RTC_HISTOGRAM_ENUMERATION(
6042 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6043 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006044}
6045
Steve Antoned10bd92017-12-05 10:52:59 -08006046void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006047 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006048 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006049 if (channel && !channel->enabled()) {
6050 channel->Enable(true);
6051 }
Steve Anton75737c02017-11-06 10:37:17 -08006052 }
6053
Steve Anton4171afb2017-11-20 10:20:22 -08006054 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006055 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006056 }
Steve Anton75737c02017-11-06 10:37:17 -08006057}
6058
6059// Returns the media index for a local ice candidate given the content name.
6060bool PeerConnection::GetLocalCandidateMediaIndex(
6061 const std::string& content_name,
6062 int* sdp_mline_index) {
6063 if (!local_description() || !sdp_mline_index) {
6064 return false;
6065 }
6066
6067 bool content_found = false;
6068 const ContentInfos& contents = local_description()->description()->contents();
6069 for (size_t index = 0; index < contents.size(); ++index) {
6070 if (contents[index].name == content_name) {
6071 *sdp_mline_index = static_cast<int>(index);
6072 content_found = true;
6073 break;
6074 }
6075 }
6076 return content_found;
6077}
6078
6079bool PeerConnection::UseCandidatesInSessionDescription(
6080 const SessionDescriptionInterface* remote_desc) {
6081 if (!remote_desc) {
6082 return true;
6083 }
6084 bool ret = true;
6085
6086 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6087 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6088 for (size_t n = 0; n < candidates->count(); ++n) {
6089 const IceCandidateInterface* candidate = candidates->at(n);
6090 bool valid = false;
6091 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6092 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006093 RTC_LOG(LS_INFO)
6094 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006095 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006096 }
6097 continue;
6098 }
6099 ret = UseCandidate(candidate);
6100 if (!ret) {
6101 break;
6102 }
6103 }
6104 }
6105 return ret;
6106}
6107
6108bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6109 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6110 size_t remote_content_size =
6111 remote_description()->description()->contents().size();
6112 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006113 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006114 return false;
6115 }
6116
6117 cricket::ContentInfo content =
6118 remote_description()->description()->contents()[mediacontent_index];
6119 std::vector<cricket::Candidate> candidates;
6120 candidates.push_back(candidate->candidate());
6121 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006122 RTCError error =
6123 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006124 if (error.ok()) {
6125 // Candidates successfully submitted for checking.
6126 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6127 ice_connection_state_ ==
6128 PeerConnectionInterface::kIceConnectionDisconnected) {
6129 // If state is New, then the session has just gotten its first remote ICE
6130 // candidates, so go to Checking.
6131 // If state is Disconnected, the session is re-using old candidates or
6132 // receiving additional ones, so go to Checking.
6133 // If state is Connected, stay Connected.
6134 // TODO(bemasc): If state is Connected, and the new candidates are for a
6135 // newly added transport, then the state actually _should_ move to
6136 // checking. Add a way to distinguish that case.
6137 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6138 }
6139 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006140 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006141 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006142 }
6143 return true;
6144}
6145
6146void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006147 // Destroy video channel first since it may have a pointer to the
6148 // voice channel.
6149 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006150 if (!video_info || video_info->rejected) {
6151 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006152 }
6153
Steve Anton6fec8802017-12-04 10:37:29 -08006154 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6155 if (!audio_info || audio_info->rejected) {
6156 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006157 }
6158
6159 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6160 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006161 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006162 }
6163}
6164
Steve Antondcc3c022017-12-22 16:02:54 -08006165RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6166 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006167 const cricket::ContentGroup* bundle_group = nullptr;
6168 if (configuration_.bundle_policy ==
6169 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006170 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006171 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006172 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6173 "max-bundle configured but session description "
6174 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006175 }
6176 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006177 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006178}
6179
6180RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006181 // Creating the media channels. Transports should already have been created
6182 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006183 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006184 if (voice && !voice->rejected &&
6185 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006186 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006187 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006188 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6189 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006190 }
6191 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6192 }
6193
Steve Antondcc3c022017-12-22 16:02:54 -08006194 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006195 if (video && !video->rejected &&
6196 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006197 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006198 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006199 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6200 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006201 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006202 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006203 }
6204
Steve Antondcc3c022017-12-22 16:02:54 -08006205 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006206 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006207 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006208 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006209 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6210 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006211 }
6212 }
6213
Steve Anton8a006912017-12-04 15:25:56 -08006214 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006215}
6216
Steve Anton4171afb2017-11-20 10:20:22 -08006217// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006218cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006219 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006220 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006221 MediaTransportInterface* media_transport = nullptr;
6222 if (configuration_.use_media_transport) {
6223 media_transport = GetMediaTransport(mid);
6224 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006225
Steve Anton75737c02017-11-06 10:37:17 -08006226 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006227 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006228 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006229 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006230 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006231 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006232 }
Steve Anton75737c02017-11-06 10:37:17 -08006233 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6234 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006235 voice_channel->SignalSentPacket.connect(this,
6236 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006237 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006238
Steve Antoneda6ccd2017-12-04 10:21:55 -08006239 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006240}
6241
Steve Anton4171afb2017-11-20 10:20:22 -08006242// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006243cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006244 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006245 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006246 MediaTransportInterface* media_transport = nullptr;
6247 if (configuration_.use_media_transport) {
6248 media_transport = GetMediaTransport(mid);
6249 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006250
Steve Anton75737c02017-11-06 10:37:17 -08006251 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006252 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006253 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006254 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006255 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006256 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006257 }
Steve Anton75737c02017-11-06 10:37:17 -08006258 video_channel->SignalDtlsSrtpSetupFailure.connect(
6259 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006260 video_channel->SignalSentPacket.connect(this,
6261 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006262 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006263
Steve Antoneda6ccd2017-12-04 10:21:55 -08006264 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006265}
6266
Zhi Huange830e682018-03-30 10:48:35 -07006267bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006268 switch (data_channel_type_) {
6269 case cricket::DCT_MEDIA_TRANSPORT:
6270 if (network_thread()->Invoke<bool>(
6271 RTC_FROM_HERE,
6272 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6273 this, mid))) {
6274 for (const auto& channel : sctp_data_channels_) {
6275 channel->OnTransportChannelCreated();
6276 }
6277 return true;
6278 }
Steve Anton75737c02017-11-06 10:37:17 -08006279 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006280 case cricket::DCT_SCTP:
6281 if (!sctp_factory_) {
6282 RTC_LOG(LS_ERROR)
6283 << "Trying to create SCTP transport, but didn't compile with "
6284 "SCTP support (HAVE_SCTP)";
6285 return false;
6286 }
6287 if (!network_thread()->Invoke<bool>(
6288 RTC_FROM_HERE,
6289 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6290 return false;
6291 }
6292 for (const auto& channel : sctp_data_channels_) {
6293 channel->OnTransportChannelCreated();
6294 }
6295 return true;
6296 case cricket::DCT_RTP:
6297 default:
6298 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6299 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6300 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006301 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006302 if (!rtp_data_channel_) {
6303 return false;
6304 }
6305 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6306 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6307 rtp_data_channel_->SignalSentPacket.connect(
6308 this, &PeerConnection::OnSentPacket_w);
6309 rtp_data_channel_->SetRtpTransport(rtp_transport);
6310 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006311 }
6312
Steve Anton75737c02017-11-06 10:37:17 -08006313 return true;
6314}
6315
6316Call::Stats PeerConnection::GetCallStats() {
6317 if (!worker_thread()->IsCurrent()) {
6318 return worker_thread()->Invoke<Call::Stats>(
6319 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6320 }
6321 if (call_) {
6322 return call_->GetStats();
6323 } else {
6324 return Call::Stats();
6325 }
6326}
6327
Zhi Huange830e682018-03-30 10:48:35 -07006328bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006329 RTC_DCHECK(network_thread()->IsCurrent());
6330 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006331 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6332 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006333 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006334 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006335 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006336 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6337 sctp_factory_->CreateSctpTransport(dtls_transport);
6338 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006339 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006340 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006341 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006342 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006343 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006344 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6345 // another thread. Would be nice if there was a helper class similar to
6346 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6347 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006348 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006349 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006350 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006351 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006352 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006353 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6354 std::move(cricket_sctp_transport));
6355 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006356 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006357}
6358
6359void PeerConnection::DestroySctpTransport_n() {
6360 RTC_DCHECK(network_thread()->IsCurrent());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006361 sctp_transport_->Clear();
6362 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006363 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006364 sctp_invoker_.reset(nullptr);
6365 sctp_ready_to_send_data_ = false;
6366}
6367
6368void PeerConnection::OnSctpTransportReadyToSendData_n() {
6369 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6370 RTC_DCHECK(network_thread()->IsCurrent());
6371 // Note: Cannot use rtc::Bind here because it will grab a reference to
6372 // PeerConnection and potentially cause PeerConnection to live longer than
6373 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6374 // be destroyed before PeerConnection is destroyed, and at that point all
6375 // pending tasks will be cleared.
6376 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6377 OnSctpTransportReadyToSendData_s(true);
6378 });
6379}
6380
6381void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6382 RTC_DCHECK(signaling_thread()->IsCurrent());
6383 sctp_ready_to_send_data_ = ready;
6384 SignalSctpReadyToSendData(ready);
6385}
6386
6387void PeerConnection::OnSctpTransportDataReceived_n(
6388 const cricket::ReceiveDataParams& params,
6389 const rtc::CopyOnWriteBuffer& payload) {
6390 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6391 RTC_DCHECK(network_thread()->IsCurrent());
6392 // Note: Cannot use rtc::Bind here because it will grab a reference to
6393 // PeerConnection and potentially cause PeerConnection to live longer than
6394 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6395 // be destroyed before PeerConnection is destroyed, and at that point all
6396 // pending tasks will be cleared.
6397 sctp_invoker_->AsyncInvoke<void>(
6398 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6399 OnSctpTransportDataReceived_s(params, payload);
6400 });
6401}
6402
6403void PeerConnection::OnSctpTransportDataReceived_s(
6404 const cricket::ReceiveDataParams& params,
6405 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006406 RTC_DCHECK_RUN_ON(signaling_thread());
6407 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006408 SignalSctpDataReceived(params, payload);
6409 }
6410}
6411
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006412void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006413 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6414 RTC_DCHECK(network_thread()->IsCurrent());
6415 sctp_invoker_->AsyncInvoke<void>(
6416 RTC_FROM_HERE, signaling_thread(),
6417 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006418 &SignalSctpClosingProcedureStartedRemotely, sid));
6419}
6420
6421void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6422 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6423 RTC_DCHECK(network_thread()->IsCurrent());
6424 sctp_invoker_->AsyncInvoke<void>(
6425 RTC_FROM_HERE, signaling_thread(),
6426 rtc::Bind(&sigslot::signal1<int>::operator(),
6427 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006428}
6429
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006430bool PeerConnection::SetupMediaTransportForDataChannels_n(
6431 const std::string& mid) {
6432 media_transport_ = transport_controller_->GetMediaTransport(mid);
6433 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006434 RTC_LOG(LS_ERROR)
6435 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006436 return false;
6437 }
6438
6439 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6440 media_transport_->SetDataSink(this);
6441 media_transport_data_mid_ = mid;
6442 transport_controller_->SignalMediaTransportStateChanged.connect(
6443 this, &PeerConnection::OnMediaTransportStateChanged_n);
6444 // Check the initial state right away, in case transport is already writable.
6445 OnMediaTransportStateChanged_n();
6446 return true;
6447}
6448
6449void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6450 if (!media_transport_) {
6451 return;
6452 }
6453 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6454 media_transport_data_mid_.reset();
6455 media_transport_->SetDataSink(nullptr);
6456 media_transport_invoker_ = nullptr;
6457 media_transport_ = nullptr;
6458}
6459
6460void PeerConnection::OnMediaTransportStateChanged_n() {
6461 if (!media_transport_data_mid_ ||
6462 transport_controller_->GetMediaTransportState(
6463 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6464 return;
6465 }
6466 media_transport_invoker_->AsyncInvoke<void>(
6467 RTC_FROM_HERE, signaling_thread(), [this] {
6468 RTC_DCHECK_RUN_ON(signaling_thread());
6469 media_transport_ready_to_send_data_ = true;
6470 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6471 });
6472}
6473
Steve Anton75737c02017-11-06 10:37:17 -08006474// Returns false if bundle is enabled and rtcp_mux is disabled.
6475bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6476 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6477 if (!bundle_enabled)
6478 return true;
6479
6480 const cricket::ContentGroup* bundle_group =
6481 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6482 RTC_DCHECK(bundle_group != NULL);
6483
6484 const cricket::ContentInfos& contents = desc->contents();
6485 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6486 citer != contents.end(); ++citer) {
6487 const cricket::ContentInfo* content = (&*citer);
6488 RTC_DCHECK(content != NULL);
6489 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006490 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006491 if (!HasRtcpMuxEnabled(content))
6492 return false;
6493 }
6494 }
6495 // RTCP-MUX is enabled in all the contents.
6496 return true;
6497}
6498
6499bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006500 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006501}
6502
Steve Anton06817cd2018-12-18 15:55:30 -08006503static RTCError ValidateMids(const cricket::SessionDescription& description) {
6504 std::set<std::string> mids;
6505 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006506 if (content.name.empty()) {
6507 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6508 "A media section is missing a MID attribute.");
6509 }
Steve Anton06817cd2018-12-18 15:55:30 -08006510 if (!mids.insert(content.name).second) {
6511 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6512 "Duplicate a=mid value '" + content.name + "'.");
6513 }
6514 }
6515 return RTCError::OK();
6516}
6517
Steve Anton8a006912017-12-04 15:25:56 -08006518RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006519 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006520 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006521 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006522 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006523 }
6524
6525 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006526 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006527 }
6528
Steve Anton3828c062017-12-06 10:34:51 -08006529 SdpType type = sdesc->GetType();
6530 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6531 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006532 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006533 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006534 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006535 }
6536
Steve Anton06817cd2018-12-18 15:55:30 -08006537 RTCError error = ValidateMids(*sdesc->description());
6538 if (!error.ok()) {
6539 return error;
6540 }
6541
Steve Anton75737c02017-11-06 10:37:17 -08006542 // Verify crypto settings.
6543 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006544 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6545 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006546 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006547 if (!crypto_error.ok()) {
6548 return crypto_error;
6549 }
Steve Anton75737c02017-11-06 10:37:17 -08006550 }
6551
6552 // Verify ice-ufrag and ice-pwd.
6553 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006554 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6555 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006556 }
6557
6558 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6560 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006561 }
6562
6563 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6564 // m-lines that do not rtcp-mux enabled.
6565
6566 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006567 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006568 // With an answer we want to compare the new answer session description with
6569 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006570 const cricket::SessionDescription* offer_desc =
6571 (source == cricket::CS_LOCAL) ? remote_description()->description()
6572 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006573 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6574 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6575 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006576 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6577 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006578 }
6579 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006580 // The re-offers should respect the order of m= sections in current
6581 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006582 // With a re-offer, either the current local or current remote descriptions
6583 // could be the most up to date, so we would like to check against both of
6584 // them if they exist. It could be the case that one of them has a 0 port
6585 // for a media section, but the other does not. This is important to check
6586 // against in the case that we are recycling an m= section.
6587 const cricket::SessionDescription* current_desc = nullptr;
6588 const cricket::SessionDescription* secondary_current_desc = nullptr;
6589 if (local_description()) {
6590 current_desc = local_description()->description();
6591 if (remote_description()) {
6592 secondary_current_desc = remote_description()->description();
6593 }
6594 } else if (remote_description()) {
6595 current_desc = remote_description()->description();
6596 }
Steve Anton75737c02017-11-06 10:37:17 -08006597 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006598 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6599 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006600 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6601 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006602 }
6603 }
6604
Steve Antonba42e992018-04-09 14:10:01 -07006605 if (IsUnifiedPlan()) {
6606 // Ensure that each audio and video media section has at most one
6607 // "StreamParams". This will return an error if receiving a session
6608 // description from a "Plan B" endpoint which adds multiple tracks of the
6609 // same type. With Unified Plan, there can only be at most one track per
6610 // media section.
6611 for (const ContentInfo& content : sdesc->description()->contents()) {
6612 const MediaContentDescription& desc = *content.description;
6613 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6614 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6615 desc.streams().size() > 1u) {
6616 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6617 "Media section has more than one track specified "
6618 "with a=ssrc lines which is not supported with "
6619 "Unified Plan.");
6620 }
6621 }
6622 }
6623
Steve Anton8a006912017-12-04 15:25:56 -08006624 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006625}
6626
Steve Anton3828c062017-12-06 10:34:51 -08006627bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006628 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006629 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006630 return (state == PeerConnectionInterface::kStable) ||
6631 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006632 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006633 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006634 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6635 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6636 }
6637}
6638
Steve Anton3828c062017-12-06 10:34:51 -08006639bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006640 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006641 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006642 return (state == PeerConnectionInterface::kStable) ||
6643 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006644 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006645 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006646 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6647 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6648 }
6649}
6650
Steve Antonf8470812017-12-04 10:46:21 -08006651const char* PeerConnection::SessionErrorToString(SessionError error) const {
6652 switch (error) {
6653 case SessionError::kNone:
6654 return "ERROR_NONE";
6655 case SessionError::kContent:
6656 return "ERROR_CONTENT";
6657 case SessionError::kTransport:
6658 return "ERROR_TRANSPORT";
6659 }
6660 RTC_NOTREACHED();
6661 return "";
6662}
6663
Steve Anton75737c02017-11-06 10:37:17 -08006664std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006665 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006666 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6667 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006668 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006669}
6670
Steve Anton8e20f172018-03-06 10:55:04 -08006671void PeerConnection::ReportSdpFormatReceived(
6672 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006673 int num_audio_mlines = 0;
6674 int num_video_mlines = 0;
6675 int num_audio_tracks = 0;
6676 int num_video_tracks = 0;
6677 for (const ContentInfo& content : remote_offer.description()->contents()) {
6678 cricket::MediaType media_type = content.media_description()->type();
6679 int num_tracks = std::max(
6680 1, static_cast<int>(content.media_description()->streams().size()));
6681 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6682 num_audio_mlines += 1;
6683 num_audio_tracks += num_tracks;
6684 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6685 num_video_mlines += 1;
6686 num_video_tracks += num_tracks;
6687 }
6688 }
6689 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6690 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6691 format = kSdpFormatReceivedComplexUnifiedPlan;
6692 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6693 format = kSdpFormatReceivedComplexPlanB;
6694 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6695 format = kSdpFormatReceivedSimple;
6696 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006697 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6698 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006699}
6700
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006701void PeerConnection::NoteUsageEvent(UsageEvent event) {
6702 RTC_DCHECK_RUN_ON(signaling_thread());
6703 usage_event_accumulator_ |= static_cast<int>(event);
6704}
6705
6706void PeerConnection::ReportUsagePattern() const {
6707 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006708 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6709 usage_event_accumulator_,
6710 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006711 const int bad_bits =
6712 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6713 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6714 const int good_bits =
6715 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6716 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6717 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6718 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6719 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006720 // If called after close(), we can't report, because observer may have
6721 // been deallocated, and therefore pointer is null. Write to log instead.
6722 if (observer_) {
6723 Observer()->OnInterestingUsage(usage_event_accumulator_);
6724 } else {
6725 RTC_LOG(LS_INFO) << "Interesting usage signature "
6726 << usage_event_accumulator_
6727 << " observed after observer shutdown";
6728 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006729 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006730}
6731
Steve Anton0ffaaa22018-02-23 10:31:30 -08006732void PeerConnection::ReportNegotiatedSdpSemantics(
6733 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006734 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006735 switch (answer.description()->msid_signaling()) {
6736 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006737 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006738 break;
6739 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006740 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006741 break;
6742 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006743 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006744 break;
6745 case cricket::kMsidSignalingMediaSection |
6746 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006747 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006748 break;
6749 default:
6750 RTC_NOTREACHED();
6751 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006752 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6753 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006754}
6755
Steve Anton75737c02017-11-06 10:37:17 -08006756// We need to check the local/remote description for the Transport instead of
6757// the session, because a new Transport added during renegotiation may have
6758// them unset while the session has them set from the previous negotiation.
6759// Not doing so may trigger the auto generation of transport description and
6760// mess up DTLS identity information, ICE credential, etc.
6761bool PeerConnection::ReadyToUseRemoteCandidate(
6762 const IceCandidateInterface* candidate,
6763 const SessionDescriptionInterface* remote_desc,
6764 bool* valid) {
6765 *valid = true;
6766
6767 const SessionDescriptionInterface* current_remote_desc =
6768 remote_desc ? remote_desc : remote_description();
6769
6770 if (!current_remote_desc) {
6771 return false;
6772 }
6773
6774 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6775 size_t remote_content_size =
6776 current_remote_desc->description()->contents().size();
6777 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006778 RTC_LOG(LS_ERROR)
6779 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6780 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006781
6782 *valid = false;
6783 return false;
6784 }
6785
6786 cricket::ContentInfo content =
6787 current_remote_desc->description()->contents()[mediacontent_index];
6788
6789 const std::string transport_name = GetTransportName(content.name);
6790 if (transport_name.empty()) {
6791 return false;
6792 }
Zhi Huange830e682018-03-30 10:48:35 -07006793 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006794}
6795
6796bool PeerConnection::SrtpRequired() const {
6797 return dtls_enabled_ ||
6798 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6799}
6800
6801void PeerConnection::OnTransportControllerGatheringState(
6802 cricket::IceGatheringState state) {
6803 RTC_DCHECK(signaling_thread()->IsCurrent());
6804 if (state == cricket::kIceGatheringGathering) {
6805 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6806 } else if (state == cricket::kIceGatheringComplete) {
6807 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6808 }
6809}
6810
6811void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006812 std::map<std::string, std::set<cricket::MediaType>>
6813 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006814 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006815 if (transceiver->internal()->channel()) {
6816 const std::string& transport_name =
6817 transceiver->internal()->channel()->transport_name();
6818 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006819 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006820 }
Steve Anton75737c02017-11-06 10:37:17 -08006821 }
6822 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006823 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6824 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006825 }
Zhi Huange830e682018-03-30 10:48:35 -07006826
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006827 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006828 if (transport_name) {
6829 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006830 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006831 }
Zhi Huange830e682018-03-30 10:48:35 -07006832
Steve Antonc7b964c2018-02-01 14:39:45 -08006833 for (const auto& entry : media_types_by_transport_name) {
6834 const std::string& transport_name = entry.first;
6835 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006836 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006837 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006838 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006839 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006840 }
6841 }
6842}
6843// Walk through the ConnectionInfos to gather best connection usage
6844// for IPv4 and IPv6.
6845void PeerConnection::ReportBestConnectionState(
6846 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006847 for (const cricket::TransportChannelStats& channel_stats :
6848 stats.channel_stats) {
6849 for (const cricket::ConnectionInfo& connection_info :
6850 channel_stats.connection_infos) {
6851 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006852 continue;
6853 }
6854
Steve Antonc7b964c2018-02-01 14:39:45 -08006855 const cricket::Candidate& local = connection_info.local_candidate;
6856 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006857
6858 // Increment the counter for IceCandidatePairType.
6859 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6860 (local.type() == RELAY_PORT_TYPE &&
6861 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006862 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6863 GetIceCandidatePairCounter(local, remote),
6864 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006865 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006866 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6867 GetIceCandidatePairCounter(local, remote),
6868 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006869 } else {
6870 RTC_CHECK(0);
6871 }
Steve Anton75737c02017-11-06 10:37:17 -08006872
6873 // Increment the counter for IP type.
6874 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006875 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6876 kBestConnections_IPv4,
6877 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006878 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006879 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6880 kBestConnections_IPv6,
6881 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006882 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006883 RTC_CHECK(!local.address().hostname().empty() &&
6884 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006885 }
6886
6887 return;
6888 }
6889 }
6890}
6891
6892void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006893 const cricket::TransportStats& stats,
6894 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006895 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6896 return;
6897 }
6898
6899 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6900 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6901 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6902 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6903 return;
6904 }
6905
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006906 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6907 for (cricket::MediaType media_type : media_types) {
6908 switch (media_type) {
6909 case cricket::MEDIA_TYPE_AUDIO:
6910 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6911 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6912 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6913 break;
6914 case cricket::MEDIA_TYPE_VIDEO:
6915 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6916 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6917 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6918 break;
6919 case cricket::MEDIA_TYPE_DATA:
6920 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6921 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6922 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6923 break;
6924 default:
6925 RTC_NOTREACHED();
6926 continue;
6927 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006928 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006929 }
6930
6931 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6932 for (cricket::MediaType media_type : media_types) {
6933 switch (media_type) {
6934 case cricket::MEDIA_TYPE_AUDIO:
6935 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6936 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6937 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6938 break;
6939 case cricket::MEDIA_TYPE_VIDEO:
6940 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6941 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6942 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6943 break;
6944 case cricket::MEDIA_TYPE_DATA:
6945 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6946 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6947 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6948 break;
6949 default:
6950 RTC_NOTREACHED();
6951 continue;
6952 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006953 }
Steve Anton75737c02017-11-06 10:37:17 -08006954 }
6955}
6956
6957void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6958 RTC_DCHECK(worker_thread()->IsCurrent());
6959 RTC_DCHECK(call_);
6960 call_->OnSentPacket(sent_packet);
6961}
6962
6963const std::string PeerConnection::GetTransportName(
6964 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006965 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006966 if (channel) {
6967 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006968 }
Steve Anton6fec8802017-12-04 10:37:29 -08006969 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006970 RTC_DCHECK(sctp_mid_);
6971 if (content_name == *sctp_mid_) {
6972 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006973 }
6974 }
6975 // Return an empty string if failed to retrieve the transport name.
6976 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006977}
6978
Steve Anton6fec8802017-12-04 10:37:29 -08006979void PeerConnection::DestroyTransceiverChannel(
6980 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6981 transceiver) {
6982 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006983
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006984 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006985 if (channel) {
6986 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006987 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006988 }
6989}
6990
6991void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006992 if (rtp_data_channel_) {
6993 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006994 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006995 rtp_data_channel_ = nullptr;
6996 }
6997
6998 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6999 // grab a reference to this PeerConnection. If this is called from the
7000 // PeerConnection destructor, the RefCountedObject vtable will have already
7001 // been destroyed (since it is a subclass of PeerConnection) and using
7002 // rtc::Bind will cause "Pure virtual function called" error to appear.
7003
7004 if (sctp_transport_) {
7005 OnDataChannelDestroyed();
7006 network_thread()->Invoke<void>(RTC_FROM_HERE,
7007 [this] { DestroySctpTransport_n(); });
7008 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007009
7010 if (media_transport_) {
7011 OnDataChannelDestroyed();
7012 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7013 RTC_DCHECK_RUN_ON(network_thread());
7014 TeardownMediaTransportForDataChannels_n();
7015 });
7016 }
Steve Anton6fec8802017-12-04 10:37:29 -08007017}
7018
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007019void PeerConnection::DestroyChannelInterface(
7020 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007021 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007022 switch (channel->media_type()) {
7023 case cricket::MEDIA_TYPE_AUDIO:
7024 channel_manager()->DestroyVoiceChannel(
7025 static_cast<cricket::VoiceChannel*>(channel));
7026 break;
7027 case cricket::MEDIA_TYPE_VIDEO:
7028 channel_manager()->DestroyVideoChannel(
7029 static_cast<cricket::VideoChannel*>(channel));
7030 break;
7031 case cricket::MEDIA_TYPE_DATA:
7032 channel_manager()->DestroyRtpDataChannel(
7033 static_cast<cricket::RtpDataChannel*>(channel));
7034 break;
7035 default:
7036 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7037 break;
7038 }
Zhi Huange830e682018-03-30 10:48:35 -07007039}
Steve Anton6fec8802017-12-04 10:37:29 -08007040
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007041bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007042 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007043 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007044 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007045 MediaTransportInterface* media_transport) {
Karl Wiberg5966c502019-02-21 23:55:09 +01007046 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007047 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007048 auto base_channel = GetChannel(mid);
7049 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007050 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007051 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007052 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007053 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007054 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007055
Karl Wiberg5966c502019-02-21 23:55:09 +01007056 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007057 // Only pass media transport to call object if media transport is used
7058 // for media (and not data channel).
7059 call_->MediaTransportChange(media_transport);
7060 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007061
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007062 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007063}
7064
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007065PeerConnectionObserver* PeerConnection::Observer() const {
7066 // In earlier production code, the pointer was not cleared on close,
7067 // which might have led to undefined behavior if the observer was not
7068 // deallocated, or strange crashes if it was.
7069 // We use CHECK in order to catch such behavior if it exists.
7070 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7071 RTC_CHECK(observer_);
7072 return observer_;
7073}
7074
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007075CryptoOptions PeerConnection::GetCryptoOptions() {
7076 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7077 // after it has been removed.
7078 return configuration_.crypto_options.has_value()
7079 ? *configuration_.crypto_options
7080 : factory_->options().crypto_options;
7081}
7082
Harald Alvestrand89061872018-01-02 14:08:34 +01007083void PeerConnection::ClearStatsCache() {
7084 if (stats_collector_) {
7085 stats_collector_->ClearCachedStatsReport();
7086 }
7087}
7088
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007089void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007090 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7091 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007092}
7093
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007094} // namespace webrtc