blob: 3be5ca3fa39a7d375e2bccf5fb8da51ad53f8211 [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
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010021#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "api/jsep_ice_candidate.h"
23#include "api/jsep_session_description.h"
24#include "api/media_stream_proxy.h"
25#include "api/media_stream_track_proxy.h"
26#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020029#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "logging/rtc_event_log/rtc_event_log.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "media/sctp/sctp_transport.h"
32#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080033#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "pc/channel_manager.h"
35#include "pc/dtmf_sender.h"
36#include "pc/media_stream.h"
37#include "pc/media_stream_observer.h"
38#include "pc/remote_audio_source.h"
39#include "pc/rtp_media_utils.h"
40#include "pc/rtp_receiver.h"
41#include "pc/rtp_sender.h"
42#include "pc/sctp_utils.h"
43#include "pc/sdp_utils.h"
44#include "pc/stream_collection.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "pc/video_capturer_track_source.h"
46#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/bind.h"
48#include "rtc_base/checks.h"
49#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010050#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080051#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020052#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080062using cricket::SessionDescription;
63using cricket::SimulcastLayerList;
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::TransportInfo;
65
66using cricket::LOCAL_PORT_TYPE;
67using cricket::STUN_PORT_TYPE;
68using cricket::RELAY_PORT_TYPE;
69using cricket::PRFLX_PORT_TYPE;
70
Steve Antonba818672017-11-06 10:21:57 -080071namespace webrtc {
72
Steve Anton75737c02017-11-06 10:37:17 -080073// Error messages
74const char kBundleWithoutRtcpMux[] =
75 "rtcp-mux must be enabled when BUNDLE "
76 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080077const char kInvalidCandidates[] = "Description contains invalid candidates.";
78const char kInvalidSdp[] = "Invalid session description.";
79const char kMlineMismatchInAnswer[] =
80 "The order of m-lines in answer doesn't match order in offer. Rejecting "
81 "answer.";
82const char kMlineMismatchInSubsequentOffer[] =
83 "The order of m-lines in subsequent offer doesn't match order from "
84 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080085const char kSdpWithoutDtlsFingerprint[] =
86 "Called with SDP without DTLS fingerprint.";
87const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
88const char kSdpWithoutIceUfragPwd[] =
89 "Called with SDP without ice-ufrag and ice-pwd.";
90const char kSessionError[] = "Session error code: ";
91const char kSessionErrorDesc[] = "Session error description: ";
92const char kDtlsSrtpSetupFailureRtp[] =
93 "Couldn't set up DTLS-SRTP on RTP channel.";
94const char kDtlsSrtpSetupFailureRtcp[] =
95 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Steve Anton75737c02017-11-06 10:37:17 -080097namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098
Seth Hampson845e8782018-03-02 11:34:10 -080099static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800100static const char kDefaultAudioSenderId[] = "defaulta0";
101static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700102
zhihuang8f65cdf2016-05-06 18:40:30 -0700103// The length of RTCP CNAMEs.
104static const int kRtcpCnameLength = 16;
105
Steve Antonad182762018-09-05 20:22:40 +0000106enum {
107 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
108 MSG_SET_SESSIONDESCRIPTION_FAILED,
109 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
110 MSG_GETSTATS,
111 MSG_FREE_DATACHANNELS,
112 MSG_REPORT_USAGE_PATTERN,
113};
114
Harald Alvestrand19793842018-06-25 12:03:50 +0200115static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
116
Steve Antonad182762018-09-05 20:22:40 +0000117struct SetSessionDescriptionMsg : public rtc::MessageData {
118 explicit SetSessionDescriptionMsg(
119 webrtc::SetSessionDescriptionObserver* observer)
120 : observer(observer) {}
121
122 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
123 RTCError error;
124};
125
126struct CreateSessionDescriptionMsg : public rtc::MessageData {
127 explicit CreateSessionDescriptionMsg(
128 webrtc::CreateSessionDescriptionObserver* observer)
129 : observer(observer) {}
130
131 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
132 RTCError error;
133};
134
135struct GetStatsMsg : public rtc::MessageData {
136 GetStatsMsg(webrtc::StatsObserver* observer,
137 webrtc::MediaStreamTrackInterface* track)
138 : observer(observer), track(track) {}
139 rtc::scoped_refptr<webrtc::StatsObserver> observer;
140 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
141};
142
deadbeefab9b2d12015-10-14 11:33:11 -0700143// Check if we can send |new_stream| on a PeerConnection.
144bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
145 webrtc::MediaStreamInterface* new_stream) {
146 if (!new_stream || !current_streams) {
147 return false;
148 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700149 if (current_streams->find(new_stream->id()) != nullptr) {
150 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100151 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700152 return false;
153 }
154 return true;
155}
156
deadbeef5e97fb52015-10-15 12:49:08 -0700157// If the direction is "recvonly" or "inactive", treat the description
158// as containing no streams.
159// See: https://code.google.com/p/webrtc/issues/detail?id=5054
160std::vector<cricket::StreamParams> GetActiveStreams(
161 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800162 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700163 ? desc->streams()
164 : std::vector<cricket::StreamParams>();
165}
166
deadbeefab9b2d12015-10-14 11:33:11 -0700167bool IsValidOfferToReceiveMedia(int value) {
168 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
169 return (value >= Options::kUndefined) &&
170 (value <= Options::kMaxOfferToReceiveMedia);
171}
172
zhihuang1c378ed2017-08-17 14:10:50 -0700173// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800174void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700175 const std::vector<rtc::scoped_refptr<
176 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700177 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200178 cricket::MediaDescriptionOptions* video_media_description_options,
179 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700180 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700181 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
182 if (audio_media_description_options) {
183 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700184 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700185 }
186 } else {
187 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
188 if (video_media_description_options) {
189 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800190 sender->id(), sender->internal()->stream_ids(), {},
191 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700192 }
193 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700194 }
zhihuang1c378ed2017-08-17 14:10:50 -0700195}
olka3c747662017-08-17 06:50:32 -0700196
zhihuang1c378ed2017-08-17 14:10:50 -0700197// Add options to |session_options| from |rtp_data_channels|.
198void AddRtpDataChannelOptions(
199 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
200 rtp_data_channels,
201 cricket::MediaDescriptionOptions* data_media_description_options) {
202 if (!data_media_description_options) {
203 return;
204 }
deadbeefab9b2d12015-10-14 11:33:11 -0700205 // Check for data channels.
206 for (const auto& kv : rtp_data_channels) {
207 const DataChannel* channel = kv.second;
208 if (channel->state() == DataChannel::kConnecting ||
209 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700210 // Legacy RTP data channels are signaled with the track/stream ID set to
211 // the data channel's label.
212 data_media_description_options->AddRtpDataChannel(channel->label(),
213 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700214 }
215 }
216}
217
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700218uint32_t ConvertIceTransportTypeToCandidateFilter(
219 PeerConnectionInterface::IceTransportsType type) {
220 switch (type) {
221 case PeerConnectionInterface::kNone:
222 return cricket::CF_NONE;
223 case PeerConnectionInterface::kRelay:
224 return cricket::CF_RELAY;
225 case PeerConnectionInterface::kNoHost:
226 return (cricket::CF_ALL & ~cricket::CF_HOST);
227 case PeerConnectionInterface::kAll:
228 return cricket::CF_ALL;
229 default:
nissec80e7412017-01-11 05:56:46 -0800230 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700231 }
232 return cricket::CF_NONE;
233}
234
deadbeef293e9262017-01-11 12:28:30 -0800235// Helper to set an error and return from a method.
236bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
237 if (error) {
238 error->set_type(type);
239 }
240 return type == webrtc::RTCErrorType::NONE;
241}
242
Steve Anton038834f2017-07-14 15:59:59 -0700243bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700244 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700245 if (error_out) {
246 *error_out = std::move(error);
247 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700248 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700249}
250
Steve Antonba818672017-11-06 10:21:57 -0800251std::string GetSignalingStateString(
252 PeerConnectionInterface::SignalingState state) {
253 switch (state) {
254 case PeerConnectionInterface::kStable:
255 return "kStable";
256 case PeerConnectionInterface::kHaveLocalOffer:
257 return "kHaveLocalOffer";
258 case PeerConnectionInterface::kHaveLocalPrAnswer:
259 return "kHavePrAnswer";
260 case PeerConnectionInterface::kHaveRemoteOffer:
261 return "kHaveRemoteOffer";
262 case PeerConnectionInterface::kHaveRemotePrAnswer:
263 return "kHaveRemotePrAnswer";
264 case PeerConnectionInterface::kClosed:
265 return "kClosed";
266 }
267 RTC_NOTREACHED();
268 return "";
269}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270
Steve Anton75737c02017-11-06 10:37:17 -0800271IceCandidatePairType GetIceCandidatePairCounter(
272 const cricket::Candidate& local,
273 const cricket::Candidate& remote) {
274 const auto& l = local.type();
275 const auto& r = remote.type();
276 const auto& host = LOCAL_PORT_TYPE;
277 const auto& srflx = STUN_PORT_TYPE;
278 const auto& relay = RELAY_PORT_TYPE;
279 const auto& prflx = PRFLX_PORT_TYPE;
280 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800281 bool local_hostname =
282 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
283 bool remote_hostname = !remote.address().hostname().empty() &&
284 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800285 bool local_private = IPIsPrivate(local.address().ipaddr());
286 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800287 if (local_hostname) {
288 if (remote_hostname) {
289 return kIceCandidatePairHostNameHostName;
290 } else if (remote_private) {
291 return kIceCandidatePairHostNameHostPrivate;
292 } else {
293 return kIceCandidatePairHostNameHostPublic;
294 }
295 } else if (local_private) {
296 if (remote_hostname) {
297 return kIceCandidatePairHostPrivateHostName;
298 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800299 return kIceCandidatePairHostPrivateHostPrivate;
300 } else {
301 return kIceCandidatePairHostPrivateHostPublic;
302 }
303 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800304 if (remote_hostname) {
305 return kIceCandidatePairHostPublicHostName;
306 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800307 return kIceCandidatePairHostPublicHostPrivate;
308 } else {
309 return kIceCandidatePairHostPublicHostPublic;
310 }
311 }
312 }
313 if (l == host && r == srflx)
314 return kIceCandidatePairHostSrflx;
315 if (l == host && r == relay)
316 return kIceCandidatePairHostRelay;
317 if (l == host && r == prflx)
318 return kIceCandidatePairHostPrflx;
319 if (l == srflx && r == host)
320 return kIceCandidatePairSrflxHost;
321 if (l == srflx && r == srflx)
322 return kIceCandidatePairSrflxSrflx;
323 if (l == srflx && r == relay)
324 return kIceCandidatePairSrflxRelay;
325 if (l == srflx && r == prflx)
326 return kIceCandidatePairSrflxPrflx;
327 if (l == relay && r == host)
328 return kIceCandidatePairRelayHost;
329 if (l == relay && r == srflx)
330 return kIceCandidatePairRelaySrflx;
331 if (l == relay && r == relay)
332 return kIceCandidatePairRelayRelay;
333 if (l == relay && r == prflx)
334 return kIceCandidatePairRelayPrflx;
335 if (l == prflx && r == host)
336 return kIceCandidatePairPrflxHost;
337 if (l == prflx && r == srflx)
338 return kIceCandidatePairPrflxSrflx;
339 if (l == prflx && r == relay)
340 return kIceCandidatePairPrflxRelay;
341 return kIceCandidatePairMax;
342}
343
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800344// Logic to decide if an m= section can be recycled. This means that the new
345// m= section is not rejected, but the old local or remote m= section is
346// rejected. |old_content_one| and |old_content_two| refer to the m= section
347// of the old remote and old local descriptions in no particular order.
348// We need to check both the old local and remote because either
349// could be the most current from the latest negotation.
350bool IsMediaSectionBeingRecycled(SdpType type,
351 const ContentInfo& content,
352 const ContentInfo* old_content_one,
353 const ContentInfo* old_content_two) {
354 return type == SdpType::kOffer && !content.rejected &&
355 ((old_content_one && old_content_one->rejected) ||
356 (old_content_two && old_content_two->rejected));
357}
358
Steve Anton75737c02017-11-06 10:37:17 -0800359// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800360// |current_desc|. The number of m= sections in |new_desc| should be no
361// less than |current_desc|. In the case of checking an answer's
362// |new_desc|, the |current_desc| is the last offer that was set as the
363// local or remote. In the case of checking an offer's |new_desc| we
364// check against the local and remote descriptions stored from the last
365// negotiation, because either of these could be the most up to date for
366// possible rejected m sections. These are the |current_desc| and
367// |secondary_current_desc|.
368bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
369 const SessionDescription* secondary_current_desc,
370 const SessionDescription& new_desc,
371 const SdpType type) {
372 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
377 const cricket::ContentInfo* secondary_content_info = nullptr;
378 if (secondary_current_desc &&
379 i < secondary_current_desc->contents().size()) {
380 secondary_content_info = &secondary_current_desc->contents()[i];
381 }
382 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
383 &current_desc.contents()[i],
384 secondary_content_info)) {
385 // For new offer descriptions, if the media section can be recycled, it's
386 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800387 continue;
388 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800389 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800390 return false;
391 }
392 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800393 new_desc.contents()[i].media_description();
394 const MediaContentDescription* current_desc_mdesc =
395 current_desc.contents()[i].media_description();
396 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399 }
400 return true;
401}
402
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800403bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
404 const SessionDescription& desc2) {
405 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800406}
407
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700408void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
409 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200410 // Array of structs needed to map {KeyExchangeProtocolType,
411 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
412 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
413 static constexpr struct {
414 KeyExchangeProtocolType protocol_type;
415 cricket::MediaType media_type;
416 KeyExchangeProtocolMedia protocol_media;
417 } kEnumCounterKeyProtocolMediaMap[] = {
418 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
419 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
420 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
421 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
422 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
423 kEnumCounterKeyProtocolMediaTypeDtlsData},
424 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
425 kEnumCounterKeyProtocolMediaTypeSdesAudio},
426 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
427 kEnumCounterKeyProtocolMediaTypeSdesVideo},
428 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
429 kEnumCounterKeyProtocolMediaTypeSdesData},
430 };
431
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700432 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
433 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100434
Mirko Bonadeiab499822018-09-11 10:43:20 +0200435 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
436 if (i.protocol_type == protocol_type && i.media_type == media_type) {
437 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
438 i.protocol_media,
439 kEnumCounterKeyProtocolMediaTypeMax);
440 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100441 }
442}
443
Harald Alvestrand76829d72018-07-18 23:24:36 +0200444void NoteAddIceCandidateResult(int result) {
445 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
446 kAddIceCandidateMax);
447}
448
Steve Anton75737c02017-11-06 10:37:17 -0800449// Checks that each non-rejected content has SDES crypto keys or a DTLS
450// fingerprint, unless it's in a BUNDLE group, in which case only the
451// BUNDLE-tag section (first media section/description in the BUNDLE group)
452// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
453// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
454// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700455RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800456 const cricket::ContentGroup* bundle =
457 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800458 for (const cricket::ContentInfo& content_info : desc->contents()) {
459 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800460 continue;
461 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100462 // Note what media is used with each crypto protocol, for all sections.
463 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
464 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700465 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800466 const std::string& mid = content_info.name;
467 if (bundle && bundle->HasContentName(mid) &&
468 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800469 // This isn't the first media section in the BUNDLE group, so it's not
470 // required to have crypto attributes, since only the crypto attributes
471 // from the first section actually get used.
472 continue;
473 }
474
475 // If the content isn't rejected or bundled into another m= section, crypto
476 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800477 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800478 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800479 if (!media || !tinfo) {
480 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800482 }
483 if (dtls_enabled) {
484 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100485 RTC_LOG(LS_WARNING)
486 << "Session description must have DTLS fingerprint if "
487 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800488 return RTCError(RTCErrorType::INVALID_PARAMETER,
489 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800490 }
491 } else {
492 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100493 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800494 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800495 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800496 }
497 }
498 }
Steve Anton8a006912017-12-04 15:25:56 -0800499 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800500}
501
502// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
503// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
504// media section/description in the BUNDLE group) needs a ufrag and pwd.
505bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
506 const cricket::ContentGroup* bundle =
507 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800508 for (const cricket::ContentInfo& content_info : desc->contents()) {
509 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800510 continue;
511 }
Steve Anton8a006912017-12-04 15:25:56 -0800512 const std::string& mid = content_info.name;
513 if (bundle && bundle->HasContentName(mid) &&
514 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800515 // This isn't the first media section in the BUNDLE group, so it's not
516 // required to have ufrag/password, since only the ufrag/password from
517 // the first section actually get used.
518 continue;
519 }
520
521 // If the content isn't rejected or bundled into another m= section,
522 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800523 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800524 if (!tinfo) {
525 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100526 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800527 return false;
528 }
529 if (tinfo->description.ice_ufrag.empty() ||
530 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100531 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800532 return false;
533 }
534 }
535 return true;
536}
537
Steve Anton75737c02017-11-06 10:37:17 -0800538// Get the SCTP port out of a SessionDescription.
539// Return -1 if not found.
540int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800541 const cricket::DataContentDescription* data_desc =
542 GetFirstDataContentDescription(session_description);
543 RTC_DCHECK(data_desc);
544 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800545 return -1;
546 }
Steve Anton75737c02017-11-06 10:37:17 -0800547 std::string value;
548 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
549 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800550 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800551 if (!codec.Matches(match_pattern)) {
552 continue;
553 }
554 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
555 return rtc::FromString<int>(value);
556 }
557 }
558 return -1;
559}
560
Steve Anton75737c02017-11-06 10:37:17 -0800561// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
562bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
563 const SessionDescriptionInterface* new_desc,
564 const std::string& content_name) {
565 if (!old_desc) {
566 return false;
567 }
568 const SessionDescription* new_sd = new_desc->description();
569 const SessionDescription* old_sd = old_desc->description();
570 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
571 if (!cinfo || cinfo->rejected) {
572 return false;
573 }
574 // If the content isn't rejected, check if ufrag and password has changed.
575 const cricket::TransportDescription* new_transport_desc =
576 new_sd->GetTransportDescriptionByName(content_name);
577 const cricket::TransportDescription* old_transport_desc =
578 old_sd->GetTransportDescriptionByName(content_name);
579 if (!new_transport_desc || !old_transport_desc) {
580 // No transport description exists. This is not an ICE restart.
581 return false;
582 }
583 if (cricket::IceCredentialsChanged(
584 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
585 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100586 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
587 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800588 return true;
589 }
590 return false;
591}
592
Steve Anton80dd7b52018-02-16 17:08:42 -0800593// Generates a string error message for SetLocalDescription/SetRemoteDescription
594// from an RTCError.
595std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
596 SdpType type,
597 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200598 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800599 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
600 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200601 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800602}
603
Seth Hampson5b4f0752018-04-02 16:31:36 -0700604std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
605 std::string output = "streams=[";
606 const char* separator = "";
607 for (const auto& stream_id : stream_ids) {
608 output.append(separator).append(stream_id);
609 separator = ", ";
610 }
611 output.append("]");
612 return output;
613}
614
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200615absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700616 int rtc_configuration_parameter) {
617 if (rtc_configuration_parameter ==
618 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200619 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700620 }
621 return rtc_configuration_parameter;
622}
623
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800624cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
625 switch (type) {
626 case DataMessageType::kText:
627 return cricket::DMT_TEXT;
628 case DataMessageType::kBinary:
629 return cricket::DMT_BINARY;
630 case DataMessageType::kControl:
631 return cricket::DMT_CONTROL;
632 default:
633 return cricket::DMT_NONE;
634 }
635 return cricket::DMT_NONE;
636}
637
638DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
639 switch (type) {
640 case cricket::DMT_TEXT:
641 return DataMessageType::kText;
642 case cricket::DMT_BINARY:
643 return DataMessageType::kBinary;
644 case cricket::DMT_CONTROL:
645 return DataMessageType::kControl;
646 case cricket::DMT_NONE:
647 default:
648 RTC_NOTREACHED();
649 }
650 return DataMessageType::kControl;
651}
652
Steve Anton75737c02017-11-06 10:37:17 -0800653} // namespace
654
Henrik Boström31638672017-11-23 17:48:32 +0100655// Upon completion, posts a task to execute the callback of the
656// SetSessionDescriptionObserver asynchronously on the same thread. At this
657// point, the state of the peer connection might no longer reflect the effects
658// of the SetRemoteDescription operation, as the peer connection could have been
659// modified during the post.
660// TODO(hbos): Remove this class once we remove the version of
661// PeerConnectionInterface::SetRemoteDescription() that takes a
662// SetSessionDescriptionObserver as an argument.
663class PeerConnection::SetRemoteDescriptionObserverAdapter
664 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
665 public:
666 SetRemoteDescriptionObserverAdapter(
667 rtc::scoped_refptr<PeerConnection> pc,
668 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
669 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
670
671 // SetRemoteDescriptionObserverInterface implementation.
672 void OnSetRemoteDescriptionComplete(RTCError error) override {
673 if (error.ok())
674 pc_->PostSetSessionDescriptionSuccess(wrapper_);
675 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100676 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100677 }
678
679 private:
680 rtc::scoped_refptr<PeerConnection> pc_;
681 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
682};
683
deadbeef293e9262017-01-11 12:28:30 -0800684bool PeerConnectionInterface::RTCConfiguration::operator==(
685 const PeerConnectionInterface::RTCConfiguration& o) const {
686 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700687 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800688 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000689 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700690 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800691 BundlePolicy bundle_policy;
692 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700693 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
694 int ice_candidate_pool_size;
695 bool disable_ipv6;
696 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700697 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100698 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700699 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200700 absl::optional<int> screencast_min_bitrate;
701 absl::optional<bool> combined_audio_video_bwe;
702 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800703 TcpCandidatePolicy tcp_candidate_policy;
704 CandidateNetworkPolicy candidate_network_policy;
705 int audio_jitter_buffer_max_packets;
706 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100707 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100708 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800709 int ice_connection_receiving_timeout;
710 int ice_backup_candidate_pair_ping_interval;
711 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800712 bool prioritize_most_likely_ice_candidate_pairs;
713 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800714 bool prune_turn_ports;
715 bool presume_writable_when_fully_relayed;
716 bool enable_ice_renomination;
717 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200718 absl::optional<int> ice_check_interval_strong_connectivity;
719 absl::optional<int> ice_check_interval_weak_connectivity;
720 absl::optional<int> ice_check_min_interval;
721 absl::optional<int> ice_unwritable_timeout;
722 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800723 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200724 absl::optional<int> stun_candidate_keepalive_interval;
725 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200726 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800727 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200728 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700729 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700730 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700731 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700732 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100733 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800734 };
735 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
736 "Did you add something to RTCConfiguration and forget to "
737 "update operator==?");
738 return type == o.type && servers == o.servers &&
739 bundle_policy == o.bundle_policy &&
740 rtcp_mux_policy == o.rtcp_mux_policy &&
741 tcp_candidate_policy == o.tcp_candidate_policy &&
742 candidate_network_policy == o.candidate_network_policy &&
743 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
744 audio_jitter_buffer_fast_accelerate ==
745 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100746 audio_jitter_buffer_min_delay_ms ==
747 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100748 audio_jitter_buffer_enable_rtx_handling ==
749 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800750 ice_connection_receiving_timeout ==
751 o.ice_connection_receiving_timeout &&
752 ice_backup_candidate_pair_ping_interval ==
753 o.ice_backup_candidate_pair_ping_interval &&
754 continual_gathering_policy == o.continual_gathering_policy &&
755 certificates == o.certificates &&
756 prioritize_most_likely_ice_candidate_pairs ==
757 o.prioritize_most_likely_ice_candidate_pairs &&
758 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800759 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700760 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100761 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800762 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800763 screencast_min_bitrate == o.screencast_min_bitrate &&
764 combined_audio_video_bwe == o.combined_audio_video_bwe &&
765 enable_dtls_srtp == o.enable_dtls_srtp &&
766 ice_candidate_pool_size == o.ice_candidate_pool_size &&
767 prune_turn_ports == o.prune_turn_ports &&
768 presume_writable_when_fully_relayed ==
769 o.presume_writable_when_fully_relayed &&
770 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800771 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800772 ice_check_interval_strong_connectivity ==
773 o.ice_check_interval_strong_connectivity &&
774 ice_check_interval_weak_connectivity ==
775 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700776 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700777 ice_unwritable_timeout == o.ice_unwritable_timeout &&
778 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800779 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800780 stun_candidate_keepalive_interval ==
781 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200782 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800783 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800784 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700785 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700786 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700787 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700788 use_media_transport_for_data_channels ==
789 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100790 crypto_options == o.crypto_options &&
791 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800792}
793
794bool PeerConnectionInterface::RTCConfiguration::operator!=(
795 const PeerConnectionInterface::RTCConfiguration& o) const {
796 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800797}
798
zhihuang8f65cdf2016-05-06 18:40:30 -0700799// Generate a RTCP CNAME when a PeerConnection is created.
800std::string GenerateRtcpCname() {
801 std::string cname;
802 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100803 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800804 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700805 }
806 return cname;
807}
808
zhihuang1c378ed2017-08-17 14:10:50 -0700809bool ValidateOfferAnswerOptions(
810 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
811 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
812 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700813}
814
zhihuang1c378ed2017-08-17 14:10:50 -0700815// From |rtc_options|, fill parts of |session_options| shared by all generated
816// m= sections (in other words, nothing that involves a map/array).
817void ExtractSharedMediaSessionOptions(
818 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
819 cricket::MediaSessionOptions* session_options) {
820 session_options->vad_enabled = rtc_options.voice_activity_detection;
821 session_options->bundle_enabled = rtc_options.use_rtp_mux;
822}
zhihuanga77e6bb2017-08-14 18:17:48 -0700823
zhihuang38ede132017-06-15 12:52:32 -0700824PeerConnection::PeerConnection(PeerConnectionFactory* factory,
825 std::unique_ptr<RtcEventLog> event_log,
826 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700828 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700829 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700830 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700831 remote_streams_(StreamCollection::Create()),
832 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833
834PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100835 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800836 RTC_DCHECK_RUN_ON(signaling_thread());
837
Steve Anton8af21862017-12-15 11:20:13 -0800838 // Need to stop transceivers before destroying the stats collector because
839 // AudioRtpSender has a reference to the StatsCollector it will update when
840 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100841 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800842 transceiver->Stop();
843 }
Steve Anton4171afb2017-11-20 10:20:22 -0800844
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700845 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800846 if (stats_collector_) {
847 stats_collector_->WaitForPendingRequest();
848 stats_collector_ = nullptr;
849 }
Steve Anton75737c02017-11-06 10:37:17 -0800850
Steve Anton8af21862017-12-15 11:20:13 -0800851 // Don't destroy BaseChannels until after stats has been cleaned up so that
852 // the last stats request can still read from the channels.
853 DestroyAllChannels();
854
Mirko Bonadei675513b2017-11-09 11:09:25 +0100855 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800856
857 webrtc_session_desc_factory_.reset();
858 sctp_invoker_.reset();
859 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800860 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800861 transport_controller_.reset();
862
deadbeef91dd5672016-05-18 16:55:30 -0700863 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700864 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700865 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700866 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700867 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700868 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800869 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700870 event_log_.reset();
871 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872}
873
Steve Anton8af21862017-12-15 11:20:13 -0800874void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800875 // Destroy video channels first since they may have a pointer to a voice
876 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100877 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800878 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800879 DestroyTransceiverChannel(transceiver);
880 }
881 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100882 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800883 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800884 DestroyTransceiverChannel(transceiver);
885 }
886 }
887 DestroyDataChannel();
888}
889
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000890bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000891 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700892 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100893 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700894
895 RTCError config_error = ValidateConfiguration(configuration);
896 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100897 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700898 return false;
899 }
900
Benjamin Wrightcab58882018-05-02 15:12:47 -0700901 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100902 RTC_LOG(LS_ERROR)
903 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100904 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800905 return false;
906 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200907
Benjamin Wrightcab58882018-05-02 15:12:47 -0700908 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800909 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100910 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100911 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800912 return false;
913 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700914
Benjamin Wrightcab58882018-05-02 15:12:47 -0700915 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700916 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700917 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700918 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800919
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200920 cricket::ServerAddresses stun_servers;
921 std::vector<cricket::RelayServerConfig> turn_servers;
922
923 RTCErrorType parse_error =
924 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
925 if (parse_error != RTCErrorType::NONE) {
926 return false;
927 }
928
deadbeef91dd5672016-05-18 16:55:30 -0700929 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700930 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700931 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200932 RTC_FROM_HERE,
933 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
934 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 return false;
936 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200937 // If initialization was successful, note if STUN or TURN servers
938 // were supplied.
939 if (!stun_servers.empty()) {
940 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
941 }
942 if (!turn_servers.empty()) {
943 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
944 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700946 // Send information about IPv4/IPv6 status.
947 PeerConnectionAddressFamilyCounter address_family;
948 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
949 address_family = kPeerConnection_IPv6;
950 } else {
951 address_family = kPeerConnection_IPv4;
952 }
953 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
954 kPeerConnectionAddressFamilyCounter_Max);
955
Zhi Huange830e682018-03-30 10:48:35 -0700956 const PeerConnectionFactoryInterface::Options& options = factory_->options();
957
Steve Anton75737c02017-11-06 10:37:17 -0800958 // RFC 3264: The numeric value of the session id and version in the
959 // o line MUST be representable with a "64 bit signed integer".
960 // Due to this constraint session id |session_id_| is max limited to
961 // LLONG_MAX.
962 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700963 JsepTransportController::Config config;
964 config.redetermine_role_on_ice_restart =
965 configuration.redetermine_role_on_ice_restart;
966 config.ssl_max_version = factory_->options().ssl_max_version;
967 config.disable_encryption = options.disable_encryption;
968 config.bundle_policy = configuration.bundle_policy;
969 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700970 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
971 // stub.
972 config.crypto_options = configuration.crypto_options.has_value()
973 ? *configuration.crypto_options
974 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700975 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700976 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700977#if defined(ENABLE_EXTERNAL_AUTH)
978 config.enable_external_auth = true;
979#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700980 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700981
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700982 if (configuration.use_media_transport ||
983 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700984 if (!factory_->media_transport_factory()) {
985 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700986 << "PeerConnecton is initialized with use_media_transport = true or "
987 << "use_media_transport_for_data_channels = true "
988 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700989 return false;
990 }
991
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -0800992 config.use_media_transport_for_media = configuration.use_media_transport;
993 config.use_media_transport_for_data_channels =
994 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700995 config.media_transport_factory = factory_->media_transport_factory();
996 }
997
Zhi Huange830e682018-03-30 10:48:35 -0700998 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700999 signaling_thread(), network_thread(), port_allocator_.get(),
1000 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001001 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001002 this, &PeerConnection::OnTransportControllerConnectionState);
1003 transport_controller_->SignalStandardizedIceConnectionState.connect(
1004 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001005 transport_controller_->SignalConnectionState.connect(
1006 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001007 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001008 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001009 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001010 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001011 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001012 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1013 transport_controller_->SignalDtlsHandshakeError.connect(
1014 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1015
1016 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001017
deadbeefab9b2d12015-10-14 11:33:11 -07001018 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001019 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020
Steve Antonba818672017-11-06 10:21:57 -08001021 configuration_ = configuration;
1022
Steve Anton75737c02017-11-06 10:37:17 -08001023 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1024 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1025 if (!configuration.certificates.empty()) {
1026 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1027 // just picking the first one. The decision should be made based on the DTLS
1028 // handshake. The DTLS negotiations need to know about all certificates.
1029 certificate = configuration.certificates[0];
1030 }
1031
Steve Antond25da372017-11-06 14:50:29 -08001032 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001033
1034 if (options.disable_encryption) {
1035 dtls_enabled_ = false;
1036 } else {
1037 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001038 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001039 // |configuration| can override the default |dtls_enabled_| value.
1040 if (configuration.enable_dtls_srtp) {
1041 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1042 }
1043 }
1044
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001045 if (configuration.use_media_transport_for_data_channels) {
1046 if (configuration.enable_rtp_data_channel) {
1047 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1048 "use_media_transport_for_data_channels are "
1049 "incompatible and cannot both be set to true";
1050 return false;
1051 }
1052 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1053 } else if (configuration.enable_rtp_data_channel) {
1054 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1055 // set. It takes precendence over the disable_sctp_data_channels
1056 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001057 data_channel_type_ = cricket::DCT_RTP;
1058 } else {
1059 // DTLS has to be enabled to use SCTP.
1060 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1061 data_channel_type_ = cricket::DCT_SCTP;
1062 }
1063 }
1064
1065 video_options_.screencast_min_bitrate_kbps =
1066 configuration.screencast_min_bitrate;
1067 audio_options_.combined_audio_video_bwe =
1068 configuration.combined_audio_video_bwe;
1069
1070 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001071 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001072
1073 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001074 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001075
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001076 audio_options_.audio_jitter_buffer_min_delay_ms =
1077 configuration.audio_jitter_buffer_min_delay_ms;
1078
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001079 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1080 configuration.audio_jitter_buffer_enable_rtx_handling;
1081
Steve Anton75737c02017-11-06 10:37:17 -08001082 // Whether the certificate generator/certificate is null or not determines
1083 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1084 // the right instructions by clearing the variables if needed.
1085 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001086 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001087 certificate = nullptr;
1088 } else if (certificate) {
1089 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001090 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001091 }
1092
1093 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1094 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001095 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001096 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1097 this, &PeerConnection::OnCertificateReady);
1098
1099 if (options.disable_encryption) {
1100 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1101 }
1102
1103 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001104 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001105 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106
Steve Anton4171afb2017-11-20 10:20:22 -08001107 // Add default audio/video transceivers for Plan B SDP.
1108 if (!IsUnifiedPlan()) {
1109 transceivers_.push_back(
1110 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1111 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1112 transceivers_.push_back(
1113 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1114 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1115 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001116 int delay_ms =
1117 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001118 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1119 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001120 return true;
1121}
1122
Steve Anton038834f2017-07-14 15:59:59 -07001123RTCError PeerConnection::ValidateConfiguration(
1124 const RTCConfiguration& config) const {
1125 if (config.ice_regather_interval_range &&
1126 config.continual_gathering_policy == GATHER_ONCE) {
1127 return RTCError(RTCErrorType::INVALID_PARAMETER,
1128 "ice_regather_interval_range specified but continual "
1129 "gathering policy is GATHER_ONCE");
1130 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001131 auto result =
1132 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1133 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001134}
1135
Yves Gerey665174f2018-06-19 15:03:05 +02001136rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001137 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1138 "Plan SdpSemantics. Please use GetSenders "
1139 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001140 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001141}
1142
Yves Gerey665174f2018-06-19 15:03:05 +02001143rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001144 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1145 "Plan SdpSemantics. Please use GetReceivers "
1146 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001147 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148}
1149
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001150bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001151 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1152 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001153 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 if (IsClosed()) {
1155 return false;
1156 }
deadbeefab9b2d12015-10-14 11:33:11 -07001157 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158 return false;
1159 }
deadbeefab9b2d12015-10-14 11:33:11 -07001160
1161 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001162 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1163 observer->SignalAudioTrackAdded.connect(this,
1164 &PeerConnection::OnAudioTrackAdded);
1165 observer->SignalAudioTrackRemoved.connect(
1166 this, &PeerConnection::OnAudioTrackRemoved);
1167 observer->SignalVideoTrackAdded.connect(this,
1168 &PeerConnection::OnVideoTrackAdded);
1169 observer->SignalVideoTrackRemoved.connect(
1170 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001171 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001172
deadbeefab9b2d12015-10-14 11:33:11 -07001173 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001174 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001175 }
1176 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001177 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001178 }
1179
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001180 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001181 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001182 return true;
1183}
1184
1185void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001186 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1187 "Plan SdpSemantics. Please use RemoveTrack "
1188 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001189 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001190 if (!IsClosed()) {
1191 for (const auto& track : local_stream->GetAudioTracks()) {
1192 RemoveAudioTrack(track.get(), local_stream);
1193 }
1194 for (const auto& track : local_stream->GetVideoTracks()) {
1195 RemoveVideoTrack(track.get(), local_stream);
1196 }
deadbeefab9b2d12015-10-14 11:33:11 -07001197 }
deadbeefab9b2d12015-10-14 11:33:11 -07001198 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001199 stream_observers_.erase(
1200 std::remove_if(
1201 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001202 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001203 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001204 }),
1205 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001206
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001207 if (IsClosed()) {
1208 return;
1209 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001210 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211}
1212
Steve Anton2d6c76a2018-01-05 17:10:52 -08001213RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001214 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001215 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001216 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001217 if (!track) {
1218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1219 }
1220 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1221 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1222 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1223 "Track has invalid kind: " + track->kind());
1224 }
Steve Antonf9381f02017-12-14 10:23:57 -08001225 if (IsClosed()) {
1226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1227 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001228 }
Steve Anton4171afb2017-11-20 10:20:22 -08001229 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001230 LOG_AND_RETURN_ERROR(
1231 RTCErrorType::INVALID_PARAMETER,
1232 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001233 }
Steve Antonf9381f02017-12-14 10:23:57 -08001234 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001235 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1236 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001237 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001238 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001239 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001240 }
1241 return sender_or_error;
1242}
deadbeefe1f9d832016-01-14 15:35:42 -08001243
Steve Antonf9381f02017-12-14 10:23:57 -08001244RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1245PeerConnection::AddTrackPlanB(
1246 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001247 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001248 if (stream_ids.size() > 1u) {
1249 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1250 "AddTrack with more than one stream is not "
1251 "supported with Plan B semantics.");
1252 }
1253 std::vector<std::string> adjusted_stream_ids = stream_ids;
1254 if (adjusted_stream_ids.empty()) {
1255 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1256 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001257 cricket::MediaType media_type =
1258 (track->kind() == MediaStreamTrackInterface::kAudioKind
1259 ? cricket::MEDIA_TYPE_AUDIO
1260 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001261 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001262 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001263 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001264 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001265 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001266 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001267 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001268 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001269 if (sender_info) {
1270 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001271 }
Steve Antonf9381f02017-12-14 10:23:57 -08001272 } else {
1273 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001274 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001275 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001276 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001277 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001278 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001279 if (sender_info) {
1280 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001281 }
deadbeefe1f9d832016-01-14 15:35:42 -08001282 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001283 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001284}
deadbeefe1f9d832016-01-14 15:35:42 -08001285
Steve Antonf9381f02017-12-14 10:23:57 -08001286RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1287PeerConnection::AddTrackUnifiedPlan(
1288 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001289 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001290 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1291 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001292 RTC_LOG(LS_INFO) << "Reusing an existing "
1293 << cricket::MediaTypeToString(transceiver->media_type())
1294 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001295 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001296 transceiver->internal()->set_direction(
1297 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001298 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001299 transceiver->internal()->set_direction(
1300 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001301 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001302 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001303 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001304 } else {
1305 cricket::MediaType media_type =
1306 (track->kind() == MediaStreamTrackInterface::kAudioKind
1307 ? cricket::MEDIA_TYPE_AUDIO
1308 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001309 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1310 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001311 std::string sender_id = track->id();
1312 // Avoid creating a sender with an existing ID by generating a random ID.
1313 // This can happen if this is the second time AddTrack has created a sender
1314 // for this track.
1315 if (FindSenderById(sender_id)) {
1316 sender_id = rtc::CreateRandomUuid();
1317 }
Florent Castelli892acf02018-10-01 22:47:20 +02001318 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001319 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1320 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001321 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001322 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001323 }
Steve Antonf9381f02017-12-14 10:23:57 -08001324 return transceiver->sender();
1325}
1326
1327rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1328PeerConnection::FindFirstTransceiverForAddedTrack(
1329 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1330 RTC_DCHECK(track);
1331 for (auto transceiver : transceivers_) {
1332 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001333 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001334 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001335 !transceiver->internal()->has_ever_been_used_to_send() &&
1336 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001337 return transceiver;
1338 }
1339 }
1340 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001341}
1342
1343bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1344 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001345 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001346}
1347
Steve Anton24db5732018-07-23 10:27:33 -07001348RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001349 rtc::scoped_refptr<RtpSenderInterface> sender) {
1350 if (!sender) {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1352 }
deadbeefe1f9d832016-01-14 15:35:42 -08001353 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001354 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1355 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001356 }
Steve Antonf9381f02017-12-14 10:23:57 -08001357 if (IsUnifiedPlan()) {
1358 auto transceiver = FindTransceiverBySender(sender);
1359 if (!transceiver || !sender->track()) {
1360 return RTCError::OK();
1361 }
1362 sender->SetTrack(nullptr);
1363 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001364 transceiver->internal()->set_direction(
1365 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001366 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001367 transceiver->internal()->set_direction(
1368 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001369 }
Steve Anton4171afb2017-11-20 10:20:22 -08001370 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001371 bool removed;
1372 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1373 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1374 } else {
1375 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1376 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1377 }
1378 if (!removed) {
1379 LOG_AND_RETURN_ERROR(
1380 RTCErrorType::INVALID_PARAMETER,
1381 "Couldn't find sender " + sender->id() + " to remove.");
1382 }
Steve Anton4171afb2017-11-20 10:20:22 -08001383 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001384 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001385 return RTCError::OK();
1386}
1387
1388rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1389PeerConnection::FindTransceiverBySender(
1390 rtc::scoped_refptr<RtpSenderInterface> sender) {
1391 for (auto transceiver : transceivers_) {
1392 if (transceiver->sender() == sender) {
1393 return transceiver;
1394 }
1395 }
1396 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001397}
1398
Steve Anton9158ef62017-11-27 13:01:52 -08001399RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1400PeerConnection::AddTransceiver(
1401 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1402 return AddTransceiver(track, RtpTransceiverInit());
1403}
1404
1405RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1406PeerConnection::AddTransceiver(
1407 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1408 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001409 RTC_CHECK(IsUnifiedPlan())
1410 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001411 if (!track) {
1412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1413 }
1414 cricket::MediaType media_type;
1415 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1416 media_type = cricket::MEDIA_TYPE_AUDIO;
1417 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1418 media_type = cricket::MEDIA_TYPE_VIDEO;
1419 } else {
1420 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1421 "Track kind is not audio or video");
1422 }
1423 return AddTransceiver(media_type, track, init);
1424}
1425
1426RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1427PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1428 return AddTransceiver(media_type, RtpTransceiverInit());
1429}
1430
1431RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1432PeerConnection::AddTransceiver(cricket::MediaType media_type,
1433 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001434 RTC_CHECK(IsUnifiedPlan())
1435 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001436 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1437 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1438 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1439 "media type is not audio or video");
1440 }
1441 return AddTransceiver(media_type, nullptr, init);
1442}
1443
1444RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1445PeerConnection::AddTransceiver(
1446 cricket::MediaType media_type,
1447 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001448 const RtpTransceiverInit& init,
1449 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001450 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1451 media_type == cricket::MEDIA_TYPE_VIDEO));
1452 if (track) {
1453 RTC_DCHECK_EQ(media_type,
1454 (track->kind() == MediaStreamTrackInterface::kAudioKind
1455 ? cricket::MEDIA_TYPE_AUDIO
1456 : cricket::MEDIA_TYPE_VIDEO));
1457 }
1458
1459 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001460 if (init.send_encodings.size() > 1) {
1461 LOG_AND_RETURN_ERROR(
1462 RTCErrorType::UNSUPPORTED_PARAMETER,
1463 "Attempted to create an encoder with more than 1 encoding parameter.");
1464 }
1465
1466 for (const auto& encoding : init.send_encodings) {
1467 if (encoding.ssrc.has_value()) {
1468 LOG_AND_RETURN_ERROR(
1469 RTCErrorType::UNSUPPORTED_PARAMETER,
1470 "Attempted to set an unimplemented parameter of RtpParameters.");
1471 }
1472 }
1473
1474 RtpParameters parameters;
1475 parameters.encodings = init.send_encodings;
1476 if (UnimplementedRtpParameterHasValue(parameters)) {
1477 LOG_AND_RETURN_ERROR(
1478 RTCErrorType::UNSUPPORTED_PARAMETER,
1479 "Attempted to set an unimplemented parameter of RtpParameters.");
1480 }
Steve Anton9158ef62017-11-27 13:01:52 -08001481
Steve Anton3d954a62018-04-02 11:27:23 -07001482 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1483 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001484 // Set the sender ID equal to the track ID if the track is specified unless
1485 // that sender ID is already in use.
1486 std::string sender_id =
1487 (track && !FindSenderById(track->id()) ? track->id()
1488 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001489 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1490 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001491 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1492 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1493 transceiver->internal()->set_direction(init.direction);
1494
Steve Anton22da89f2018-01-25 13:58:07 -08001495 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001496 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001497 }
Steve Antonf9381f02017-12-14 10:23:57 -08001498
1499 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1500}
1501
Steve Anton02ee47c2018-01-10 16:26:06 -08001502rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1503PeerConnection::CreateSender(
1504 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001505 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001506 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001507 const std::vector<std::string>& stream_ids,
1508 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001509 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001510 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1511 RTC_DCHECK(!track ||
1512 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1513 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1514 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001515 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001516 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001517 } else {
1518 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1519 RTC_DCHECK(!track ||
1520 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1521 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001522 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001523 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001524 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001525 bool set_track_succeeded = sender->SetTrack(track);
1526 RTC_DCHECK(set_track_succeeded);
1527 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001528 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001529 return sender;
1530}
1531
1532rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1533PeerConnection::CreateReceiver(cricket::MediaType media_type,
1534 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001535 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1536 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001537 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001538 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001539 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1540 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001541 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001542 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001543 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001544 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001545 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1546 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001547 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001548 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001549 return receiver;
1550}
1551
1552rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1553PeerConnection::CreateAndAddTransceiver(
1554 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1555 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1556 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001557 // Ensure that the new sender does not have an ID that is already in use by
1558 // another sender.
1559 // Allow receiver IDs to conflict since those come from remote SDP (which
1560 // could be invalid, but should not cause a crash).
1561 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001562 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1563 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001564 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001565 transceiver->internal()->SignalNegotiationNeeded.connect(
1566 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001567 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001568}
1569
Steve Anton52d86772018-02-20 15:48:12 -08001570void PeerConnection::OnNegotiationNeeded() {
1571 RTC_DCHECK_RUN_ON(signaling_thread());
1572 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001573 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001574}
1575
deadbeeffac06552015-11-25 11:26:01 -08001576rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001577 const std::string& kind,
1578 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001579 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1580 "Plan SdpSemantics. Please use AddTransceiver "
1581 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001582 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001583 if (IsClosed()) {
1584 return nullptr;
1585 }
Steve Anton4171afb2017-11-20 10:20:22 -08001586
Seth Hampson5b4f0752018-04-02 16:31:36 -07001587 // Internally we need to have one stream with Plan B semantics, so we
1588 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001589 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001590 if (stream_id.empty()) {
1591 stream_ids.push_back(rtc::CreateRandomUuid());
1592 RTC_LOG(LS_INFO)
1593 << "No stream_id specified for sender. Generated stream ID: "
1594 << stream_ids[0];
1595 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001596 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001597 }
1598
Steve Anton4171afb2017-11-20 10:20:22 -08001599 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001600 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001601 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001602 auto* audio_sender = new AudioRtpSender(
1603 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001604 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001605 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001606 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001607 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001608 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001609 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001610 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001611 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001612 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001613 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001614 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001615 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001616 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001617 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001618 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001619 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001620
deadbeefe1f9d832016-01-14 15:35:42 -08001621 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001622}
1623
deadbeef70ab1a12015-09-28 16:53:55 -07001624std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1625 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001626 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001627 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001628 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001629 }
1630 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001631}
1632
Steve Anton4171afb2017-11-20 10:20:22 -08001633std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1634PeerConnection::GetSendersInternal() const {
1635 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1636 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001637 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001638 auto senders = transceiver->internal()->senders();
1639 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1640 }
1641 return all_senders;
1642}
1643
deadbeef70ab1a12015-09-28 16:53:55 -07001644std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1645PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001646 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001647 for (const auto& receiver : GetReceiversInternal()) {
1648 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001649 }
1650 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001651}
1652
Steve Anton4171afb2017-11-20 10:20:22 -08001653std::vector<
1654 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1655PeerConnection::GetReceiversInternal() const {
1656 std::vector<
1657 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1658 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001659 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001660 auto receivers = transceiver->internal()->receivers();
1661 all_receivers.insert(all_receivers.end(), receivers.begin(),
1662 receivers.end());
1663 }
1664 return all_receivers;
1665}
1666
Steve Anton9158ef62017-11-27 13:01:52 -08001667std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1668PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001669 RTC_CHECK(IsUnifiedPlan())
1670 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001671 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001672 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001673 all_transceivers.push_back(transceiver);
1674 }
1675 return all_transceivers;
1676}
1677
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001678bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001679 MediaStreamTrackInterface* track,
1680 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001681 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001682 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001683 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001684 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685 return false;
1686 }
1687
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001688 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001689 // The StatsCollector is used to tell if a track is valid because it may
1690 // remember tracks that the PeerConnection previously removed.
1691 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001692 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1693 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001694 return false;
1695 }
Steve Antonad182762018-09-05 20:22:40 +00001696 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1697 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698 return true;
1699}
1700
hbos74e1a4f2016-09-15 23:33:01 -07001701void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001702 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001703 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001704 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001705 stats_collector_->GetStatsReport(callback);
1706}
1707
Henrik Boström1df1bf82018-03-20 13:24:20 +01001708void PeerConnection::GetStats(
1709 rtc::scoped_refptr<RtpSenderInterface> selector,
1710 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1711 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1712 RTC_DCHECK(callback);
1713 RTC_DCHECK(stats_collector_);
1714 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1715 if (selector) {
1716 for (const auto& proxy_transceiver : transceivers_) {
1717 for (const auto& proxy_sender :
1718 proxy_transceiver->internal()->senders()) {
1719 if (proxy_sender == selector) {
1720 internal_sender = proxy_sender->internal();
1721 break;
1722 }
1723 }
1724 if (internal_sender)
1725 break;
1726 }
1727 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001728 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001729 // belong to the PeerConnection (in Plan B, senders can be removed from the
1730 // PeerConnection). This means that "all the stats objects representing the
1731 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1732 // produces an empty stats report.
1733 stats_collector_->GetStatsReport(internal_sender, callback);
1734}
1735
1736void PeerConnection::GetStats(
1737 rtc::scoped_refptr<RtpReceiverInterface> selector,
1738 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1739 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1740 RTC_DCHECK(callback);
1741 RTC_DCHECK(stats_collector_);
1742 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1743 if (selector) {
1744 for (const auto& proxy_transceiver : transceivers_) {
1745 for (const auto& proxy_receiver :
1746 proxy_transceiver->internal()->receivers()) {
1747 if (proxy_receiver == selector) {
1748 internal_receiver = proxy_receiver->internal();
1749 break;
1750 }
1751 }
1752 if (internal_receiver)
1753 break;
1754 }
1755 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001756 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001757 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1758 // the PeerConnection). This means that "all the stats objects representing
1759 // the selector" is an empty set. Invoking GetStatsReport() with a null
1760 // selector produces an empty stats report.
1761 stats_collector_->GetStatsReport(internal_receiver, callback);
1762}
1763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1765 return signaling_state_;
1766}
1767
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768PeerConnectionInterface::IceConnectionState
1769PeerConnection::ice_connection_state() {
1770 return ice_connection_state_;
1771}
1772
Alex Loiko9289eda2018-11-23 16:18:59 +00001773PeerConnectionInterface::IceConnectionState
1774PeerConnection::standardized_ice_connection_state() {
1775 return standardized_ice_connection_state_;
1776}
1777
Jonas Olsson635474e2018-10-18 15:58:17 +02001778PeerConnectionInterface::PeerConnectionState
1779PeerConnection::peer_connection_state() {
1780 return connection_state_;
1781}
1782
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783PeerConnectionInterface::IceGatheringState
1784PeerConnection::ice_gathering_state() {
1785 return ice_gathering_state_;
1786}
1787
Yves Gerey665174f2018-06-19 15:03:05 +02001788rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789 const std::string& label,
1790 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001791 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001792
deadbeefab9b2d12015-10-14 11:33:11 -07001793 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001794
kwibergd1fe2812016-04-27 06:47:29 -07001795 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001796 if (config) {
1797 internal_config.reset(new InternalDataChannelInit(*config));
1798 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001799 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001800 InternalCreateDataChannel(label, internal_config.get()));
1801 if (!channel.get()) {
1802 return nullptr;
1803 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001804
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001805 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1806 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001807 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001808 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001809 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001810 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001811 return DataChannelProxy::Create(signaling_thread(), channel.get());
1812}
1813
1814void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001815 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001816 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001817
nisse7ce109a2017-01-31 00:57:56 -08001818 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001820 return;
1821 }
deadbeefab9b2d12015-10-14 11:33:11 -07001822
Steve Anton8d3444d2017-10-20 15:30:51 -07001823 if (IsClosed()) {
1824 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001825 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001826 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001827 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001828 return;
1829 }
1830
zhihuang1c378ed2017-08-17 14:10:50 -07001831 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001832 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001833 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001834 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001835 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001836 return;
1837 }
1838
Steve Anton22da89f2018-01-25 13:58:07 -08001839 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1840 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1841 if (IsUnifiedPlan()) {
1842 RTCError error = HandleLegacyOfferOptions(options);
1843 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001844 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001845 return;
1846 }
1847 }
1848
zhihuang1c378ed2017-08-17 14:10:50 -07001849 cricket::MediaSessionOptions session_options;
1850 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001851 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001852}
1853
Steve Anton22da89f2018-01-25 13:58:07 -08001854RTCError PeerConnection::HandleLegacyOfferOptions(
1855 const RTCOfferAnswerOptions& options) {
1856 RTC_DCHECK(IsUnifiedPlan());
1857
1858 if (options.offer_to_receive_audio == 0) {
1859 RemoveRecvDirectionFromReceivingTransceiversOfType(
1860 cricket::MEDIA_TYPE_AUDIO);
1861 } else if (options.offer_to_receive_audio == 1) {
1862 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1863 } else if (options.offer_to_receive_audio > 1) {
1864 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1865 "offer_to_receive_audio > 1 is not supported.");
1866 }
1867
1868 if (options.offer_to_receive_video == 0) {
1869 RemoveRecvDirectionFromReceivingTransceiversOfType(
1870 cricket::MEDIA_TYPE_VIDEO);
1871 } else if (options.offer_to_receive_video == 1) {
1872 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1873 } else if (options.offer_to_receive_video > 1) {
1874 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1875 "offer_to_receive_video > 1 is not supported.");
1876 }
1877
1878 return RTCError::OK();
1879}
1880
1881void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1882 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001883 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001884 RtpTransceiverDirection new_direction =
1885 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1886 if (new_direction != transceiver->direction()) {
1887 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1888 << " transceiver (MID="
1889 << transceiver->mid().value_or("<not set>") << ") from "
1890 << RtpTransceiverDirectionToString(
1891 transceiver->direction())
1892 << " to "
1893 << RtpTransceiverDirectionToString(new_direction)
1894 << " since CreateOffer specified offer_to_receive=0";
1895 transceiver->internal()->set_direction(new_direction);
1896 }
Steve Anton22da89f2018-01-25 13:58:07 -08001897 }
1898}
1899
1900void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1901 cricket::MediaType media_type) {
1902 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001903 RTC_LOG(LS_INFO)
1904 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1905 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001906 RtpTransceiverInit init;
1907 init.direction = RtpTransceiverDirection::kRecvOnly;
1908 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1909 }
1910}
1911
1912std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1913PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1914 std::vector<
1915 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1916 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001917 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001918 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001919 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1920 receiving_transceivers.push_back(transceiver);
1921 }
1922 }
1923 return receiving_transceivers;
1924}
1925
htaa2a49d92016-03-04 02:51:39 -08001926void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1927 const RTCOfferAnswerOptions& options) {
1928 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001929 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001930 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001931 return;
1932 }
1933
Steve Antondffead82018-02-06 10:31:29 -08001934 if (!(signaling_state_ == kHaveRemoteOffer ||
1935 signaling_state_ == kHaveLocalPrAnswer)) {
1936 std::string error =
1937 "PeerConnection cannot create an answer in a state other than "
1938 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001939 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001940 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001941 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001942 return;
1943 }
1944
Steve Antondffead82018-02-06 10:31:29 -08001945 // The remote description should be set if we're in the right state.
1946 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001947
Steve Anton22da89f2018-01-25 13:58:07 -08001948 if (IsUnifiedPlan()) {
1949 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1950 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1951 "supported with Unified Plan semantics. Use the "
1952 "RtpTransceiver API instead.";
1953 }
1954 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1955 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1956 "supported with Unified Plan semantics. Use the "
1957 "RtpTransceiver API instead.";
1958 }
1959 }
1960
htaa2a49d92016-03-04 02:51:39 -08001961 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001962 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001963
Steve Antond25da372017-11-06 14:50:29 -08001964 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001965}
1966
1967void PeerConnection::SetLocalDescription(
1968 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001969 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001970 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001971
Steve Anton80dd7b52018-02-16 17:08:42 -08001972 // The SetLocalDescription contract is that we take ownership of the session
1973 // description regardless of the outcome, so wrap it in a unique_ptr right
1974 // away. Ideally, SetLocalDescription's signature will be changed to take the
1975 // description as a unique_ptr argument to formalize this agreement.
1976 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1977
nisse7ce109a2017-01-31 00:57:56 -08001978 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001979 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980 return;
1981 }
Steve Anton8a006912017-12-04 15:25:56 -08001982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001984 PostSetSessionDescriptionFailure(
1985 observer,
1986 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987 return;
1988 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001989
Steve Anton80dd7b52018-02-16 17:08:42 -08001990 // If a session error has occurred the PeerConnection is in a possibly
1991 // inconsistent state so fail right away.
1992 if (session_error() != SessionError::kNone) {
1993 std::string error_message = GetSessionErrorMsg();
1994 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001995 PostSetSessionDescriptionFailure(
1996 observer,
1997 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001998 return;
1999 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002000
Steve Anton80dd7b52018-02-16 17:08:42 -08002001 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2002 if (!error.ok()) {
2003 std::string error_message = GetSetDescriptionErrorMessage(
2004 cricket::CS_LOCAL, desc->GetType(), error);
2005 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002006 PostSetSessionDescriptionFailure(
2007 observer,
2008 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002009 return;
2010 }
2011
2012 // Grab the description type before moving ownership to ApplyLocalDescription,
2013 // which may destroy it before returning.
2014 const SdpType type = desc->GetType();
2015
2016 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002017 // |desc| may be destroyed at this point.
2018
2019 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002020 // If ApplyLocalDescription fails, the PeerConnection could be in an
2021 // inconsistent state, so act conservatively here and set the session error
2022 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2023 SetSessionError(SessionError::kContent, error.message());
2024 std::string error_message =
2025 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2026 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002027 PostSetSessionDescriptionFailure(
2028 observer,
2029 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002030 return;
2031 }
Steve Anton8a006912017-12-04 15:25:56 -08002032 RTC_DCHECK(local_description());
2033
2034 PostSetSessionDescriptionSuccess(observer);
2035
Steve Antonad182762018-09-05 20:22:40 +00002036 // MaybeStartGathering needs to be called after posting
2037 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2038 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002039 transport_controller_->MaybeStartGathering();
2040
Steve Antona3a92c22017-12-07 10:27:41 -08002041 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002042 // TODO(deadbeef): We already had to hop to the network thread for
2043 // MaybeStartGathering...
2044 network_thread()->Invoke<void>(
2045 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2046 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002047 // Make UMA notes about what was agreed to.
2048 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002049 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002050 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002051}
2052
2053RTCError PeerConnection::ApplyLocalDescription(
2054 std::unique_ptr<SessionDescriptionInterface> desc) {
2055 RTC_DCHECK_RUN_ON(signaling_thread());
2056 RTC_DCHECK(desc);
2057
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002058 // Update stats here so that we have the most recent stats for tracks and
2059 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002060 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002061
Steve Antondcc3c022017-12-22 16:02:54 -08002062 // Take a reference to the old local description since it's used below to
2063 // compare against the new local description. When setting the new local
2064 // description, grab ownership of the replaced session description in case it
2065 // is the same as |old_local_description|, to keep it alive for the duration
2066 // of the method.
2067 const SessionDescriptionInterface* old_local_description =
2068 local_description();
2069 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002070 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002071 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002072 replaced_local_description = pending_local_description_
2073 ? std::move(pending_local_description_)
2074 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002075 current_local_description_ = std::move(desc);
2076 pending_local_description_ = nullptr;
2077 current_remote_description_ = std::move(pending_remote_description_);
2078 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002079 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002080 pending_local_description_ = std::move(desc);
2081 }
2082 // The session description to apply now must be accessed by
2083 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002084 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002085
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002086 if (!is_caller_) {
2087 if (remote_description()) {
2088 // Remote description was applied first, so this PC is the callee.
2089 is_caller_ = false;
2090 } else {
2091 // Local description is applied first, so this PC is the caller.
2092 is_caller_ = true;
2093 }
2094 }
2095
Zhi Huange830e682018-03-30 10:48:35 -07002096 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2097 if (!error.ok()) {
2098 return error;
2099 }
2100
Steve Antondcc3c022017-12-22 16:02:54 -08002101 if (IsUnifiedPlan()) {
2102 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002103 cricket::CS_LOCAL, *local_description(), old_local_description,
2104 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002105 if (!error.ok()) {
2106 return error;
2107 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002108 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2109 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002110 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002111 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2112 // Note that code paths that don't set MID won't be able to use
2113 // information about DTLS transports.
2114 if (transceiver->mid()) {
2115 auto dtls_transport =
2116 LookupDtlsTransportByMidInternal(*transceiver->mid());
2117 transceiver->internal()->sender_internal()->set_transport(
2118 dtls_transport);
2119 transceiver->internal()->receiver_internal()->set_transport(
2120 dtls_transport);
2121 }
2122
Steve Antondcc3c022017-12-22 16:02:54 -08002123 const ContentInfo* content =
2124 FindMediaSectionForTransceiver(transceiver, local_description());
2125 if (!content) {
2126 continue;
2127 }
2128 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002129 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2130 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002131 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002132 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2133 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2134 // "recvonly", process the removal of a remote track for the media
2135 // description, given transceiver, removeList, and muteTracks.
2136 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2137 (transceiver->internal()->fired_direction() &&
2138 RtpTransceiverDirectionHasRecv(
2139 *transceiver->internal()->fired_direction()))) {
2140 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2141 &removed_streams);
2142 }
2143 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2144 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002145 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002146 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002147 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002148 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002149 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002150 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002151 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002152 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002153 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002154 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002155 }
2156 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002157 // Media channels will be created only when offer is set. These may use new
2158 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002159 if (type == SdpType::kOffer) {
2160 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2161 // description is applied. Restore back to old description.
2162 RTCError error = CreateChannels(*local_description()->description());
2163 if (!error.ok()) {
2164 return error;
2165 }
2166 }
Steve Antondcc3c022017-12-22 16:02:54 -08002167 // Remove unused channels if MediaContentDescription is rejected.
2168 RemoveUnusedChannels(local_description()->description());
2169 }
Steve Anton8a006912017-12-04 15:25:56 -08002170
Zhi Huange830e682018-03-30 10:48:35 -07002171 error = UpdateSessionState(type, cricket::CS_LOCAL,
2172 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002173 if (!error.ok()) {
2174 return error;
2175 }
Steve Antondcc3c022017-12-22 16:02:54 -08002176
Steve Anton8a006912017-12-04 15:25:56 -08002177 if (remote_description()) {
2178 // Now that we have a local description, we can push down remote candidates.
2179 UseCandidatesInSessionDescription(remote_description());
2180 }
2181
2182 pending_ice_restarts_.clear();
2183 if (session_error() != SessionError::kNone) {
2184 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2185 }
2186
deadbeefab9b2d12015-10-14 11:33:11 -07002187 // If setting the description decided our SSL role, allocate any necessary
2188 // SCTP sids.
2189 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002190 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002191 AllocateSctpSids(role);
2192 }
2193
Steve Antond3679212018-01-17 17:41:02 -08002194 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002195 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002196 const ContentInfo* content =
2197 FindMediaSectionForTransceiver(transceiver, local_description());
2198 if (!content) {
2199 continue;
2200 }
Steve Anton74255ff2018-01-24 18:32:57 -08002201 const auto& streams = content->media_description()->streams();
2202 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002203 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002204 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002205 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002206 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002207 } else {
2208 // 0 is a special value meaning "this sender has no associated send
2209 // stream". Need to call this so the sender won't attempt to configure
2210 // a no longer existing stream and run into DCHECKs in the lower
2211 // layers.
2212 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002213 }
2214 }
2215 } else {
2216 // Plan B semantics.
2217
Steve Antondcc3c022017-12-22 16:02:54 -08002218 // Update state and SSRC of local MediaStreams and DataChannels based on the
2219 // local session description.
2220 const cricket::ContentInfo* audio_content =
2221 GetFirstAudioContent(local_description()->description());
2222 if (audio_content) {
2223 if (audio_content->rejected) {
2224 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2225 } else {
2226 const cricket::AudioContentDescription* audio_desc =
2227 audio_content->media_description()->as_audio();
2228 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2229 }
deadbeeffaac4972015-11-12 15:33:07 -08002230 }
deadbeefab9b2d12015-10-14 11:33:11 -07002231
Steve Antondcc3c022017-12-22 16:02:54 -08002232 const cricket::ContentInfo* video_content =
2233 GetFirstVideoContent(local_description()->description());
2234 if (video_content) {
2235 if (video_content->rejected) {
2236 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2237 } else {
2238 const cricket::VideoContentDescription* video_desc =
2239 video_content->media_description()->as_video();
2240 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2241 }
deadbeeffaac4972015-11-12 15:33:07 -08002242 }
deadbeefab9b2d12015-10-14 11:33:11 -07002243 }
2244
2245 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002246 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002247 if (data_content) {
2248 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002249 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002250 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002251 cricket::kMediaProtocolRtpPrefix)) {
2252 UpdateLocalRtpDataChannels(data_desc->streams());
2253 }
2254 }
2255
Steve Anton8a006912017-12-04 15:25:56 -08002256 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257}
2258
Steve Anton06817cd2018-12-18 15:55:30 -08002259// The SDP parser used to populate these values by default for the 'content
2260// name' if an a=mid line was absent.
2261static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2262 switch (media_type) {
2263 case cricket::MEDIA_TYPE_AUDIO:
2264 return cricket::CN_AUDIO;
2265 case cricket::MEDIA_TYPE_VIDEO:
2266 return cricket::CN_VIDEO;
2267 case cricket::MEDIA_TYPE_DATA:
2268 return cricket::CN_DATA;
2269 }
2270 RTC_NOTREACHED();
2271 return "";
2272}
2273
2274void PeerConnection::FillInMissingRemoteMids(
2275 cricket::SessionDescription* remote_description) {
2276 RTC_DCHECK(remote_description);
2277 const cricket::ContentInfos& local_contents =
2278 (local_description() ? local_description()->description()->contents()
2279 : cricket::ContentInfos());
Steve Anton06817cd2018-12-18 15:55:30 -08002280 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2281 cricket::ContentInfo& content = remote_description->contents()[i];
2282 if (!content.name.empty()) {
2283 continue;
2284 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002285 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002286 absl::string_view source_explanation;
2287 if (IsUnifiedPlan()) {
2288 if (i < local_contents.size()) {
2289 new_mid = local_contents[i].name;
2290 source_explanation = "from the matching local media section";
2291 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002292 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002293 source_explanation = "generated just now";
2294 }
2295 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002296 new_mid = std::string(
2297 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002298 source_explanation = "to match pre-existing behavior";
2299 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002300 content.name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002301 remote_description->transport_infos()[i].content_name =
2302 std::string(new_mid);
2303 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2304 << " is missing an a=mid line. Filling in the value '"
2305 << new_mid << "' " << source_explanation << ".";
2306 }
2307}
2308
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002309void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002310 SetSessionDescriptionObserver* observer,
2311 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002312 SetRemoteDescription(
2313 std::unique_ptr<SessionDescriptionInterface>(desc),
2314 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2315 new SetRemoteDescriptionObserverAdapter(this, observer)));
2316}
2317
2318void PeerConnection::SetRemoteDescription(
2319 std::unique_ptr<SessionDescriptionInterface> desc,
2320 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002321 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002322
nisse7ce109a2017-01-31 00:57:56 -08002323 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002324 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002325 return;
2326 }
Steve Anton8a006912017-12-04 15:25:56 -08002327
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002328 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002329 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002330 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002331 return;
2332 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002333
Steve Anton80dd7b52018-02-16 17:08:42 -08002334 // If a session error has occurred the PeerConnection is in a possibly
2335 // inconsistent state so fail right away.
2336 if (session_error() != SessionError::kNone) {
2337 std::string error_message = GetSessionErrorMsg();
2338 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2339 observer->OnSetRemoteDescriptionComplete(
2340 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2341 return;
2342 }
Steve Anton71439a62018-02-15 11:53:06 -08002343
Steve Antonba42e992018-04-09 14:10:01 -07002344 if (desc->GetType() == SdpType::kOffer) {
2345 // Report to UMA the format of the received offer.
2346 ReportSdpFormatReceived(*desc);
2347 }
2348
Steve Anton06817cd2018-12-18 15:55:30 -08002349 // Handle remote descriptions missing a=mid lines for interop with legacy end
2350 // points.
2351 FillInMissingRemoteMids(desc->description());
2352
Steve Anton80dd7b52018-02-16 17:08:42 -08002353 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002354 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002355 std::string error_message = GetSetDescriptionErrorMessage(
2356 cricket::CS_REMOTE, desc->GetType(), error);
2357 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002358 observer->OnSetRemoteDescriptionComplete(
2359 RTCError(error.type(), std::move(error_message)));
2360 return;
2361 }
Steve Anton71439a62018-02-15 11:53:06 -08002362
Steve Anton80dd7b52018-02-16 17:08:42 -08002363 // Grab the description type before moving ownership to
2364 // ApplyRemoteDescription, which may destroy it before returning.
2365 const SdpType type = desc->GetType();
2366
2367 error = ApplyRemoteDescription(std::move(desc));
2368 // |desc| may be destroyed at this point.
2369
2370 if (!error.ok()) {
2371 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2372 // inconsistent state, so act conservatively here and set the session error
2373 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2374 SetSessionError(SessionError::kContent, error.message());
2375 std::string error_message =
2376 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2377 RTC_LOG(LS_ERROR) << error_message;
2378 observer->OnSetRemoteDescriptionComplete(
2379 RTCError(error.type(), std::move(error_message)));
2380 return;
2381 }
2382 RTC_DCHECK(remote_description());
2383
2384 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002385 // TODO(deadbeef): We already had to hop to the network thread for
2386 // MaybeStartGathering...
2387 network_thread()->Invoke<void>(
2388 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2389 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002390 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002391 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002392 }
2393
2394 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002395 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002396}
2397
2398RTCError PeerConnection::ApplyRemoteDescription(
2399 std::unique_ptr<SessionDescriptionInterface> desc) {
2400 RTC_DCHECK_RUN_ON(signaling_thread());
2401 RTC_DCHECK(desc);
2402
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002403 // Update stats here so that we have the most recent stats for tracks and
2404 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002405 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002406
Steve Antondcc3c022017-12-22 16:02:54 -08002407 // Take a reference to the old remote description since it's used below to
2408 // compare against the new remote description. When setting the new remote
2409 // description, grab ownership of the replaced session description in case it
2410 // is the same as |old_remote_description|, to keep it alive for the duration
2411 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002412 const SessionDescriptionInterface* old_remote_description =
2413 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002414 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002415 SdpType type = desc->GetType();
2416 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002417 replaced_remote_description = pending_remote_description_
2418 ? std::move(pending_remote_description_)
2419 : std::move(current_remote_description_);
2420 current_remote_description_ = std::move(desc);
2421 pending_remote_description_ = nullptr;
2422 current_local_description_ = std::move(pending_local_description_);
2423 } else {
2424 replaced_remote_description = std::move(pending_remote_description_);
2425 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002426 }
Steve Anton8a006912017-12-04 15:25:56 -08002427 // The session description to apply now must be accessed by
2428 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002429 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002430
Zhi Huange830e682018-03-30 10:48:35 -07002431 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2432 if (!error.ok()) {
2433 return error;
2434 }
Steve Anton8a006912017-12-04 15:25:56 -08002435 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002436 if (IsUnifiedPlan()) {
2437 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002438 cricket::CS_REMOTE, *remote_description(), local_description(),
2439 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002440 if (!error.ok()) {
2441 return error;
2442 }
Steve Antondcc3c022017-12-22 16:02:54 -08002443 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002444 // Media channels will be created only when offer is set. These may use new
2445 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002446 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002447 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002448 // description is applied. Restore back to old description.
2449 RTCError error = CreateChannels(*remote_description()->description());
2450 if (!error.ok()) {
2451 return error;
2452 }
2453 }
Steve Antondcc3c022017-12-22 16:02:54 -08002454 // Remove unused channels if MediaContentDescription is rejected.
2455 RemoveUnusedChannels(remote_description()->description());
2456 }
Steve Anton8a006912017-12-04 15:25:56 -08002457
Zhi Huange830e682018-03-30 10:48:35 -07002458 // NOTE: Candidates allocation will be initiated only when
2459 // SetLocalDescription is called.
2460 error = UpdateSessionState(type, cricket::CS_REMOTE,
2461 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002462 if (!error.ok()) {
2463 return error;
2464 }
2465
2466 if (local_description() &&
2467 !UseCandidatesInSessionDescription(remote_description())) {
2468 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2469 }
2470
2471 if (old_remote_description) {
2472 for (const cricket::ContentInfo& content :
2473 old_remote_description->description()->contents()) {
2474 // Check if this new SessionDescription contains new ICE ufrag and
2475 // password that indicates the remote peer requests an ICE restart.
2476 // TODO(deadbeef): When we start storing both the current and pending
2477 // remote description, this should reset pending_ice_restarts and compare
2478 // against the current description.
2479 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2480 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002481 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002482 pending_ice_restarts_.insert(content.name);
2483 }
2484 } else {
2485 // We retain all received candidates only if ICE is not restarted.
2486 // When ICE is restarted, all previous candidates belong to an old
2487 // generation and should not be kept.
2488 // TODO(deadbeef): This goes against the W3C spec which says the remote
2489 // description should only contain candidates from the last set remote
2490 // description plus any candidates added since then. We should remove
2491 // this once we're sure it won't break anything.
2492 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2493 old_remote_description, content.name, mutable_remote_description());
2494 }
2495 }
2496 }
2497
2498 if (session_error() != SessionError::kNone) {
2499 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2500 }
2501
2502 // Set the the ICE connection state to connecting since the connection may
2503 // become writable with peer reflexive candidates before any remote candidate
2504 // is signaled.
2505 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2506 // is to have a new signal the indicates a change in checking state from the
2507 // transport and expose a new checking() member from transport that can be
2508 // read to determine the current checking state. The existing SignalConnecting
2509 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002510 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002511 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002512 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2513 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2514 }
2515
deadbeefab9b2d12015-10-14 11:33:11 -07002516 // If setting the description decided our SSL role, allocate any necessary
2517 // SCTP sids.
2518 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002519 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002520 AllocateSctpSids(role);
2521 }
2522
Steve Antondcc3c022017-12-22 16:02:54 -08002523 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002524 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002525 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002526 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002527 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002528 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002529 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002530 const ContentInfo* content =
2531 FindMediaSectionForTransceiver(transceiver, remote_description());
2532 if (!content) {
2533 continue;
2534 }
2535 const MediaContentDescription* media_desc = content->media_description();
2536 RtpTransceiverDirection local_direction =
2537 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002538 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2539 // RTCSessionDescription: Set the associated remote streams given
2540 // transceiver.[[Receiver]], msids, addList, and removeList".
2541 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2542 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2543 std::vector<std::string> stream_ids;
2544 if (!media_desc->streams().empty()) {
2545 // The remote description has signaled the stream IDs.
2546 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002547 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002548 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2549 << " (" << GetStreamIdsString(stream_ids) << ").";
2550 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2551 stream_ids, &added_streams,
2552 &removed_streams);
2553 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2554 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2555 // and transceiver's current direction is neither sendrecv nor recvonly,
2556 // process the addition of a remote track for the media description.
2557 if (!transceiver->fired_direction() ||
2558 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2559 RTC_LOG(LS_INFO)
2560 << "Processing the addition of a remote track for MID="
2561 << content->name << ".";
2562 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002563 }
Steve Antondcc3c022017-12-22 16:02:54 -08002564 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002565 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002566 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2567 // removal of a remote track for the media description, given transceiver,
2568 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002569 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002570 (transceiver->fired_direction() &&
2571 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2572 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2573 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002574 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002575 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002576 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002577 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002578 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002579 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002580 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002581 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002582 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002583 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2584 if (transceiver->mid()) {
2585 auto dtls_transport =
2586 LookupDtlsTransportByMidInternal(*transceiver->mid());
2587 transceiver->internal()->sender_internal()->set_transport(
2588 dtls_transport);
2589 transceiver->internal()->receiver_internal()->set_transport(
2590 dtls_transport);
2591 }
Steve Antondcc3c022017-12-22 16:02:54 -08002592 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002593 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002594 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002595 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002596 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2597 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002598 transceiver->Stop();
2599 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002600 if (!content->rejected &&
2601 RtpTransceiverDirectionHasRecv(local_direction)) {
2602 // Set ssrc to 0 in the case of an unsignalled ssrc.
2603 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002604 if (!media_desc->streams().empty() &&
2605 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002606 ssrc = media_desc->streams()[0].first_ssrc();
2607 }
2608 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002609 }
Steve Antondcc3c022017-12-22 16:02:54 -08002610 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002611 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002612 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002613 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002614 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002615 observer->OnTrack(transceiver);
2616 observer->OnAddTrack(transceiver->receiver(),
2617 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002618 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002619 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002620 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002621 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002622 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002623 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002624 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002625 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002626 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002627 }
Steve Antondcc3c022017-12-22 16:02:54 -08002628 }
2629
Henrik Boströmfdb92012017-11-09 19:55:44 +01002630 const cricket::ContentInfo* audio_content =
2631 GetFirstAudioContent(remote_description()->description());
2632 const cricket::ContentInfo* video_content =
2633 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002634 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002635 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002636 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002637 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002638 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002639 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002640
2641 // Check if the descriptions include streams, just in case the peer supports
2642 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002643 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002644 (audio_desc && !audio_desc->streams().empty()) ||
2645 (video_desc && !video_desc->streams().empty())) {
2646 remote_peer_supports_msid_ = true;
2647 }
deadbeefab9b2d12015-10-14 11:33:11 -07002648
2649 // We wait to signal new streams until we finish processing the description,
2650 // since only at that point will new streams have all their tracks.
2651 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2652
Steve Antondcc3c022017-12-22 16:02:54 -08002653 if (!IsUnifiedPlan()) {
2654 // TODO(steveanton): When removing RTP senders/receivers in response to a
2655 // rejected media section, there is some cleanup logic that expects the
2656 // voice/ video channel to still be set. But in this method the voice/video
2657 // channel would have been destroyed by the SetRemoteDescription caller
2658 // above so the cleanup that relies on them fails to run. The RemoveSenders
2659 // calls should be moved to right before the DestroyChannel calls to fix
2660 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002661
Steve Antondcc3c022017-12-22 16:02:54 -08002662 // Find all audio rtp streams and create corresponding remote AudioTracks
2663 // and MediaStreams.
2664 if (audio_content) {
2665 if (audio_content->rejected) {
2666 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2667 } else {
2668 bool default_audio_track_needed =
2669 !remote_peer_supports_msid_ &&
2670 RtpTransceiverDirectionHasSend(audio_desc->direction());
2671 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2672 default_audio_track_needed, audio_desc->type(),
2673 new_streams);
2674 }
deadbeeffaac4972015-11-12 15:33:07 -08002675 }
deadbeefab9b2d12015-10-14 11:33:11 -07002676
Steve Antondcc3c022017-12-22 16:02:54 -08002677 // Find all video rtp streams and create corresponding remote VideoTracks
2678 // and MediaStreams.
2679 if (video_content) {
2680 if (video_content->rejected) {
2681 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2682 } else {
2683 bool default_video_track_needed =
2684 !remote_peer_supports_msid_ &&
2685 RtpTransceiverDirectionHasSend(video_desc->direction());
2686 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2687 default_video_track_needed, video_desc->type(),
2688 new_streams);
2689 }
deadbeeffaac4972015-11-12 15:33:07 -08002690 }
deadbeefab9b2d12015-10-14 11:33:11 -07002691
Steve Antondcc3c022017-12-22 16:02:54 -08002692 // Update the DataChannels with the information from the remote peer.
2693 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002694 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002695 cricket::kMediaProtocolRtpPrefix)) {
2696 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2697 }
deadbeefab9b2d12015-10-14 11:33:11 -07002698 }
deadbeefab9b2d12015-10-14 11:33:11 -07002699
Steve Antondcc3c022017-12-22 16:02:54 -08002700 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002701 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002702 for (size_t i = 0; i < new_streams->count(); ++i) {
2703 MediaStreamInterface* new_stream = new_streams->at(i);
2704 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002705 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002706 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2707 }
deadbeefab9b2d12015-10-14 11:33:11 -07002708
Steve Antondcc3c022017-12-22 16:02:54 -08002709 UpdateEndedRemoteMediaStreams();
2710 }
deadbeefab9b2d12015-10-14 11:33:11 -07002711
Steve Anton8a006912017-12-04 15:25:56 -08002712 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002713}
2714
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002715void PeerConnection::SetAssociatedRemoteStreams(
2716 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2717 const std::vector<std::string>& stream_ids,
2718 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2719 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2720 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2721 for (const std::string& stream_id : stream_ids) {
2722 rtc::scoped_refptr<MediaStreamInterface> stream =
2723 remote_streams_->find(stream_id);
2724 if (!stream) {
2725 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2726 MediaStream::Create(stream_id));
2727 remote_streams_->AddStream(stream);
2728 added_streams->push_back(stream);
2729 }
2730 media_streams.push_back(stream);
2731 }
2732 // Special case: "a=msid" missing, use random stream ID.
2733 if (media_streams.empty() &&
2734 !(remote_description()->description()->msid_signaling() &
2735 cricket::kMsidSignalingMediaSection)) {
2736 if (!missing_msid_default_stream_) {
2737 missing_msid_default_stream_ = MediaStreamProxy::Create(
2738 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2739 added_streams->push_back(missing_msid_default_stream_);
2740 }
2741 media_streams.push_back(missing_msid_default_stream_);
2742 }
2743 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2744 receiver->streams();
2745 // SetStreams() will add/remove the receiver's track to/from the streams. This
2746 // differs from the spec - the spec uses an "addList" and "removeList" to
2747 // update the stream-track relationships in a later step. We do this earlier,
2748 // changing the order of things, but the end-result is the same.
2749 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2750 // instead. https://crbug.com/webrtc/9480
2751 receiver->SetStreams(media_streams);
2752 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2753}
2754
Steve Anton0f5400a2018-07-17 14:25:36 -07002755void PeerConnection::ProcessRemovalOfRemoteTrack(
2756 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2757 transceiver,
2758 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2759 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2760 RTC_DCHECK(transceiver->mid());
2761 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2762 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002763 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002764 transceiver->internal()->receiver_internal()->streams();
2765 // This will remove the remote track from the streams.
2766 transceiver->internal()->receiver_internal()->set_stream_ids({});
2767 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002768 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2769}
2770
2771void PeerConnection::RemoveRemoteStreamsIfEmpty(
2772 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2773 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2774 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2775 // streams, see if the stream was removed by checking if this was the last
2776 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002777 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002778 if (remote_stream->GetAudioTracks().empty() &&
2779 remote_stream->GetVideoTracks().empty()) {
2780 remote_streams_->RemoveStream(remote_stream);
2781 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002782 }
2783 }
2784}
2785
Steve Antondcc3c022017-12-22 16:02:54 -08002786RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2787 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002788 const SessionDescriptionInterface& new_session,
2789 const SessionDescriptionInterface* old_local_description,
2790 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002791 RTC_DCHECK(IsUnifiedPlan());
2792
Steve Anton7464fca2018-01-19 11:10:37 -08002793 const cricket::ContentGroup* bundle_group = nullptr;
2794 if (new_session.GetType() == SdpType::kOffer) {
2795 auto bundle_group_or_error =
2796 GetEarlyBundleGroup(*new_session.description());
2797 if (!bundle_group_or_error.ok()) {
2798 return bundle_group_or_error.MoveError();
2799 }
2800 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002801 }
Steve Antondcc3c022017-12-22 16:02:54 -08002802
Steve Antondcc3c022017-12-22 16:02:54 -08002803 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002804 for (size_t i = 0; i < new_contents.size(); ++i) {
2805 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002806 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002807 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002808 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2809 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002810 const cricket::ContentInfo* old_local_content = nullptr;
2811 if (old_local_description &&
2812 i < old_local_description->description()->contents().size()) {
2813 old_local_content =
2814 &old_local_description->description()->contents()[i];
2815 }
2816 const cricket::ContentInfo* old_remote_content = nullptr;
2817 if (old_remote_description &&
2818 i < old_remote_description->description()->contents().size()) {
2819 old_remote_content =
2820 &old_remote_description->description()->contents()[i];
2821 }
Steve Antondcc3c022017-12-22 16:02:54 -08002822 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002823 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2824 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002825 if (!transceiver_or_error.ok()) {
2826 return transceiver_or_error.MoveError();
2827 }
2828 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002829 RTCError error =
2830 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2831 if (!error.ok()) {
2832 return error;
2833 }
2834 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002835 if (GetDataMid() && new_content.name != *GetDataMid()) {
2836 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002837 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2838 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002839 continue;
2840 }
2841 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2842 if (!error.ok()) {
2843 return error;
2844 }
Steve Antondcc3c022017-12-22 16:02:54 -08002845 } else {
2846 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2847 "Unknown section type.");
2848 }
2849 }
2850
2851 return RTCError::OK();
2852}
2853
2854RTCError PeerConnection::UpdateTransceiverChannel(
2855 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2856 transceiver,
2857 const cricket::ContentInfo& content,
2858 const cricket::ContentGroup* bundle_group) {
2859 RTC_DCHECK(IsUnifiedPlan());
2860 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002861 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002862 if (content.rejected) {
2863 if (channel) {
2864 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002865 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002866 }
2867 } else {
2868 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002869 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002870 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002871 } else {
Steve Anton69470252018-02-09 11:43:08 -08002872 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002873 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002874 }
2875 if (!channel) {
2876 LOG_AND_RETURN_ERROR(
2877 RTCErrorType::INTERNAL_ERROR,
2878 "Failed to create channel for mid=" + content.name);
2879 }
2880 transceiver->internal()->SetChannel(channel);
2881 }
2882 }
2883 return RTCError::OK();
2884}
2885
Steve Antonfa2260d2017-12-28 16:38:23 -08002886RTCError PeerConnection::UpdateDataChannel(
2887 cricket::ContentSource source,
2888 const cricket::ContentInfo& content,
2889 const cricket::ContentGroup* bundle_group) {
2890 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002891 // If data channels are disabled, ignore this media section. CreateAnswer
2892 // will take care of rejecting it.
2893 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002894 }
2895 if (content.rejected) {
2896 DestroyDataChannel();
2897 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002898 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002899 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002900 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2901 "Failed to create data channel.");
2902 }
2903 }
2904 if (source == cricket::CS_REMOTE) {
2905 const MediaContentDescription* data_desc = content.media_description();
2906 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2907 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2908 }
2909 }
2910 }
2911 return RTCError::OK();
2912}
2913
Steve Antondcc3c022017-12-22 16:02:54 -08002914RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2915PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002916 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002917 size_t mline_index,
2918 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002919 const ContentInfo* old_local_content,
2920 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002921 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002922 // If this is an offer then the m= section might be recycled. If the m=
2923 // section is being recycled (defined as: rejected in the current local or
2924 // remote description and not rejected in new description), dissociate the
2925 // currently associated RtpTransceiver by setting its mid property to null,
2926 // and discard the mapping between the transceiver and its m= section index.
2927 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2928 old_remote_content)) {
2929 // We want to dissociate the transceiver that has the rejected mid.
2930 const std::string& old_mid =
2931 (old_local_content && old_local_content->rejected)
2932 ? old_local_content->name
2933 : old_remote_content->name;
2934 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002935 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002936 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2937 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002938 old_transceiver->internal()->set_mid(absl::nullopt);
2939 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002940 }
2941 }
2942 const MediaContentDescription* media_desc = content.media_description();
2943 auto transceiver = GetAssociatedTransceiver(content.name);
2944 if (source == cricket::CS_LOCAL) {
2945 // Find the RtpTransceiver that corresponds to this m= section, using the
2946 // mapping between transceivers and m= section indices established when
2947 // creating the offer.
2948 if (!transceiver) {
2949 transceiver = GetTransceiverByMLineIndex(mline_index);
2950 }
2951 if (!transceiver) {
2952 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2953 "Unknown transceiver");
2954 }
2955 } else {
2956 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2957 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2958 // of the same type...
2959 if (!transceiver &&
2960 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2961 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2962 }
2963 // If no RtpTransceiver was found in the previous step, create one with a
2964 // recvonly direction.
2965 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002966 RTC_LOG(LS_INFO) << "Adding "
2967 << cricket::MediaTypeToString(media_desc->type())
2968 << " transceiver for MID=" << content.name
2969 << " at i=" << mline_index
2970 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002971 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002972 auto sender =
2973 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002974 std::string receiver_id;
2975 if (!media_desc->streams().empty()) {
2976 receiver_id = media_desc->streams()[0].id;
2977 } else {
2978 receiver_id = rtc::CreateRandomUuid();
2979 }
2980 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002981 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002982 transceiver->internal()->set_direction(
2983 RtpTransceiverDirection::kRecvOnly);
2984 }
2985 }
2986 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002987 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002988 LOG_AND_RETURN_ERROR(
2989 RTCErrorType::INVALID_PARAMETER,
2990 "Transceiver type does not match media description type.");
2991 }
2992 // Associate the found or created RtpTransceiver with the m= section by
2993 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2994 // section, and establish a mapping between the transceiver and the index of
2995 // the m= section.
2996 transceiver->internal()->set_mid(content.name);
2997 transceiver->internal()->set_mline_index(mline_index);
2998 return std::move(transceiver);
2999}
3000
3001rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3002PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3003 RTC_DCHECK(IsUnifiedPlan());
3004 for (auto transceiver : transceivers_) {
3005 if (transceiver->mid() == mid) {
3006 return transceiver;
3007 }
3008 }
3009 return nullptr;
3010}
3011
3012rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3013PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3014 RTC_DCHECK(IsUnifiedPlan());
3015 for (auto transceiver : transceivers_) {
3016 if (transceiver->internal()->mline_index() == mline_index) {
3017 return transceiver;
3018 }
3019 }
3020 return nullptr;
3021}
3022
3023rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3024PeerConnection::FindAvailableTransceiverToReceive(
3025 cricket::MediaType media_type) const {
3026 RTC_DCHECK(IsUnifiedPlan());
3027 // From JSEP section 5.10 (Applying a Remote Description):
3028 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3029 // the same type that were added to the PeerConnection by addTrack and are not
3030 // associated with any m= section and are not stopped, find the first such
3031 // RtpTransceiver.
3032 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003033 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003034 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3035 !transceiver->stopped()) {
3036 return transceiver;
3037 }
3038 }
3039 return nullptr;
3040}
3041
Steve Antoned10bd92017-12-05 10:52:59 -08003042const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3043 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3044 transceiver,
3045 const SessionDescriptionInterface* sdesc) const {
3046 RTC_DCHECK(transceiver);
3047 RTC_DCHECK(sdesc);
3048 if (IsUnifiedPlan()) {
3049 if (!transceiver->internal()->mid()) {
3050 // This transceiver is not associated with a media section yet.
3051 return nullptr;
3052 }
3053 return sdesc->description()->GetContentByName(
3054 *transceiver->internal()->mid());
3055 } else {
3056 // Plan B only allows at most one audio and one video section, so use the
3057 // first media section of that type.
3058 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003059 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003060 }
3061}
3062
deadbeef46c73892016-11-16 19:42:04 -08003063PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3064 return configuration_;
3065}
3066
deadbeef293e9262017-01-11 12:28:30 -08003067bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3068 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003069 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003070 if (IsClosed()) {
3071 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3072 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3073 }
3074
Qingsi Wanga2d60672018-04-11 16:57:45 -07003075 // According to JSEP, after setLocalDescription, changing the candidate pool
3076 // size is not allowed, and changing the set of ICE servers will not result
3077 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003078 if (local_description() && configuration.ice_candidate_pool_size !=
3079 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003080 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3081 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003082 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003083 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003084
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003085 if (local_description() &&
3086 configuration.use_media_transport != configuration_.use_media_transport) {
3087 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3088 "SetLocalDescription.";
3089 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3090 }
3091
3092 if (remote_description() &&
3093 configuration.use_media_transport != configuration_.use_media_transport) {
3094 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3095 "SetRemoteDescription.";
3096 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3097 }
3098
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003099 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003100 configuration.use_media_transport_for_data_channels !=
3101 configuration_.use_media_transport_for_data_channels) {
3102 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3103 "after calling SetLocalDescription.";
3104 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3105 }
3106
3107 if (remote_description() &&
3108 configuration.use_media_transport_for_data_channels !=
3109 configuration_.use_media_transport_for_data_channels) {
3110 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3111 "after calling SetRemoteDescription.";
3112 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3113 }
3114
3115 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003116 configuration.crypto_options != configuration_.crypto_options) {
3117 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3118 "SetLocalDescription.";
3119 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3120 }
3121
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003122 if (configuration.use_media_transport_for_data_channels ||
3123 configuration.use_media_transport) {
3124 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3125 << "Media transport requires MaxBundle policy.";
3126 }
3127
deadbeef293e9262017-01-11 12:28:30 -08003128 // The simplest (and most future-compatible) way to tell if the config was
3129 // modified in an invalid way is to copy each property we do support
3130 // modifying, then use operator==. There are far more properties we don't
3131 // support modifying than those we do, and more could be added.
3132 RTCConfiguration modified_config = configuration_;
3133 modified_config.servers = configuration.servers;
3134 modified_config.type = configuration.type;
3135 modified_config.ice_candidate_pool_size =
3136 configuration.ice_candidate_pool_size;
3137 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003138 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003139 modified_config.ice_check_interval_strong_connectivity =
3140 configuration.ice_check_interval_strong_connectivity;
3141 modified_config.ice_check_interval_weak_connectivity =
3142 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003143 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3144 modified_config.ice_unwritable_min_checks =
3145 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003146 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003147 modified_config.stun_candidate_keepalive_interval =
3148 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003149 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003150 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003151 modified_config.active_reset_srtp_params =
3152 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003153 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003154 modified_config.use_media_transport_for_data_channels =
3155 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003156 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003157 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003158 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3159 }
3160
Steve Anton038834f2017-07-14 15:59:59 -07003161 // Validate the modified configuration.
3162 RTCError validate_error = ValidateConfiguration(modified_config);
3163 if (!validate_error.ok()) {
3164 return SafeSetError(std::move(validate_error), error);
3165 }
3166
deadbeef293e9262017-01-11 12:28:30 -08003167 // Note that this isn't possible through chromium, since it's an unsigned
3168 // short in WebIDL.
3169 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003170 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003171 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3172 }
3173
3174 // Parse ICE servers before hopping to network thread.
3175 cricket::ServerAddresses stun_servers;
3176 std::vector<cricket::RelayServerConfig> turn_servers;
3177 RTCErrorType parse_error =
3178 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3179 if (parse_error != RTCErrorType::NONE) {
3180 return SafeSetError(parse_error, error);
3181 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003182 // Note if STUN or TURN servers were supplied.
3183 if (!stun_servers.empty()) {
3184 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3185 }
3186 if (!turn_servers.empty()) {
3187 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3188 }
deadbeef293e9262017-01-11 12:28:30 -08003189
3190 // In theory this shouldn't fail.
3191 if (!network_thread()->Invoke<bool>(
3192 RTC_FROM_HERE,
3193 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3194 stun_servers, turn_servers, modified_config.type,
3195 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003196 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003197 modified_config.turn_customizer,
3198 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003199 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003200 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3201 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003202
deadbeefd1a38b52016-12-10 13:15:33 -08003203 // As described in JSEP, calling setConfiguration with new ICE servers or
3204 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3205 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003206 if (modified_config.servers != configuration_.servers ||
3207 modified_config.type != configuration_.type ||
3208 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003209 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003210 }
skvladd1f5fda2017-02-03 16:54:05 -08003211
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003212 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003213 transport_controller_->SetMediaTransportSettings(
3214 modified_config.use_media_transport,
3215 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003216
Zhi Huangb57e1692018-06-12 11:41:11 -07003217 if (configuration_.active_reset_srtp_params !=
3218 modified_config.active_reset_srtp_params) {
3219 transport_controller_->SetActiveResetSrtpParams(
3220 modified_config.active_reset_srtp_params);
3221 }
3222
deadbeef293e9262017-01-11 12:28:30 -08003223 configuration_ = modified_config;
3224 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003225}
3226
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003227bool PeerConnection::AddIceCandidate(
3228 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003229 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003230 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003231 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003232 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003233 return false;
3234 }
Steve Antond25da372017-11-06 14:50:29 -08003235
3236 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003237 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003238 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003239 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003240 return false;
3241 }
3242
3243 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003244 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003245 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003246 return false;
3247 }
3248
3249 bool valid = false;
3250 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3251 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003252 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003253 return false;
3254 }
3255
3256 // Add this candidate to the remote session description.
3257 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003258 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003259 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003260 return false;
3261 }
3262
3263 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003264 bool result = UseCandidate(ice_candidate);
3265 if (result) {
3266 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3267 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3268 } else {
3269 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3270 }
3271 return result;
Steve Antond25da372017-11-06 14:50:29 -08003272 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003273 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003274 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003275 return true;
3276 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277}
3278
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003279bool PeerConnection::RemoveIceCandidates(
3280 const std::vector<cricket::Candidate>& candidates) {
3281 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003282 if (IsClosed()) {
3283 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3284 return false;
3285 }
3286
Steve Antond25da372017-11-06 14:50:29 -08003287 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003288 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3289 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003290 return false;
3291 }
3292
3293 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003294 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003295 return false;
3296 }
3297
3298 size_t number_removed =
3299 mutable_remote_description()->RemoveCandidates(candidates);
3300 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003301 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003302 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003303 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003304 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003305 }
3306
3307 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003308 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3309 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003310 RTC_LOG(LS_ERROR)
3311 << "RemoveIceCandidates: Error when removing remote candidates: "
3312 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003313 }
3314 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003315}
3316
Niels Möller0c4f7be2018-05-07 14:01:37 +02003317RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003318 if (!worker_thread()->IsCurrent()) {
3319 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003320 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003321 }
3322
Niels Möller0c4f7be2018-05-07 14:01:37 +02003323 const bool has_min = bitrate.min_bitrate_bps.has_value();
3324 const bool has_start = bitrate.start_bitrate_bps.has_value();
3325 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003326 if (has_min && *bitrate.min_bitrate_bps < 0) {
3327 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3328 "min_bitrate_bps <= 0");
3329 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003330 if (has_start) {
3331 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003332 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003333 "start_bitrate_bps < min_bitrate_bps");
3334 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3336 "curent_bitrate_bps < 0");
3337 }
3338 }
3339 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003340 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003342 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003343 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3345 "max_bitrate_bps < min_bitrate_bps");
3346 } else if (*bitrate.max_bitrate_bps < 0) {
3347 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3348 "max_bitrate_bps < 0");
3349 }
3350 }
3351
zstein4b979802017-06-02 14:37:37 -07003352 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003353 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003354
3355 return RTCError::OK();
3356}
3357
Alex Narest78609d52017-10-20 10:37:47 +02003358void PeerConnection::SetBitrateAllocationStrategy(
3359 std::unique_ptr<rtc::BitrateAllocationStrategy>
3360 bitrate_allocation_strategy) {
3361 rtc::Thread* worker_thread = factory_->worker_thread();
3362 if (!worker_thread->IsCurrent()) {
3363 rtc::BitrateAllocationStrategy* strategy_raw =
3364 bitrate_allocation_strategy.release();
3365 auto functor = [this, strategy_raw]() {
3366 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003367 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003368 };
3369 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3370 return;
3371 }
3372 RTC_DCHECK(call_.get());
3373 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3374}
3375
henrika5f6bf242017-11-01 11:06:56 +01003376void PeerConnection::SetAudioPlayout(bool playout) {
3377 if (!worker_thread()->IsCurrent()) {
3378 worker_thread()->Invoke<void>(
3379 RTC_FROM_HERE,
3380 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3381 return;
3382 }
3383 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003384 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003385 audio_state->SetPlayout(playout);
3386}
3387
3388void PeerConnection::SetAudioRecording(bool recording) {
3389 if (!worker_thread()->IsCurrent()) {
3390 worker_thread()->Invoke<void>(
3391 RTC_FROM_HERE,
3392 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3393 return;
3394 }
3395 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003396 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003397 audio_state->SetRecording(recording);
3398}
3399
Steve Anton8c0f7a72017-10-03 10:03:10 -07003400std::unique_ptr<rtc::SSLCertificate>
3401PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003402 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3403 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003404 return nullptr;
3405 }
Steve Antonf25303e2018-10-16 15:23:31 -07003406 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003407}
3408
Zhi Huang70b820f2018-01-27 14:16:15 -08003409std::unique_ptr<rtc::SSLCertChain>
3410PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003411 auto audio_transceiver = GetFirstAudioTransceiver();
3412 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003413 return nullptr;
3414 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003415 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003416 audio_transceiver->internal()->channel()->transport_name());
3417}
3418
3419rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3420PeerConnection::GetFirstAudioTransceiver() const {
3421 for (auto transceiver : transceivers_) {
3422 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3423 return transceiver;
3424 }
3425 }
3426 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003427}
3428
ivoc14d5dbe2016-07-04 07:06:55 -07003429bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3430 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003431 // TODO(eladalon): It would be better to not allow negative values into PC.
3432 const size_t max_size = (max_size_bytes < 0)
3433 ? RtcEventLog::kUnlimitedOutput
3434 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003435 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3436 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3437 output_period_ms = 5000;
3438 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003439 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003440 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003441 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003442}
3443
Bjorn Tereliusde939432017-11-20 17:38:14 +01003444bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3445 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003446 // TODO(eladalon): In C++14, this can be done with a lambda.
3447 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003448 bool operator()() {
3449 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3450 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003451 PeerConnection* const pc;
3452 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003453 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003454 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003455 return worker_thread()->Invoke<bool>(
3456 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003457}
3458
3459void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003460 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003461 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3462}
3463
Harald Alvestrandad88c882018-11-28 16:47:46 +01003464rtc::scoped_refptr<DtlsTransportInterface>
3465PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3466 return transport_controller_->LookupDtlsTransportByMid(mid);
3467}
3468
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003469rtc::scoped_refptr<DtlsTransport>
3470PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3471 return transport_controller_->LookupDtlsTransportByMid(mid);
3472}
3473
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003474const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003475 return pending_local_description_ ? pending_local_description_.get()
3476 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003477}
3478
3479const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003480 return pending_remote_description_ ? pending_remote_description_.get()
3481 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003482}
3483
deadbeeffe4a8a42016-12-20 17:56:17 -08003484const SessionDescriptionInterface* PeerConnection::current_local_description()
3485 const {
Steve Anton75737c02017-11-06 10:37:17 -08003486 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003487}
3488
3489const SessionDescriptionInterface* PeerConnection::current_remote_description()
3490 const {
Steve Anton75737c02017-11-06 10:37:17 -08003491 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003492}
3493
3494const SessionDescriptionInterface* PeerConnection::pending_local_description()
3495 const {
Steve Anton75737c02017-11-06 10:37:17 -08003496 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003497}
3498
3499const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3500 const {
Steve Anton75737c02017-11-06 10:37:17 -08003501 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003502}
3503
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003504void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003505 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506 // Update stats here so that we have the most recent stats for tracks and
3507 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003508 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509
Steve Anton75737c02017-11-06 10:37:17 -08003510 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003511 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003512
Mirko Bonadei739baf02019-01-27 17:29:42 +01003513 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003514 transceiver->Stop();
3515 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003516
3517 // Ensure that all asynchronous stats requests are completed before destroying
3518 // the transport controller below.
3519 if (stats_collector_) {
3520 stats_collector_->WaitForPendingRequest();
3521 }
3522
3523 // Don't destroy BaseChannels until after stats has been cleaned up so that
3524 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003525 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003526
Qingsi Wang93a84392018-01-30 17:13:09 -08003527 // The event log is used in the transport controller, which must be outlived
3528 // by the former. CreateOffer by the peer connection is implemented
3529 // asynchronously and if the peer connection is closed without resetting the
3530 // WebRTC session description factory, the session description factory would
3531 // call the transport controller.
3532 webrtc_session_desc_factory_.reset();
3533 transport_controller_.reset();
3534
deadbeef42a42632017-03-10 15:18:00 -08003535 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003536 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3537 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003538
Steve Anton978b8762017-09-29 12:15:02 -07003539 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003540 call_.reset();
3541 // The event log must outlive call (and any other object that uses it).
3542 event_log_.reset();
3543 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003544 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003545 // The .h file says that observer can be discarded after close() returns.
3546 // Make sure this is true.
3547 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003548}
3549
Steve Antonad182762018-09-05 20:22:40 +00003550void PeerConnection::OnMessage(rtc::Message* msg) {
3551 switch (msg->message_id) {
3552 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3553 SetSessionDescriptionMsg* param =
3554 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3555 param->observer->OnSuccess();
3556 delete param;
3557 break;
3558 }
3559 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3560 SetSessionDescriptionMsg* param =
3561 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3562 param->observer->OnFailure(std::move(param->error));
3563 delete param;
3564 break;
3565 }
3566 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3567 CreateSessionDescriptionMsg* param =
3568 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3569 param->observer->OnFailure(std::move(param->error));
3570 delete param;
3571 break;
3572 }
3573 case MSG_GETSTATS: {
3574 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3575 StatsReports reports;
3576 stats_->GetStats(param->track, &reports);
3577 param->observer->OnComplete(reports);
3578 delete param;
3579 break;
3580 }
3581 case MSG_FREE_DATACHANNELS: {
3582 sctp_data_channels_to_free_.clear();
3583 break;
3584 }
3585 case MSG_REPORT_USAGE_PATTERN: {
3586 ReportUsagePattern();
3587 break;
3588 }
3589 default:
3590 RTC_NOTREACHED() << "Not implemented";
3591 break;
3592 }
3593}
3594
Steve Antonafb0bb72018-02-20 11:35:37 -08003595cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3596 RTC_DCHECK(!IsUnifiedPlan());
3597 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3598 GetAudioTransceiver()->internal()->channel());
3599 if (voice_channel) {
3600 return voice_channel->media_channel();
3601 } else {
3602 return nullptr;
3603 }
3604}
3605
3606cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3607 RTC_DCHECK(!IsUnifiedPlan());
3608 auto* video_channel = static_cast<cricket::VideoChannel*>(
3609 GetVideoTransceiver()->internal()->channel());
3610 if (video_channel) {
3611 return video_channel->media_channel();
3612 } else {
3613 return nullptr;
3614 }
3615}
3616
Steve Anton4171afb2017-11-20 10:20:22 -08003617void PeerConnection::CreateAudioReceiver(
3618 MediaStreamInterface* stream,
3619 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003620 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3621 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003622 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3623 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003624 auto* audio_receiver = new AudioRtpReceiver(
3625 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003626 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003627 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3628 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3629 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003630 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003631 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003632 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003633}
3634
Steve Anton4171afb2017-11-20 10:20:22 -08003635void PeerConnection::CreateVideoReceiver(
3636 MediaStreamInterface* stream,
3637 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003638 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3639 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003640 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3641 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003642 auto* video_receiver = new VideoRtpReceiver(
3643 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003644 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003645 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3646 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3647 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003648 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003649 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003650 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003651}
3652
deadbeef70ab1a12015-09-28 16:53:55 -07003653// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3654// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003655rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003656 const RtpSenderInfo& remote_sender_info) {
3657 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3658 if (!receiver) {
3659 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3660 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003661 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003662 }
Steve Anton4171afb2017-11-20 10:20:22 -08003663 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3664 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3665 } else {
3666 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3667 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003668 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003669}
3670
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003671void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3672 MediaStreamInterface* stream) {
3673 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003674 RTC_DCHECK(track);
3675 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003676 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003677 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003678 // We already have a sender for this track, so just change the stream_id
3679 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003680 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003681 return;
3682 }
3683
3684 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003685 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003686 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003687 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003688 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003689 // If the sender has already been configured in SDP, we call SetSsrc,
3690 // which will connect the sender to the underlying transport. This can
3691 // occur if a local session description that contains the ID of the sender
3692 // is set before AddStream is called. It can also occur if the local
3693 // session description is not changed and RemoveStream is called, and
3694 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003695 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003696 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003697 if (sender_info) {
3698 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003699 }
3700}
3701
3702// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3703// indefinitely, when we have unified plan SDP.
3704void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3705 MediaStreamInterface* stream) {
3706 RTC_DCHECK(!IsClosed());
3707 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003708 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003709 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3710 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003711 return;
3712 }
Steve Anton4171afb2017-11-20 10:20:22 -08003713 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003714}
3715
3716void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3717 MediaStreamInterface* stream) {
3718 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003719 RTC_DCHECK(track);
3720 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003721 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003722 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003723 // We already have a sender for this track, so just change the stream_id
3724 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003725 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003726 return;
3727 }
3728
3729 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003730 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003731 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003732 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003733 GetVideoTransceiver()->internal()->AddSender(new_sender);
3734 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003735 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003736 if (sender_info) {
3737 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003738 }
3739}
3740
3741void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3742 MediaStreamInterface* stream) {
3743 RTC_DCHECK(!IsClosed());
3744 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003745 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003746 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3747 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003748 return;
3749 }
Steve Anton4171afb2017-11-20 10:20:22 -08003750 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003751}
3752
Steve Antonba818672017-11-06 10:21:57 -08003753void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003754 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003755 if (ice_connection_state_ == new_state) {
3756 return;
3757 }
3758
deadbeefcbecd352015-09-23 11:50:27 -07003759 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003760 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003761 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003762 return;
3763 }
Steve Antonba818672017-11-06 10:21:57 -08003764
Mirko Bonadei675513b2017-11-09 11:09:25 +01003765 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3766 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003767 RTC_DCHECK(ice_connection_state_ !=
3768 PeerConnectionInterface::kIceConnectionClosed);
3769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003770 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003771 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003772}
3773
Alex Loiko9289eda2018-11-23 16:18:59 +00003774void PeerConnection::SetStandardizedIceConnectionState(
3775 PeerConnectionInterface::IceConnectionState new_state) {
3776 RTC_DCHECK(signaling_thread()->IsCurrent());
3777 if (standardized_ice_connection_state_ == new_state)
3778 return;
3779 if (IsClosed())
3780 return;
3781 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003782 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003783}
3784
Jonas Olsson635474e2018-10-18 15:58:17 +02003785void PeerConnection::SetConnectionState(
3786 PeerConnectionInterface::PeerConnectionState new_state) {
3787 RTC_DCHECK(signaling_thread()->IsCurrent());
3788 if (connection_state_ == new_state)
3789 return;
3790 if (IsClosed())
3791 return;
3792 connection_state_ = new_state;
3793 Observer()->OnConnectionChange(new_state);
3794}
3795
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003796void PeerConnection::OnIceGatheringChange(
3797 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003798 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003799 if (IsClosed()) {
3800 return;
3801 }
3802 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003803 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003804}
3805
jbauch81bf7b02017-03-25 08:31:12 -07003806void PeerConnection::OnIceCandidate(
3807 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003808 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003809 if (IsClosed()) {
3810 return;
3811 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003812 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003813 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3814 candidate->candidate().address().IsPrivateIP()) {
3815 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3816 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003817 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003818}
3819
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003820void PeerConnection::OnIceCandidatesRemoved(
3821 const std::vector<cricket::Candidate>& candidates) {
3822 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003823 if (IsClosed()) {
3824 return;
3825 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003826 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003827}
3828
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003829void PeerConnection::ChangeSignalingState(
3830 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003831 RTC_DCHECK(signaling_thread()->IsCurrent());
3832 if (signaling_state_ == signaling_state) {
3833 return;
3834 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003835 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3836 << GetSignalingStateString(signaling_state_)
3837 << " New state: "
3838 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003839 signaling_state_ = signaling_state;
3840 if (signaling_state == kClosed) {
3841 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003842 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003843 standardized_ice_connection_state_ =
3844 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003845 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3846 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003847 if (ice_gathering_state_ != kIceGatheringComplete) {
3848 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003849 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003850 }
3851 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003852 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003853}
3854
deadbeefeb459812015-12-15 19:24:43 -08003855void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3856 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003857 if (IsClosed()) {
3858 return;
3859 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003860 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003861 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003862}
3863
deadbeefeb459812015-12-15 19:24:43 -08003864void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3865 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003866 if (IsClosed()) {
3867 return;
3868 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003869 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003870 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003871}
3872
3873void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3874 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003875 if (IsClosed()) {
3876 return;
3877 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003878 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003879 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003880}
3881
3882void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3883 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003884 if (IsClosed()) {
3885 return;
3886 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003887 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003888 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003889}
3890
Henrik Boström31638672017-11-23 17:48:32 +01003891void PeerConnection::PostSetSessionDescriptionSuccess(
3892 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003893 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3894 signaling_thread()->Post(RTC_FROM_HERE, this,
3895 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003896}
3897
deadbeefab9b2d12015-10-14 11:33:11 -07003898void PeerConnection::PostSetSessionDescriptionFailure(
3899 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003900 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003901 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003902 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3903 msg->error = std::move(error);
3904 signaling_thread()->Post(RTC_FROM_HERE, this,
3905 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003906}
3907
3908void PeerConnection::PostCreateSessionDescriptionFailure(
3909 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003910 RTCError error) {
3911 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003912 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3913 msg->error = std::move(error);
3914 signaling_thread()->Post(RTC_FROM_HERE, this,
3915 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003916}
3917
zhihuang1c378ed2017-08-17 14:10:50 -07003918void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003919 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003920 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003921 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003922
Steve Antondcc3c022017-12-22 16:02:54 -08003923 if (IsUnifiedPlan()) {
3924 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3925 } else {
3926 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3927 }
3928
Steve Antonfa2260d2017-12-28 16:38:23 -08003929 // Intentionally unset the data channel type for RTP data channel with the
3930 // second condition. Otherwise the RTP data channels would be successfully
3931 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3932 // when building with chromium. We want to leave RTP data channels broken, so
3933 // people won't try to use them.
3934 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3935 session_options->data_channel_type = data_channel_type();
3936 }
3937
Steve Antondcc3c022017-12-22 16:02:54 -08003938 // Apply ICE restart flag and renomination flag.
3939 for (auto& options : session_options->media_description_options) {
3940 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3941 options.transport_options.enable_ice_renomination =
3942 configuration_.enable_ice_renomination;
3943 }
3944
3945 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003946 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003947 session_options->pooled_ice_credentials =
3948 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3949 RTC_FROM_HERE,
3950 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3951 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003952 session_options->offer_extmap_allow_mixed =
3953 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003954}
3955
3956void PeerConnection::GetOptionsForPlanBOffer(
3957 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3958 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003959 // Figure out transceiver directional preferences.
3960 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3961 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3962
3963 // By default, generate sendrecv/recvonly m= sections.
3964 bool recv_audio = true;
3965 bool recv_video = true;
3966
3967 // By default, only offer a new m= section if we have media to send with it.
3968 bool offer_new_audio_description = send_audio;
3969 bool offer_new_video_description = send_video;
3970 bool offer_new_data_description = HasDataChannels();
3971
3972 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003973 if (offer_answer_options.offer_to_receive_audio !=
3974 RTCOfferAnswerOptions::kUndefined) {
3975 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003976 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003977 offer_new_audio_description ||
3978 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003979 }
Steve Antondcc3c022017-12-22 16:02:54 -08003980 if (offer_answer_options.offer_to_receive_video !=
3981 RTCOfferAnswerOptions::kUndefined) {
3982 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003983 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003984 offer_new_video_description ||
3985 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003986 }
3987
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003988 absl::optional<size_t> audio_index;
3989 absl::optional<size_t> video_index;
3990 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003991 // If a current description exists, generate m= sections in the same order,
3992 // using the first audio/video/data section that appears and rejecting
3993 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003994 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003995 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003996 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003997 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3998 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3999 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004000 }
4001
zhihuang1c378ed2017-08-17 14:10:50 -07004002 // Add audio/video/data m= sections to the end if needed.
4003 if (!audio_index && offer_new_audio_description) {
4004 session_options->media_description_options.push_back(
4005 cricket::MediaDescriptionOptions(
4006 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004007 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4008 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004009 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004010 }
zhihuang1c378ed2017-08-17 14:10:50 -07004011 if (!video_index && offer_new_video_description) {
4012 session_options->media_description_options.push_back(
4013 cricket::MediaDescriptionOptions(
4014 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004015 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4016 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004017 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004018 }
zhihuang1c378ed2017-08-17 14:10:50 -07004019 if (!data_index && offer_new_data_description) {
4020 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004021 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004022 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004023 }
4024
4025 cricket::MediaDescriptionOptions* audio_media_description_options =
4026 !audio_index ? nullptr
4027 : &session_options->media_description_options[*audio_index];
4028 cricket::MediaDescriptionOptions* video_media_description_options =
4029 !video_index ? nullptr
4030 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004031
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004032 AddPlanBRtpSenderOptions(GetSendersInternal(),
4033 audio_media_description_options,
4034 video_media_description_options,
4035 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004036}
4037
Steve Antondcc3c022017-12-22 16:02:54 -08004038static cricket::MediaDescriptionOptions
4039GetMediaDescriptionOptionsForTransceiver(
4040 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4041 transceiver,
4042 const std::string& mid) {
4043 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004044 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004045 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004046 // This behavior is specified in JSEP. The gist is that:
4047 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4048 // sendrecv.
4049 // 2. If the MSID is included, then it must be included in any subsequent
4050 // offer/answer exactly the same until the RtpTransceiver is stopped.
4051 if (!transceiver->stopped() &&
4052 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
4053 transceiver->internal()->has_ever_been_used_to_send())) {
4054 cricket::SenderOptions sender_options;
4055 sender_options.track_id = transceiver->sender()->id();
4056 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02004057 int num_send_encoding_layers =
4058 transceiver->sender()->init_send_encodings().size();
4059 sender_options.num_sim_layers =
4060 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08004061 media_description_options.sender_options.push_back(sender_options);
4062 }
Steve Antondcc3c022017-12-22 16:02:54 -08004063 return media_description_options;
4064}
4065
Steve Anton5c72e712018-12-10 14:25:30 -08004066// Returns the ContentInfo at mline index |i|, or null if none exists.
4067static const ContentInfo* GetContentByIndex(
4068 const SessionDescriptionInterface* sdesc,
4069 size_t i) {
4070 if (!sdesc) {
4071 return nullptr;
4072 }
4073 const ContentInfos& contents = sdesc->description()->contents();
4074 return (i < contents.size() ? &contents[i] : nullptr);
4075}
4076
Steve Antondcc3c022017-12-22 16:02:54 -08004077void PeerConnection::GetOptionsForUnifiedPlanOffer(
4078 const RTCOfferAnswerOptions& offer_answer_options,
4079 cricket::MediaSessionOptions* session_options) {
4080 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4081 // Offers) and 5.2.2 (Subsequent Offers).
4082 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4083 const ContentInfos& local_contents =
4084 (local_description() ? local_description()->description()->contents()
4085 : ContentInfos());
4086 const ContentInfos& remote_contents =
4087 (remote_description() ? remote_description()->description()->contents()
4088 : ContentInfos());
4089 // The mline indices that can be recycled. New transceivers should reuse these
4090 // slots first.
4091 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004092 // First, go through each media section that exists in either the local or
4093 // remote description and generate a media section in this offer for the
4094 // associated transceiver. If a media section can be recycled, generate a
4095 // default, rejected media section here that can be later overwritten.
4096 for (size_t i = 0;
4097 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4098 // Either |local_content| or |remote_content| is non-null.
4099 const ContentInfo* local_content =
4100 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004101 const ContentInfo* current_local_content =
4102 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004103 const ContentInfo* remote_content =
4104 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004105 const ContentInfo* current_remote_content =
4106 GetContentByIndex(current_remote_description(), i);
4107 bool had_been_rejected =
4108 (current_local_content && current_local_content->rejected) ||
4109 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004110 const std::string& mid =
4111 (local_content ? local_content->name : remote_content->name);
4112 cricket::MediaType media_type =
4113 (local_content ? local_content->media_description()->type()
4114 : remote_content->media_description()->type());
4115 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4116 media_type == cricket::MEDIA_TYPE_VIDEO) {
4117 auto transceiver = GetAssociatedTransceiver(mid);
4118 RTC_CHECK(transceiver);
4119 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004120 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004121 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004122 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004123 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4124 RtpTransceiverDirection::kInactive,
4125 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004126 recycleable_mline_indices.push(i);
4127 } else {
4128 session_options->media_description_options.push_back(
4129 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4130 // CreateOffer shouldn't really cause any state changes in
4131 // PeerConnection, but we need a way to match new transceivers to new
4132 // media sections in SetLocalDescription and JSEP specifies this is done
4133 // by recording the index of the media section generated for the
4134 // transceiver in the offer.
4135 transceiver->internal()->set_mline_index(i);
4136 }
4137 } else {
4138 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004139 RTC_CHECK(GetDataMid());
4140 if (had_been_rejected || mid != *GetDataMid()) {
4141 session_options->media_description_options.push_back(
4142 GetMediaDescriptionOptionsForRejectedData(mid));
4143 } else {
4144 session_options->media_description_options.push_back(
4145 GetMediaDescriptionOptionsForActiveData(mid));
4146 }
Steve Antondcc3c022017-12-22 16:02:54 -08004147 }
4148 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004149
Steve Antondcc3c022017-12-22 16:02:54 -08004150 // Next, look for transceivers that are newly added (that is, are not stopped
4151 // and not associated). Reuse media sections marked as recyclable first,
4152 // otherwise append to the end of the offer. New media sections should be
4153 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004154 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004155 if (transceiver->mid() || transceiver->stopped()) {
4156 continue;
4157 }
4158 size_t mline_index;
4159 if (!recycleable_mline_indices.empty()) {
4160 mline_index = recycleable_mline_indices.front();
4161 recycleable_mline_indices.pop();
4162 session_options->media_description_options[mline_index] =
4163 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004164 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004165 } else {
4166 mline_index = session_options->media_description_options.size();
4167 session_options->media_description_options.push_back(
4168 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004169 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004170 }
4171 // See comment above for why CreateOffer changes the transceiver's state.
4172 transceiver->internal()->set_mline_index(mline_index);
4173 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004174 // Lastly, add a m-section if we have local data channels and an m section
4175 // does not already exist.
4176 if (!GetDataMid() && HasDataChannels()) {
4177 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004178 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004179 }
Steve Antondcc3c022017-12-22 16:02:54 -08004180}
4181
4182void PeerConnection::GetOptionsForAnswer(
4183 const RTCOfferAnswerOptions& offer_answer_options,
4184 cricket::MediaSessionOptions* session_options) {
4185 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4186
4187 if (IsUnifiedPlan()) {
4188 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4189 } else {
4190 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4191 }
4192
Steve Antonfa2260d2017-12-28 16:38:23 -08004193 // Intentionally unset the data channel type for RTP data channel. Otherwise
4194 // the RTP data channels would be successfully negotiated by default and the
4195 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4196 // We want to leave RTP data channels broken, so people won't try to use them.
4197 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4198 session_options->data_channel_type = data_channel_type();
4199 }
4200
Steve Antondcc3c022017-12-22 16:02:54 -08004201 // Apply ICE renomination flag.
4202 for (auto& options : session_options->media_description_options) {
4203 options.transport_options.enable_ice_renomination =
4204 configuration_.enable_ice_renomination;
4205 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004206
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()));
deadbeefab9b2d12015-10-14 11:33:11 -07004214}
4215
Steve Antondcc3c022017-12-22 16:02:54 -08004216void PeerConnection::GetOptionsForPlanBAnswer(
4217 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004218 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004219 // Figure out transceiver directional preferences.
4220 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4221 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4222
4223 // By default, generate sendrecv/recvonly m= sections. The direction is also
4224 // restricted by the direction in the offer.
4225 bool recv_audio = true;
4226 bool recv_video = true;
4227
4228 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004229 if (offer_answer_options.offer_to_receive_audio !=
4230 RTCOfferAnswerOptions::kUndefined) {
4231 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004232 }
Steve Antondcc3c022017-12-22 16:02:54 -08004233 if (offer_answer_options.offer_to_receive_video !=
4234 RTCOfferAnswerOptions::kUndefined) {
4235 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004236 }
4237
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004238 absl::optional<size_t> audio_index;
4239 absl::optional<size_t> video_index;
4240 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004241
4242 // Generate m= sections that match those in the offer.
4243 // Note that mediasession.cc will handle intersection our preferred
4244 // direction with the offered direction.
4245 GenerateMediaDescriptionOptions(
4246 remote_description(),
4247 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4248 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4249 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004250
4251 cricket::MediaDescriptionOptions* audio_media_description_options =
4252 !audio_index ? nullptr
4253 : &session_options->media_description_options[*audio_index];
4254 cricket::MediaDescriptionOptions* video_media_description_options =
4255 !video_index ? nullptr
4256 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004257
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004258 AddPlanBRtpSenderOptions(GetSendersInternal(),
4259 audio_media_description_options,
4260 video_media_description_options,
4261 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004262}
zhihuangaf388472016-11-02 16:49:48 -07004263
Steve Antondcc3c022017-12-22 16:02:54 -08004264void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4265 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4266 cricket::MediaSessionOptions* session_options) {
4267 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4268 // Answers) and 5.3.2 (Subsequent Answers).
4269 RTC_DCHECK(remote_description());
4270 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4271 for (const ContentInfo& content :
4272 remote_description()->description()->contents()) {
4273 cricket::MediaType media_type = content.media_description()->type();
4274 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4275 media_type == cricket::MEDIA_TYPE_VIDEO) {
4276 auto transceiver = GetAssociatedTransceiver(content.name);
4277 RTC_CHECK(transceiver);
4278 session_options->media_description_options.push_back(
4279 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4280 } else {
4281 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004282 // Reject all data sections if data channels are disabled.
4283 // Reject a data section if it has already been rejected.
4284 // Reject all data sections except for the first one.
4285 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4286 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004287 session_options->media_description_options.push_back(
4288 GetMediaDescriptionOptionsForRejectedData(content.name));
4289 } else {
4290 session_options->media_description_options.push_back(
4291 GetMediaDescriptionOptionsForActiveData(content.name));
4292 }
Steve Antondcc3c022017-12-22 16:02:54 -08004293 }
4294 }
htaa2a49d92016-03-04 02:51:39 -08004295}
4296
zhihuang1c378ed2017-08-17 14:10:50 -07004297void PeerConnection::GenerateMediaDescriptionOptions(
4298 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004299 RtpTransceiverDirection audio_direction,
4300 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004301 absl::optional<size_t>* audio_index,
4302 absl::optional<size_t>* video_index,
4303 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004304 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004305 for (const cricket::ContentInfo& content :
4306 session_desc->description()->contents()) {
4307 if (IsAudioContent(&content)) {
4308 // If we already have an audio m= section, reject this extra one.
4309 if (*audio_index) {
4310 session_options->media_description_options.push_back(
4311 cricket::MediaDescriptionOptions(
4312 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004313 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004314 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004315 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004316 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004317 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4318 content.name, audio_direction,
4319 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004320 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004321 }
4322 } else if (IsVideoContent(&content)) {
4323 // If we already have an video m= section, reject this extra one.
4324 if (*video_index) {
4325 session_options->media_description_options.push_back(
4326 cricket::MediaDescriptionOptions(
4327 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004328 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004329 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004330 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004331 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004332 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4333 content.name, video_direction,
4334 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004335 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004336 }
4337 } else {
4338 RTC_DCHECK(IsDataContent(&content));
4339 // If we already have an data m= section, reject this extra one.
4340 if (*data_index) {
4341 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004342 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004343 } else {
4344 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004345 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004346 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004347 }
4348 }
htaa2a49d92016-03-04 02:51:39 -08004349 }
deadbeefab9b2d12015-10-14 11:33:11 -07004350}
4351
Steve Antonfa2260d2017-12-28 16:38:23 -08004352cricket::MediaDescriptionOptions
4353PeerConnection::GetMediaDescriptionOptionsForActiveData(
4354 const std::string& mid) const {
4355 // Direction for data sections is meaningless, but legacy endpoints might
4356 // expect sendrecv.
4357 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4358 RtpTransceiverDirection::kSendRecv,
4359 /*stopped=*/false);
4360 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4361 return options;
4362}
4363
4364cricket::MediaDescriptionOptions
4365PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4366 const std::string& mid) const {
4367 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4368 RtpTransceiverDirection::kInactive,
4369 /*stopped=*/true);
4370 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4371 return options;
4372}
4373
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004374absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004375 switch (data_channel_type_) {
4376 case cricket::DCT_RTP:
4377 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004378 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004379 }
4380 return rtp_data_channel_->content_name();
4381 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004382 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004383 case cricket::DCT_MEDIA_TRANSPORT:
4384 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004385 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004386 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004387 }
4388}
4389
Steve Anton4171afb2017-11-20 10:20:22 -08004390void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4391 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4392 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004393 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004394}
4395
Steve Anton4171afb2017-11-20 10:20:22 -08004396void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004397 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004398 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004399 cricket::MediaType media_type,
4400 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004401 RTC_DCHECK(!IsUnifiedPlan());
4402
Steve Anton4171afb2017-11-20 10:20:22 -08004403 std::vector<RtpSenderInfo>* current_senders =
4404 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004405
Steve Anton4171afb2017-11-20 10:20:22 -08004406 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004407 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004408 for (auto sender_it = current_senders->begin();
4409 sender_it != current_senders->end();
4410 /* incremented manually */) {
4411 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004412 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004413 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004414 std::string params_stream_id;
4415 if (params) {
4416 params_stream_id =
4417 (!params->first_stream_id().empty() ? params->first_stream_id()
4418 : kDefaultStreamId);
4419 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004420 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004421 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004422 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004423 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004424 sender_exists) {
4425 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004426 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004427 OnRemoteSenderRemoved(info, media_type);
4428 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004429 }
4430 }
4431
Steve Anton4171afb2017-11-20 10:20:22 -08004432 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004433 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004434 if (!params.has_ssrcs()) {
4435 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4436 // sender, this means it is coming from a Unified Plan endpoint,so we just
4437 // create a default.
4438 default_sender_needed = true;
4439 break;
4440 }
4441
Seth Hampson845e8782018-03-02 11:34:10 -08004442 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004443 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004444 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4445 // not supported in Plan B, we just take the first here and create the
4446 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004447 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004448 (!params.first_stream_id().empty() ? params.first_stream_id()
4449 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004450 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004451 uint32_t ssrc = params.first_ssrc();
4452
4453 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004454 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004455 if (!stream) {
4456 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004457 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004458 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004459 remote_streams_->AddStream(stream);
4460 new_streams->AddStream(stream);
4461 }
4462
Steve Anton4171afb2017-11-20 10:20:22 -08004463 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004464 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004465 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004466 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004467 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004468 }
4469 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004470
Steve Anton4171afb2017-11-20 10:20:22 -08004471 // Add default sender if necessary.
4472 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004473 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004474 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004475 if (!default_stream) {
4476 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004477 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004478 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004479 remote_streams_->AddStream(default_stream);
4480 new_streams->AddStream(default_stream);
4481 }
Steve Anton4171afb2017-11-20 10:20:22 -08004482 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4483 ? kDefaultAudioSenderId
4484 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004485 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004486 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004487 if (!default_sender_info) {
4488 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004489 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004490 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004491 }
4492 }
deadbeefab9b2d12015-10-14 11:33:11 -07004493}
4494
Steve Anton4171afb2017-11-20 10:20:22 -08004495void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4496 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004497 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4498 << " receiver for track_id=" << sender_info.sender_id
4499 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004500
Steve Anton3d954a62018-04-02 11:27:23 -07004501 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004502 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004503 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004504 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004505 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004506 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004507 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004508 }
4509}
4510
Steve Anton4171afb2017-11-20 10:20:22 -08004511void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4512 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004513 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4514 << " receiver for track_id=" << sender_info.sender_id
4515 << " and stream_id=" << sender_info.stream_id;
4516
Seth Hampson845e8782018-03-02 11:34:10 -08004517 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004518
Henrik Boström933d8b02017-10-10 10:05:16 -07004519 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004520 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004521 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4522 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004523 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004524 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004525 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004526 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004527 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004528 }
4529 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004530 // Stopping or destroying a VideoRtpReceiver will end the
4531 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004532 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004533 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004534 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004535 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004536 // There's no guarantee the track is still available, e.g. the track may
4537 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004538 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004539 }
4540 } else {
nisseede5da42017-01-12 05:15:36 -08004541 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004542 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004543 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004544 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004545 }
deadbeefab9b2d12015-10-14 11:33:11 -07004546}
4547
4548void PeerConnection::UpdateEndedRemoteMediaStreams() {
4549 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4550 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4551 MediaStreamInterface* stream = remote_streams_->at(i);
4552 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4553 streams_to_remove.push_back(stream);
4554 }
4555 }
4556
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004557 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004558 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004559 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004560 }
4561}
4562
Steve Anton4171afb2017-11-20 10:20:22 -08004563void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004564 const std::vector<cricket::StreamParams>& streams,
4565 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004566 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004567
Seth Hampson845e8782018-03-02 11:34:10 -08004568 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004569 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004570 for (auto sender_it = current_senders->begin();
4571 sender_it != current_senders->end();
4572 /* incremented manually */) {
4573 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004574 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004575 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4576 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004577 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004578 OnLocalSenderRemoved(info, media_type);
4579 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004580 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004581 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004582 }
4583 }
4584
Steve Anton4171afb2017-11-20 10:20:22 -08004585 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004586 for (const cricket::StreamParams& params : streams) {
4587 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004588 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004589 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004590 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004591 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004592 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004593 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004594 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004595 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004596 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004597 }
4598 }
4599}
4600
Steve Anton4171afb2017-11-20 10:20:22 -08004601void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4602 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004603 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004604 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004605 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004606 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4607 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004608 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004609 return;
4610 }
4611
deadbeeffac06552015-11-25 11:26:01 -08004612 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004613 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004614 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004615 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004616 }
deadbeeffac06552015-11-25 11:26:01 -08004617
Seth Hampson5b4f0752018-04-02 16:31:36 -07004618 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004619 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004620}
4621
Steve Anton4171afb2017-11-20 10:20:22 -08004622void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4623 cricket::MediaType media_type) {
4624 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004625 if (!sender) {
4626 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004627 // SessionDescriptions has been renegotiated.
4628 return;
4629 }
deadbeeffac06552015-11-25 11:26:01 -08004630
4631 // A sender has been removed from the SessionDescription but it's still
4632 // associated with the PeerConnection. This only occurs if the SDP doesn't
4633 // match with the calls to CreateSender, AddStream and RemoveStream.
4634 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004635 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004636 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004637 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004638 }
deadbeeffac06552015-11-25 11:26:01 -08004639
Steve Anton4171afb2017-11-20 10:20:22 -08004640 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004641}
4642
4643void PeerConnection::UpdateLocalRtpDataChannels(
4644 const cricket::StreamParamsVec& streams) {
4645 std::vector<std::string> existing_channels;
4646
4647 // Find new and active data channels.
4648 for (const cricket::StreamParams& params : streams) {
4649 // |it->sync_label| is actually the data channel label. The reason is that
4650 // we use the same naming of data channels as we do for
4651 // MediaStreams and Tracks.
4652 // For MediaStreams, the sync_label is the MediaStream label and the
4653 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004654 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004655 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004656 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004657 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004658 continue;
4659 }
4660 // Set the SSRC the data channel should use for sending.
4661 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4662 existing_channels.push_back(data_channel_it->first);
4663 }
4664
4665 UpdateClosingRtpDataChannels(existing_channels, true);
4666}
4667
4668void PeerConnection::UpdateRemoteRtpDataChannels(
4669 const cricket::StreamParamsVec& streams) {
4670 std::vector<std::string> existing_channels;
4671
4672 // Find new and active data channels.
4673 for (const cricket::StreamParams& params : streams) {
4674 // The data channel label is either the mslabel or the SSRC if the mslabel
4675 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004676 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004677 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004678 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004679 auto data_channel_it = rtp_data_channels_.find(label);
4680 if (data_channel_it == rtp_data_channels_.end()) {
4681 // This is a new data channel.
4682 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4683 } else {
4684 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4685 }
4686 existing_channels.push_back(label);
4687 }
4688
4689 UpdateClosingRtpDataChannels(existing_channels, false);
4690}
4691
4692void PeerConnection::UpdateClosingRtpDataChannels(
4693 const std::vector<std::string>& active_channels,
4694 bool is_local_update) {
4695 auto it = rtp_data_channels_.begin();
4696 while (it != rtp_data_channels_.end()) {
4697 DataChannel* data_channel = it->second;
4698 if (std::find(active_channels.begin(), active_channels.end(),
4699 data_channel->label()) != active_channels.end()) {
4700 ++it;
4701 continue;
4702 }
4703
4704 if (is_local_update) {
4705 data_channel->SetSendSsrc(0);
4706 } else {
4707 data_channel->RemotePeerRequestClose();
4708 }
4709
4710 if (data_channel->state() == DataChannel::kClosed) {
4711 rtp_data_channels_.erase(it);
4712 it = rtp_data_channels_.begin();
4713 } else {
4714 ++it;
4715 }
4716 }
4717}
4718
4719void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4720 uint32_t remote_ssrc) {
4721 rtc::scoped_refptr<DataChannel> channel(
4722 InternalCreateDataChannel(label, nullptr));
4723 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004724 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004725 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004726 return;
4727 }
4728 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004729 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4730 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004731 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004732}
4733
4734rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4735 const std::string& label,
4736 const InternalDataChannelInit* config) {
4737 if (IsClosed()) {
4738 return nullptr;
4739 }
Steve Anton75737c02017-11-06 10:37:17 -08004740 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004741 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004742 << "InternalCreateDataChannel: Data is not supported in this call.";
4743 return nullptr;
4744 }
4745 InternalDataChannelInit new_config =
4746 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004747 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004748 if (new_config.id < 0) {
4749 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004750 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004751 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004752 RTC_LOG(LS_ERROR)
4753 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004754 return nullptr;
4755 }
4756 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004757 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004758 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004759 return nullptr;
4760 }
4761 }
4762
Steve Anton75737c02017-11-06 10:37:17 -08004763 rtc::scoped_refptr<DataChannel> channel(
4764 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004765 if (!channel) {
4766 sid_allocator_.ReleaseSid(new_config.id);
4767 return nullptr;
4768 }
4769
4770 if (channel->data_channel_type() == cricket::DCT_RTP) {
4771 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004772 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4773 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004774 return nullptr;
4775 }
4776 rtp_data_channels_[channel->label()] = channel;
4777 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004778 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004779 sctp_data_channels_.push_back(channel);
4780 channel->SignalClosed.connect(this,
4781 &PeerConnection::OnSctpDataChannelClosed);
4782 }
4783
Steve Anton2d8609c2018-01-23 16:38:46 -08004784 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004785 return channel;
4786}
4787
4788bool PeerConnection::HasDataChannels() const {
4789 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4790}
4791
4792void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4793 for (const auto& channel : sctp_data_channels_) {
4794 if (channel->id() < 0) {
4795 int sid;
4796 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004797 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004798 continue;
4799 }
4800 channel->SetSctpSid(sid);
4801 }
4802 }
4803}
4804
4805void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004806 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004807 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4808 ++it) {
4809 if (it->get() == channel) {
4810 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004811 // After the closing procedure is done, it's safe to use this ID for
4812 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004813 sid_allocator_.ReleaseSid(channel->id());
4814 }
deadbeefbd292462015-12-14 18:15:29 -08004815 // Since this method is triggered by a signal from the DataChannel,
4816 // we can't free it directly here; we need to free it asynchronously.
4817 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004818 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004819 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4820 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004821 return;
4822 }
4823 }
4824}
4825
deadbeefab9b2d12015-10-14 11:33:11 -07004826void PeerConnection::OnDataChannelDestroyed() {
4827 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4828 // DataChannel may callback to us and try to modify the list.
4829 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4830 temp_rtp_dcs.swap(rtp_data_channels_);
4831 for (const auto& kv : temp_rtp_dcs) {
4832 kv.second->OnTransportChannelDestroyed();
4833 }
4834
4835 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4836 temp_sctp_dcs.swap(sctp_data_channels_);
4837 for (const auto& channel : temp_sctp_dcs) {
4838 channel->OnTransportChannelDestroyed();
4839 }
4840}
4841
4842void PeerConnection::OnDataChannelOpenMessage(
4843 const std::string& label,
4844 const InternalDataChannelInit& config) {
4845 rtc::scoped_refptr<DataChannel> channel(
4846 InternalCreateDataChannel(label, &config));
4847 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004848 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004849 return;
4850 }
4851
deadbeefa601f5c2016-06-06 14:27:39 -07004852 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4853 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004854 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004855 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004856}
4857
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004858bool PeerConnection::HandleOpenMessage_s(
4859 const cricket::ReceiveDataParams& params,
4860 const rtc::CopyOnWriteBuffer& buffer) {
4861 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4862 // Received OPEN message; parse and signal that a new data channel should
4863 // be created.
4864 std::string label;
4865 InternalDataChannelInit config;
4866 config.id = params.ssrc;
4867 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4868 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4869 << params.ssrc;
4870 return true;
4871 }
4872 config.open_handshake_role = InternalDataChannelInit::kAcker;
4873 OnDataChannelOpenMessage(label, config);
4874 return true;
4875 }
4876 return false;
4877}
4878
Steve Anton4171afb2017-11-20 10:20:22 -08004879rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4880PeerConnection::GetAudioTransceiver() const {
4881 // This method only works with Plan B SDP, where there is a single
4882 // audio/video transceiver.
4883 RTC_DCHECK(!IsUnifiedPlan());
4884 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004885 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004886 return transceiver;
4887 }
4888 }
4889 RTC_NOTREACHED();
4890 return nullptr;
4891}
4892
4893rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4894PeerConnection::GetVideoTransceiver() const {
4895 // This method only works with Plan B SDP, where there is a single
4896 // audio/video transceiver.
4897 RTC_DCHECK(!IsUnifiedPlan());
4898 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004899 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004900 return transceiver;
4901 }
4902 }
4903 RTC_NOTREACHED();
4904 return nullptr;
4905}
4906
4907// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4908// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004909bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004910 switch (type) {
4911 case cricket::MEDIA_TYPE_AUDIO:
4912 return !GetAudioTransceiver()->internal()->senders().empty();
4913 case cricket::MEDIA_TYPE_VIDEO:
4914 return !GetVideoTransceiver()->internal()->senders().empty();
4915 case cricket::MEDIA_TYPE_DATA:
4916 return false;
4917 }
4918 RTC_NOTREACHED();
4919 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004920}
4921
Steve Anton4171afb2017-11-20 10:20:22 -08004922rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4923PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01004924 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08004925 for (auto sender : transceiver->internal()->senders()) {
4926 if (sender->track() == track) {
4927 return sender;
4928 }
4929 }
4930 }
4931 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004932}
4933
Steve Anton4171afb2017-11-20 10:20:22 -08004934rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4935PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01004936 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08004937 for (auto sender : transceiver->internal()->senders()) {
4938 if (sender->id() == sender_id) {
4939 return sender;
4940 }
4941 }
4942 }
4943 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004944}
4945
Steve Anton4171afb2017-11-20 10:20:22 -08004946rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4947PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01004948 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08004949 for (auto receiver : transceiver->internal()->receivers()) {
4950 if (receiver->id() == receiver_id) {
4951 return receiver;
4952 }
4953 }
4954 }
4955 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004956}
4957
Steve Anton4171afb2017-11-20 10:20:22 -08004958std::vector<PeerConnection::RtpSenderInfo>*
4959PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4960 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4961 media_type == cricket::MEDIA_TYPE_VIDEO);
4962 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4963 ? &remote_audio_sender_infos_
4964 : &remote_video_sender_infos_;
4965}
4966
4967std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004968 cricket::MediaType media_type) {
4969 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4970 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004971 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4972 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004973}
4974
Steve Anton4171afb2017-11-20 10:20:22 -08004975const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4976 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004977 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004978 const std::string sender_id) const {
4979 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004980 if (sender_info.stream_id == stream_id &&
4981 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004982 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004983 }
4984 }
4985 return nullptr;
4986}
4987
4988DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4989 for (const auto& channel : sctp_data_channels_) {
4990 if (channel->id() == sid) {
4991 return channel;
4992 }
4993 }
4994 return nullptr;
4995}
4996
deadbeef91dd5672016-05-18 16:55:30 -07004997bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004998 const cricket::ServerAddresses& stun_servers,
4999 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005000 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005001 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005002 // To handle both internal and externally created port allocator, we will
5003 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005004 port_allocator_flags_ = port_allocator_->flags();
5005 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5006 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5007 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005008 // If the disable-IPv6 flag was specified, we'll not override it
5009 // by experiment.
5010 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005011 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005012 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5013 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005014 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005015 }
5016
zhihuangb09b3f92017-03-07 14:40:51 -08005017 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005018 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005019 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005020 }
5021
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005022 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005023 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005024 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005025 }
5026
honghaiz60347052016-05-31 18:29:12 -07005027 if (configuration.candidate_network_policy ==
5028 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005029 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005030 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005031 }
5032
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005033 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005034 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005035 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5036 }
5037
Qingsi Wanga2d60672018-04-11 16:57:45 -07005038 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005039 // No step delay is used while allocating ports.
5040 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5041 port_allocator_->set_candidate_filter(
5042 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005043 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005044
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005045 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005046 for (auto& turn_server : turn_servers_copy) {
5047 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005048 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005049 // Call this last since it may create pooled allocator sessions using the
5050 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005051 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005052 stun_servers, std::move(turn_servers_copy),
5053 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5054 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005055 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005056 return true;
5057}
5058
deadbeef91dd5672016-05-18 16:55:30 -07005059bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005060 const cricket::ServerAddresses& stun_servers,
5061 const std::vector<cricket::RelayServerConfig>& turn_servers,
5062 IceTransportsType type,
5063 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005064 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005065 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005066 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005067 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005068 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005069 // According to JSEP, after setLocalDescription, changing the candidate pool
5070 // size is not allowed, and changing the set of ICE servers will not result
5071 // in new candidates being gathered.
5072 if (local_description()) {
5073 port_allocator_->FreezeCandidatePool();
5074 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005075 // Add the custom tls turn servers if they exist.
5076 auto turn_servers_copy = turn_servers;
5077 for (auto& turn_server : turn_servers_copy) {
5078 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5079 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005080 // Call this last since it may create pooled allocator sessions using the
5081 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005082 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005083 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5084 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005085}
5086
Steve Antonba818672017-11-06 10:21:57 -08005087cricket::ChannelManager* PeerConnection::channel_manager() const {
5088 return factory_->channel_manager();
5089}
5090
Elad Alon99c3fe52017-10-13 16:29:40 +02005091bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005092 std::unique_ptr<RtcEventLogOutput> output,
5093 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005094 if (!event_log_) {
5095 return false;
5096 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005097 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005098}
5099
5100void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005101 if (event_log_) {
5102 event_log_->StopLogging();
5103 }
ivoc14d5dbe2016-07-04 07:06:55 -07005104}
nisseeaabdf62017-05-05 02:23:02 -07005105
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005106cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005107 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005108 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005109 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005110 if (channel && channel->content_name() == content_name) {
5111 return channel;
5112 }
Steve Anton75737c02017-11-06 10:37:17 -08005113 }
5114 if (rtp_data_channel() &&
5115 rtp_data_channel()->content_name() == content_name) {
5116 return rtp_data_channel();
5117 }
5118 return nullptr;
5119}
5120
5121bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005122 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005123 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005124 RTC_LOG(LS_INFO)
5125 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005126 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005127 return false;
5128 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005129 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005130 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005131 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005132 return false;
5133 }
5134
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005135 absl::optional<rtc::SSLRole> dtls_role;
5136 if (sctp_mid_) {
5137 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5138 } else if (is_caller_) {
5139 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5140 }
Zhi Huange830e682018-03-30 10:48:35 -07005141 if (dtls_role) {
5142 *role = *dtls_role;
5143 return true;
5144 }
5145 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005146}
5147
5148bool PeerConnection::GetSslRole(const std::string& content_name,
5149 rtc::SSLRole* role) {
5150 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005151 RTC_LOG(LS_INFO)
5152 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005153 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005154 return false;
5155 }
5156
Zhi Huange830e682018-03-30 10:48:35 -07005157 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5158 if (dtls_role) {
5159 *role = *dtls_role;
5160 return true;
5161 }
5162 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005163}
5164
Steve Antonf8470812017-12-04 10:46:21 -08005165void PeerConnection::SetSessionError(SessionError error,
5166 const std::string& error_desc) {
5167 RTC_DCHECK_RUN_ON(signaling_thread());
5168 if (error != session_error_) {
5169 session_error_ = error;
5170 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005171 }
5172}
5173
Zhi Huange830e682018-03-30 10:48:35 -07005174RTCError PeerConnection::UpdateSessionState(
5175 SdpType type,
5176 cricket::ContentSource source,
5177 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005178 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005179
5180 // If there's already a pending error then no state transition should happen.
5181 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005182 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005183
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005184 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005185 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005186 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005187 }
5188
5189 // Update the signaling state according to the specified state machine (see
5190 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005191 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005192 ChangeSignalingState(source == cricket::CS_LOCAL
5193 ? PeerConnectionInterface::kHaveLocalOffer
5194 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005195 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005196 ChangeSignalingState(source == cricket::CS_LOCAL
5197 ? PeerConnectionInterface::kHaveLocalPrAnswer
5198 : PeerConnectionInterface::kHaveRemotePrAnswer);
5199 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005200 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005201 ChangeSignalingState(PeerConnectionInterface::kStable);
5202 }
5203
5204 // Update internal objects according to the session description's media
5205 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005206 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005207 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005208 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005209 }
5210
Steve Anton8a006912017-12-04 15:25:56 -08005211 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005212}
5213
Steve Anton8a006912017-12-04 15:25:56 -08005214RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005215 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005216 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005217 const SessionDescriptionInterface* sdesc =
5218 (source == cricket::CS_LOCAL ? local_description()
5219 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005220 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005221
5222 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005223 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005224 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005225 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005226 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005227 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005228 continue;
5229 }
5230 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005231 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005232 if (!content_desc) {
5233 continue;
5234 }
5235 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005236 bool success = (source == cricket::CS_LOCAL)
5237 ? channel->SetLocalContent(content_desc, type, &error)
5238 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005239 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005240 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005241 }
5242 }
5243
5244 // If using the RtpDataChannel, push down the new SDP section for it too.
5245 if (rtp_data_channel_) {
5246 const ContentInfo* data_content =
5247 cricket::GetFirstDataContent(sdesc->description());
5248 if (data_content && !data_content->rejected) {
5249 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005250 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005251 if (data_desc) {
5252 std::string error;
5253 bool success =
5254 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005255 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005256 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005257 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005258 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005259 }
Steve Anton75737c02017-11-06 10:37:17 -08005260 }
5261 }
5262 }
Steve Antoned10bd92017-12-05 10:52:59 -08005263
Steve Anton75737c02017-11-06 10:37:17 -08005264 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5265 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5266 if (sctp_transport_ && local_description() && remote_description() &&
5267 cricket::GetFirstDataContent(local_description()->description()) &&
5268 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005269 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005270 RTC_FROM_HERE,
5271 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005272 if (!success) {
5273 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5274 "Failed to push down SCTP parameters.");
5275 }
Steve Anton75737c02017-11-06 10:37:17 -08005276 }
Steve Antoned10bd92017-12-05 10:52:59 -08005277
Steve Anton8a006912017-12-04 15:25:56 -08005278 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005279}
5280
5281bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5282 RTC_DCHECK(network_thread()->IsCurrent());
5283 RTC_DCHECK(local_description());
5284 RTC_DCHECK(remote_description());
5285 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5286 // When we support "max-message-size", that would also be pushed down here.
5287 return sctp_transport_->Start(
5288 GetSctpPort(local_description()->description()),
5289 GetSctpPort(remote_description()->description()));
5290}
5291
Steve Anton8a006912017-12-04 15:25:56 -08005292RTCError PeerConnection::PushdownTransportDescription(
5293 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005294 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005295 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005296
Zhi Huange830e682018-03-30 10:48:35 -07005297 if (source == cricket::CS_LOCAL) {
5298 const SessionDescriptionInterface* sdesc = local_description();
5299 RTC_DCHECK(sdesc);
5300 return transport_controller_->SetLocalDescription(type,
5301 sdesc->description());
5302 } else {
5303 const SessionDescriptionInterface* sdesc = remote_description();
5304 RTC_DCHECK(sdesc);
5305 return transport_controller_->SetRemoteDescription(type,
5306 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005307 }
Steve Anton75737c02017-11-06 10:37:17 -08005308}
5309
5310bool PeerConnection::GetTransportDescription(
5311 const SessionDescription* description,
5312 const std::string& content_name,
5313 cricket::TransportDescription* tdesc) {
5314 if (!description || !tdesc) {
5315 return false;
5316 }
5317 const TransportInfo* transport_info =
5318 description->GetTransportInfoByName(content_name);
5319 if (!transport_info) {
5320 return false;
5321 }
5322 *tdesc = transport_info->description;
5323 return true;
5324}
5325
Steve Anton75737c02017-11-06 10:37:17 -08005326cricket::IceConfig PeerConnection::ParseIceConfig(
5327 const PeerConnectionInterface::RTCConfiguration& config) const {
5328 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005329 switch (config.continual_gathering_policy) {
5330 case PeerConnectionInterface::GATHER_ONCE:
5331 gathering_policy = cricket::GATHER_ONCE;
5332 break;
5333 case PeerConnectionInterface::GATHER_CONTINUALLY:
5334 gathering_policy = cricket::GATHER_CONTINUALLY;
5335 break;
5336 default:
5337 RTC_NOTREACHED();
5338 gathering_policy = cricket::GATHER_ONCE;
5339 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005340
Steve Anton75737c02017-11-06 10:37:17 -08005341 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005342 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5343 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005344 ice_config.prioritize_most_likely_candidate_pairs =
5345 config.prioritize_most_likely_ice_candidate_pairs;
5346 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005347 RTCConfigurationToIceConfigOptionalInt(
5348 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005349 ice_config.continual_gathering_policy = gathering_policy;
5350 ice_config.presume_writable_when_fully_relayed =
5351 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005352 ice_config.ice_check_interval_strong_connectivity =
5353 config.ice_check_interval_strong_connectivity;
5354 ice_config.ice_check_interval_weak_connectivity =
5355 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005356 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005357 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5358 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005359 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005360 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005361 ice_config.regather_all_networks_interval_range =
5362 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005363 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005364 return ice_config;
5365}
5366
Steve Antona41959e2018-11-28 11:15:33 -08005367static absl::string_view GetTrackIdBySsrc(
5368 const SessionDescriptionInterface* session_description,
5369 uint32_t ssrc) {
5370 if (!session_description) {
5371 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005372 }
Steve Antona41959e2018-11-28 11:15:33 -08005373 for (const cricket::ContentInfo& content :
5374 session_description->description()->contents()) {
5375 const cricket::MediaContentDescription& media =
5376 *content.media_description();
5377 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5378 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5379 const cricket::StreamParams* stream_params =
5380 cricket::GetStreamBySsrc(media.streams(), ssrc);
5381 if (stream_params) {
5382 return stream_params->id;
5383 }
5384 }
5385 }
5386 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005387}
5388
Steve Antona41959e2018-11-28 11:15:33 -08005389absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5390 return GetTrackIdBySsrc(local_description(), ssrc);
5391}
5392
5393absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5394 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005395}
5396
5397bool PeerConnection::SendData(const cricket::SendDataParams& params,
5398 const rtc::CopyOnWriteBuffer& payload,
5399 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005400 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5401 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5402 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005403 return false;
5404 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005405 if (media_transport_) {
5406 SendDataParams send_params;
5407 send_params.type = ToWebrtcDataMessageType(params.type);
5408 send_params.ordered = params.ordered;
5409 if (params.max_rtx_count >= 0) {
5410 send_params.max_rtx_count = params.max_rtx_count;
5411 } else if (params.max_rtx_ms >= 0) {
5412 send_params.max_rtx_ms = params.max_rtx_ms;
5413 }
5414 return media_transport_->SendData(params.sid, send_params, payload).ok();
5415 }
Steve Anton75737c02017-11-06 10:37:17 -08005416 return rtp_data_channel_
5417 ? rtp_data_channel_->SendData(params, payload, result)
5418 : network_thread()->Invoke<bool>(
5419 RTC_FROM_HERE,
5420 Bind(&cricket::SctpTransportInternal::SendData,
5421 sctp_transport_.get(), params, payload, result));
5422}
5423
5424bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005425 RTC_DCHECK_RUN_ON(signaling_thread());
5426 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005427 // Don't log an error here, because DataChannels are expected to call
5428 // ConnectDataChannel in this state. It's the only way to initially tell
5429 // whether or not the underlying transport is ready.
5430 return false;
5431 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005432 if (media_transport_) {
5433 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5434 &DataChannel::OnChannelReady);
5435 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5436 &DataChannel::OnDataReceived);
5437 SignalMediaTransportChannelClosing_s.connect(
5438 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5439 SignalMediaTransportChannelClosed_s.connect(
5440 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5441 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005442 rtp_data_channel_->SignalReadyToSendData.connect(
5443 webrtc_data_channel, &DataChannel::OnChannelReady);
5444 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5445 &DataChannel::OnDataReceived);
5446 } else {
5447 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5448 &DataChannel::OnChannelReady);
5449 SignalSctpDataReceived.connect(webrtc_data_channel,
5450 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005451 SignalSctpClosingProcedureStartedRemotely.connect(
5452 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5453 SignalSctpClosingProcedureComplete.connect(
5454 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005455 }
5456 return true;
5457}
5458
5459void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005460 RTC_DCHECK_RUN_ON(signaling_thread());
5461 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005462 RTC_LOG(LS_ERROR)
5463 << "DisconnectDataChannel called when rtp_data_channel_ and "
5464 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005465 return;
5466 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005467 if (media_transport_) {
5468 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5469 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5470 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5471 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5472 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005473 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5474 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5475 } else {
5476 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5477 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005478 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5479 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005480 }
5481}
5482
5483void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005484 if (media_transport_) {
5485 // No-op. Media transport does not need to add streams.
5486 return;
5487 }
Steve Anton75737c02017-11-06 10:37:17 -08005488 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005489 RTC_LOG(LS_ERROR)
5490 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005491 return;
5492 }
5493 network_thread()->Invoke<void>(
5494 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5495 sctp_transport_.get(), sid));
5496}
5497
5498void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005499 if (media_transport_) {
5500 media_transport_->CloseChannel(sid);
5501 return;
5502 }
Steve Anton75737c02017-11-06 10:37:17 -08005503 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005504 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005505 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005506 return;
5507 }
5508 network_thread()->Invoke<void>(
5509 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5510 sctp_transport_.get(), sid));
5511}
5512
5513bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005514 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005515 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005516 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005517 sctp_ready_to_send_data_;
5518}
5519
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005520void PeerConnection::OnDataReceived(int channel_id,
5521 DataMessageType type,
5522 const rtc::CopyOnWriteBuffer& buffer) {
5523 cricket::ReceiveDataParams params;
5524 params.sid = channel_id;
5525 params.type = ToCricketDataMessageType(type);
5526 media_transport_invoker_->AsyncInvoke<void>(
5527 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5528 RTC_DCHECK_RUN_ON(signaling_thread());
5529 if (!HandleOpenMessage_s(params, buffer)) {
5530 SignalMediaTransportReceivedData_s(params, buffer);
5531 }
5532 });
5533}
5534
5535void PeerConnection::OnChannelClosing(int channel_id) {
5536 media_transport_invoker_->AsyncInvoke<void>(
5537 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5538 RTC_DCHECK_RUN_ON(signaling_thread());
5539 SignalMediaTransportChannelClosing_s(channel_id);
5540 });
5541}
5542
5543void PeerConnection::OnChannelClosed(int channel_id) {
5544 media_transport_invoker_->AsyncInvoke<void>(
5545 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5546 RTC_DCHECK_RUN_ON(signaling_thread());
5547 SignalMediaTransportChannelClosed_s(channel_id);
5548 });
5549}
5550
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005551absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005552 if (sctp_mid_ && transport_controller_) {
5553 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5554 if (dtls_transport) {
5555 return dtls_transport->transport_name();
5556 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005557 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005558 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005559 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005560}
5561
Qingsi Wang72a43a12018-02-20 16:03:18 -08005562cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5563 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005564 network_thread()->Invoke<void>(
5565 RTC_FROM_HERE,
5566 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5567 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005568 return candidate_states_list;
5569}
5570
Steve Anton5dfde182018-02-06 10:34:40 -08005571std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5572 const {
5573 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005574 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005575 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005576 if (channel) {
5577 transport_names_by_mid[channel->content_name()] =
5578 channel->transport_name();
5579 }
Steve Anton75737c02017-11-06 10:37:17 -08005580 }
Steve Anton5dfde182018-02-06 10:34:40 -08005581 if (rtp_data_channel_) {
5582 transport_names_by_mid[rtp_data_channel_->content_name()] =
5583 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005584 }
5585 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005586 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005587 RTC_DCHECK(transport_name);
5588 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005589 }
Steve Anton5dfde182018-02-06 10:34:40 -08005590 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005591}
5592
Steve Anton5dfde182018-02-06 10:34:40 -08005593std::map<std::string, cricket::TransportStats>
5594PeerConnection::GetTransportStatsByNames(
5595 const std::set<std::string>& transport_names) {
5596 if (!network_thread()->IsCurrent()) {
5597 return network_thread()
5598 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5599 RTC_FROM_HERE,
5600 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005601 }
Steve Anton5dfde182018-02-06 10:34:40 -08005602 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5603 for (const std::string& transport_name : transport_names) {
5604 cricket::TransportStats transport_stats;
5605 bool success =
5606 transport_controller_->GetStats(transport_name, &transport_stats);
5607 if (success) {
5608 transport_stats_by_name[transport_name] = std::move(transport_stats);
5609 } else {
5610 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5611 << transport_name;
5612 }
5613 }
5614 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005615}
5616
5617bool PeerConnection::GetLocalCertificate(
5618 const std::string& transport_name,
5619 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005620 if (!certificate) {
5621 return false;
5622 }
5623 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5624 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005625}
5626
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005627std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005628 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005629 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005630}
5631
5632cricket::DataChannelType PeerConnection::data_channel_type() const {
5633 return data_channel_type_;
5634}
5635
5636bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5637 return pending_ice_restarts_.find(content_name) !=
5638 pending_ice_restarts_.end();
5639}
5640
Steve Anton75737c02017-11-06 10:37:17 -08005641bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5642 return transport_controller_->NeedsIceRestart(content_name);
5643}
5644
5645void PeerConnection::OnCertificateReady(
5646 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5647 transport_controller_->SetLocalCertificate(certificate);
5648}
5649
5650void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005651 SetSessionError(SessionError::kTransport,
5652 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005653}
5654
Alex Loiko9289eda2018-11-23 16:18:59 +00005655void PeerConnection::OnTransportControllerConnectionState(
5656 cricket::IceConnectionState state) {
5657 switch (state) {
5658 case cricket::kIceConnectionConnecting:
5659 // If the current state is Connected or Completed, then there were
5660 // writable channels but now there are not, so the next state must
5661 // be Disconnected.
5662 // kIceConnectionConnecting is currently used as the default,
5663 // un-connected state by the TransportController, so its only use is
5664 // detecting disconnections.
5665 if (ice_connection_state_ ==
5666 PeerConnectionInterface::kIceConnectionConnected ||
5667 ice_connection_state_ ==
5668 PeerConnectionInterface::kIceConnectionCompleted) {
5669 SetIceConnectionState(
5670 PeerConnectionInterface::kIceConnectionDisconnected);
5671 }
5672 break;
5673 case cricket::kIceConnectionFailed:
5674 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5675 break;
5676 case cricket::kIceConnectionConnected:
5677 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5678 "all transports are writable.";
5679 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5680 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5681 break;
5682 case cricket::kIceConnectionCompleted:
5683 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5684 "all transports are complete.";
5685 if (ice_connection_state_ !=
5686 PeerConnectionInterface::kIceConnectionConnected) {
5687 // If jumping directly from "checking" to "connected",
5688 // signal "connected" first.
5689 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5690 }
5691 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5692 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5693 ReportTransportStats();
5694 break;
5695 default:
5696 RTC_NOTREACHED();
5697 }
5698}
5699
Steve Anton75737c02017-11-06 10:37:17 -08005700void PeerConnection::OnTransportControllerCandidatesGathered(
5701 const std::string& transport_name,
5702 const cricket::Candidates& candidates) {
5703 RTC_DCHECK(signaling_thread()->IsCurrent());
5704 int sdp_mline_index;
5705 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005706 RTC_LOG(LS_ERROR)
5707 << "OnTransportControllerCandidatesGathered: content name "
5708 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005709 return;
5710 }
5711
5712 for (cricket::Candidates::const_iterator citer = candidates.begin();
5713 citer != candidates.end(); ++citer) {
5714 // Use transport_name as the candidate media id.
5715 std::unique_ptr<JsepIceCandidate> candidate(
5716 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5717 if (local_description()) {
5718 mutable_local_description()->AddCandidate(candidate.get());
5719 }
5720 OnIceCandidate(std::move(candidate));
5721 }
5722}
5723
5724void PeerConnection::OnTransportControllerCandidatesRemoved(
5725 const std::vector<cricket::Candidate>& candidates) {
5726 RTC_DCHECK(signaling_thread()->IsCurrent());
5727 // Sanity check.
5728 for (const cricket::Candidate& candidate : candidates) {
5729 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005730 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005731 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005732 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005733 return;
5734 }
5735 }
5736
5737 if (local_description()) {
5738 mutable_local_description()->RemoveCandidates(candidates);
5739 }
5740 OnIceCandidatesRemoved(candidates);
5741}
5742
5743void PeerConnection::OnTransportControllerDtlsHandshakeError(
5744 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005745 RTC_HISTOGRAM_ENUMERATION(
5746 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5747 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005748}
5749
Steve Antoned10bd92017-12-05 10:52:59 -08005750void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005751 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005752 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005753 if (channel && !channel->enabled()) {
5754 channel->Enable(true);
5755 }
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
5757
Steve Anton4171afb2017-11-20 10:20:22 -08005758 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005759 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005760 }
Steve Anton75737c02017-11-06 10:37:17 -08005761}
5762
5763// Returns the media index for a local ice candidate given the content name.
5764bool PeerConnection::GetLocalCandidateMediaIndex(
5765 const std::string& content_name,
5766 int* sdp_mline_index) {
5767 if (!local_description() || !sdp_mline_index) {
5768 return false;
5769 }
5770
5771 bool content_found = false;
5772 const ContentInfos& contents = local_description()->description()->contents();
5773 for (size_t index = 0; index < contents.size(); ++index) {
5774 if (contents[index].name == content_name) {
5775 *sdp_mline_index = static_cast<int>(index);
5776 content_found = true;
5777 break;
5778 }
5779 }
5780 return content_found;
5781}
5782
5783bool PeerConnection::UseCandidatesInSessionDescription(
5784 const SessionDescriptionInterface* remote_desc) {
5785 if (!remote_desc) {
5786 return true;
5787 }
5788 bool ret = true;
5789
5790 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5791 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5792 for (size_t n = 0; n < candidates->count(); ++n) {
5793 const IceCandidateInterface* candidate = candidates->at(n);
5794 bool valid = false;
5795 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5796 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005797 RTC_LOG(LS_INFO)
5798 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005799 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005800 }
5801 continue;
5802 }
5803 ret = UseCandidate(candidate);
5804 if (!ret) {
5805 break;
5806 }
5807 }
5808 }
5809 return ret;
5810}
5811
5812bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5813 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5814 size_t remote_content_size =
5815 remote_description()->description()->contents().size();
5816 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005817 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005818 return false;
5819 }
5820
5821 cricket::ContentInfo content =
5822 remote_description()->description()->contents()[mediacontent_index];
5823 std::vector<cricket::Candidate> candidates;
5824 candidates.push_back(candidate->candidate());
5825 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005826 RTCError error =
5827 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005828 if (error.ok()) {
5829 // Candidates successfully submitted for checking.
5830 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5831 ice_connection_state_ ==
5832 PeerConnectionInterface::kIceConnectionDisconnected) {
5833 // If state is New, then the session has just gotten its first remote ICE
5834 // candidates, so go to Checking.
5835 // If state is Disconnected, the session is re-using old candidates or
5836 // receiving additional ones, so go to Checking.
5837 // If state is Connected, stay Connected.
5838 // TODO(bemasc): If state is Connected, and the new candidates are for a
5839 // newly added transport, then the state actually _should_ move to
5840 // checking. Add a way to distinguish that case.
5841 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5842 }
5843 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005844 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005845 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005846 }
5847 return true;
5848}
5849
5850void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 // Destroy video channel first since it may have a pointer to the
5852 // voice channel.
5853 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005854 if (!video_info || video_info->rejected) {
5855 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005856 }
5857
Steve Anton6fec8802017-12-04 10:37:29 -08005858 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5859 if (!audio_info || audio_info->rejected) {
5860 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005861 }
5862
5863 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5864 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005865 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005866 }
5867}
5868
Steve Antondcc3c022017-12-22 16:02:54 -08005869RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5870 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005871 const cricket::ContentGroup* bundle_group = nullptr;
5872 if (configuration_.bundle_policy ==
5873 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005874 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005875 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005876 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5877 "max-bundle configured but session description "
5878 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005879 }
5880 }
Steve Antondcc3c022017-12-22 16:02:54 -08005881 return std::move(bundle_group);
5882}
5883
5884RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005885 // Creating the media channels. Transports should already have been created
5886 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005887 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005888 if (voice && !voice->rejected &&
5889 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005890 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005891 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005892 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5893 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005894 }
5895 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5896 }
5897
Steve Antondcc3c022017-12-22 16:02:54 -08005898 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005899 if (video && !video->rejected &&
5900 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005901 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005902 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005903 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5904 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005905 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005906 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005907 }
5908
Steve Antondcc3c022017-12-22 16:02:54 -08005909 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005910 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005911 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005912 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005913 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5914 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005915 }
5916 }
5917
Steve Anton8a006912017-12-04 15:25:56 -08005918 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005919}
5920
Steve Anton4171afb2017-11-20 10:20:22 -08005921// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005922cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005923 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005924 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005925 MediaTransportInterface* media_transport = nullptr;
5926 if (configuration_.use_media_transport) {
5927 media_transport = GetMediaTransport(mid);
5928 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005929
Steve Anton75737c02017-11-06 10:37:17 -08005930 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005931 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005932 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5933 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005934 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005935 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005936 }
Steve Anton75737c02017-11-06 10:37:17 -08005937 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5938 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005939 voice_channel->SignalSentPacket.connect(this,
5940 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005941 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005942
Steve Antoneda6ccd2017-12-04 10:21:55 -08005943 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005944}
5945
Steve Anton4171afb2017-11-20 10:20:22 -08005946// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005947cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005948 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005949 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01005950 MediaTransportInterface* media_transport = nullptr;
5951 if (configuration_.use_media_transport) {
5952 media_transport = GetMediaTransport(mid);
5953 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005954
Steve Anton75737c02017-11-06 10:37:17 -08005955 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01005956 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005957 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5958 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005959 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005960 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005961 }
Steve Anton75737c02017-11-06 10:37:17 -08005962 video_channel->SignalDtlsSrtpSetupFailure.connect(
5963 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005964 video_channel->SignalSentPacket.connect(this,
5965 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005966 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005967
Steve Antoneda6ccd2017-12-04 10:21:55 -08005968 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005969}
5970
Zhi Huange830e682018-03-30 10:48:35 -07005971bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005972 switch (data_channel_type_) {
5973 case cricket::DCT_MEDIA_TRANSPORT:
5974 if (network_thread()->Invoke<bool>(
5975 RTC_FROM_HERE,
5976 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5977 this, mid))) {
5978 for (const auto& channel : sctp_data_channels_) {
5979 channel->OnTransportChannelCreated();
5980 }
5981 return true;
5982 }
Steve Anton75737c02017-11-06 10:37:17 -08005983 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005984 case cricket::DCT_SCTP:
5985 if (!sctp_factory_) {
5986 RTC_LOG(LS_ERROR)
5987 << "Trying to create SCTP transport, but didn't compile with "
5988 "SCTP support (HAVE_SCTP)";
5989 return false;
5990 }
5991 if (!network_thread()->Invoke<bool>(
5992 RTC_FROM_HERE,
5993 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5994 return false;
5995 }
5996 for (const auto& channel : sctp_data_channels_) {
5997 channel->OnTransportChannelCreated();
5998 }
5999 return true;
6000 case cricket::DCT_RTP:
6001 default:
6002 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6003 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6004 configuration_.media_config, rtp_transport, signaling_thread(), mid,
6005 SrtpRequired(), GetCryptoOptions());
6006 if (!rtp_data_channel_) {
6007 return false;
6008 }
6009 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6010 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6011 rtp_data_channel_->SignalSentPacket.connect(
6012 this, &PeerConnection::OnSentPacket_w);
6013 rtp_data_channel_->SetRtpTransport(rtp_transport);
6014 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006015 }
6016
Steve Anton75737c02017-11-06 10:37:17 -08006017 return true;
6018}
6019
6020Call::Stats PeerConnection::GetCallStats() {
6021 if (!worker_thread()->IsCurrent()) {
6022 return worker_thread()->Invoke<Call::Stats>(
6023 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6024 }
6025 if (call_) {
6026 return call_->GetStats();
6027 } else {
6028 return Call::Stats();
6029 }
6030}
6031
Zhi Huange830e682018-03-30 10:48:35 -07006032bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006033 RTC_DCHECK(network_thread()->IsCurrent());
6034 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006035 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006036 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006037 RTC_DCHECK(dtls_transport);
6038 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006039 RTC_DCHECK(sctp_transport_);
6040 sctp_invoker_.reset(new rtc::AsyncInvoker());
6041 sctp_transport_->SignalReadyToSendData.connect(
6042 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6043 sctp_transport_->SignalDataReceived.connect(
6044 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006045 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6046 // another thread. Would be nice if there was a helper class similar to
6047 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6048 // code.
6049 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6050 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6051 sctp_transport_->SignalClosingProcedureComplete.connect(
6052 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006053 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006054 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006055 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006056}
6057
6058void PeerConnection::DestroySctpTransport_n() {
6059 RTC_DCHECK(network_thread()->IsCurrent());
6060 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006061 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006062 sctp_invoker_.reset(nullptr);
6063 sctp_ready_to_send_data_ = false;
6064}
6065
6066void PeerConnection::OnSctpTransportReadyToSendData_n() {
6067 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6068 RTC_DCHECK(network_thread()->IsCurrent());
6069 // Note: Cannot use rtc::Bind here because it will grab a reference to
6070 // PeerConnection and potentially cause PeerConnection to live longer than
6071 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6072 // be destroyed before PeerConnection is destroyed, and at that point all
6073 // pending tasks will be cleared.
6074 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6075 OnSctpTransportReadyToSendData_s(true);
6076 });
6077}
6078
6079void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6080 RTC_DCHECK(signaling_thread()->IsCurrent());
6081 sctp_ready_to_send_data_ = ready;
6082 SignalSctpReadyToSendData(ready);
6083}
6084
6085void PeerConnection::OnSctpTransportDataReceived_n(
6086 const cricket::ReceiveDataParams& params,
6087 const rtc::CopyOnWriteBuffer& payload) {
6088 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6089 RTC_DCHECK(network_thread()->IsCurrent());
6090 // Note: Cannot use rtc::Bind here because it will grab a reference to
6091 // PeerConnection and potentially cause PeerConnection to live longer than
6092 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6093 // be destroyed before PeerConnection is destroyed, and at that point all
6094 // pending tasks will be cleared.
6095 sctp_invoker_->AsyncInvoke<void>(
6096 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6097 OnSctpTransportDataReceived_s(params, payload);
6098 });
6099}
6100
6101void PeerConnection::OnSctpTransportDataReceived_s(
6102 const cricket::ReceiveDataParams& params,
6103 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006104 RTC_DCHECK_RUN_ON(signaling_thread());
6105 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006106 SignalSctpDataReceived(params, payload);
6107 }
6108}
6109
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006110void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006111 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6112 RTC_DCHECK(network_thread()->IsCurrent());
6113 sctp_invoker_->AsyncInvoke<void>(
6114 RTC_FROM_HERE, signaling_thread(),
6115 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006116 &SignalSctpClosingProcedureStartedRemotely, sid));
6117}
6118
6119void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6120 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6121 RTC_DCHECK(network_thread()->IsCurrent());
6122 sctp_invoker_->AsyncInvoke<void>(
6123 RTC_FROM_HERE, signaling_thread(),
6124 rtc::Bind(&sigslot::signal1<int>::operator(),
6125 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006126}
6127
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006128bool PeerConnection::SetupMediaTransportForDataChannels_n(
6129 const std::string& mid) {
6130 media_transport_ = transport_controller_->GetMediaTransport(mid);
6131 if (!media_transport_) {
6132 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6133 return false;
6134 }
6135
6136 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6137 media_transport_->SetDataSink(this);
6138 media_transport_data_mid_ = mid;
6139 transport_controller_->SignalMediaTransportStateChanged.connect(
6140 this, &PeerConnection::OnMediaTransportStateChanged_n);
6141 // Check the initial state right away, in case transport is already writable.
6142 OnMediaTransportStateChanged_n();
6143 return true;
6144}
6145
6146void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6147 if (!media_transport_) {
6148 return;
6149 }
6150 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6151 media_transport_data_mid_.reset();
6152 media_transport_->SetDataSink(nullptr);
6153 media_transport_invoker_ = nullptr;
6154 media_transport_ = nullptr;
6155}
6156
6157void PeerConnection::OnMediaTransportStateChanged_n() {
6158 if (!media_transport_data_mid_ ||
6159 transport_controller_->GetMediaTransportState(
6160 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6161 return;
6162 }
6163 media_transport_invoker_->AsyncInvoke<void>(
6164 RTC_FROM_HERE, signaling_thread(), [this] {
6165 RTC_DCHECK_RUN_ON(signaling_thread());
6166 media_transport_ready_to_send_data_ = true;
6167 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6168 });
6169}
6170
Steve Anton75737c02017-11-06 10:37:17 -08006171// Returns false if bundle is enabled and rtcp_mux is disabled.
6172bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6173 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6174 if (!bundle_enabled)
6175 return true;
6176
6177 const cricket::ContentGroup* bundle_group =
6178 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6179 RTC_DCHECK(bundle_group != NULL);
6180
6181 const cricket::ContentInfos& contents = desc->contents();
6182 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6183 citer != contents.end(); ++citer) {
6184 const cricket::ContentInfo* content = (&*citer);
6185 RTC_DCHECK(content != NULL);
6186 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006187 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006188 if (!HasRtcpMuxEnabled(content))
6189 return false;
6190 }
6191 }
6192 // RTCP-MUX is enabled in all the contents.
6193 return true;
6194}
6195
6196bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006197 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006198}
6199
Steve Anton06817cd2018-12-18 15:55:30 -08006200static RTCError ValidateMids(const cricket::SessionDescription& description) {
6201 std::set<std::string> mids;
6202 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006203 if (content.name.empty()) {
6204 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6205 "A media section is missing a MID attribute.");
6206 }
Steve Anton06817cd2018-12-18 15:55:30 -08006207 if (!mids.insert(content.name).second) {
6208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6209 "Duplicate a=mid value '" + content.name + "'.");
6210 }
6211 }
6212 return RTCError::OK();
6213}
6214
Steve Anton8a006912017-12-04 15:25:56 -08006215RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006216 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006217 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006218 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006219 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006220 }
6221
6222 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006224 }
6225
Steve Anton3828c062017-12-06 10:34:51 -08006226 SdpType type = sdesc->GetType();
6227 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6228 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006229 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006230 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006231 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006232 }
6233
Steve Anton06817cd2018-12-18 15:55:30 -08006234 RTCError error = ValidateMids(*sdesc->description());
6235 if (!error.ok()) {
6236 return error;
6237 }
6238
Steve Anton75737c02017-11-06 10:37:17 -08006239 // Verify crypto settings.
6240 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006241 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6242 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006243 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006244 if (!crypto_error.ok()) {
6245 return crypto_error;
6246 }
Steve Anton75737c02017-11-06 10:37:17 -08006247 }
6248
6249 // Verify ice-ufrag and ice-pwd.
6250 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6252 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006253 }
6254
6255 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6257 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006258 }
6259
6260 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6261 // m-lines that do not rtcp-mux enabled.
6262
6263 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006264 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006265 // With an answer we want to compare the new answer session description with
6266 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006267 const cricket::SessionDescription* offer_desc =
6268 (source == cricket::CS_LOCAL) ? remote_description()->description()
6269 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006270 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6271 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6272 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6274 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006275 }
6276 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006277 // The re-offers should respect the order of m= sections in current
6278 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006279 // With a re-offer, either the current local or current remote descriptions
6280 // could be the most up to date, so we would like to check against both of
6281 // them if they exist. It could be the case that one of them has a 0 port
6282 // for a media section, but the other does not. This is important to check
6283 // against in the case that we are recycling an m= section.
6284 const cricket::SessionDescription* current_desc = nullptr;
6285 const cricket::SessionDescription* secondary_current_desc = nullptr;
6286 if (local_description()) {
6287 current_desc = local_description()->description();
6288 if (remote_description()) {
6289 secondary_current_desc = remote_description()->description();
6290 }
6291 } else if (remote_description()) {
6292 current_desc = remote_description()->description();
6293 }
Steve Anton75737c02017-11-06 10:37:17 -08006294 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006295 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6296 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6298 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006299 }
6300 }
6301
Steve Antonba42e992018-04-09 14:10:01 -07006302 if (IsUnifiedPlan()) {
6303 // Ensure that each audio and video media section has at most one
6304 // "StreamParams". This will return an error if receiving a session
6305 // description from a "Plan B" endpoint which adds multiple tracks of the
6306 // same type. With Unified Plan, there can only be at most one track per
6307 // media section.
6308 for (const ContentInfo& content : sdesc->description()->contents()) {
6309 const MediaContentDescription& desc = *content.description;
6310 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6311 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6312 desc.streams().size() > 1u) {
6313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6314 "Media section has more than one track specified "
6315 "with a=ssrc lines which is not supported with "
6316 "Unified Plan.");
6317 }
6318 }
6319 }
6320
Steve Anton8a006912017-12-04 15:25:56 -08006321 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006322}
6323
Steve Anton3828c062017-12-06 10:34:51 -08006324bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006325 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006326 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006327 return (state == PeerConnectionInterface::kStable) ||
6328 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006329 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006330 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006331 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6332 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6333 }
6334}
6335
Steve Anton3828c062017-12-06 10:34:51 -08006336bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006337 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006338 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006339 return (state == PeerConnectionInterface::kStable) ||
6340 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006341 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006342 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006343 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6344 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6345 }
6346}
6347
Steve Antonf8470812017-12-04 10:46:21 -08006348const char* PeerConnection::SessionErrorToString(SessionError error) const {
6349 switch (error) {
6350 case SessionError::kNone:
6351 return "ERROR_NONE";
6352 case SessionError::kContent:
6353 return "ERROR_CONTENT";
6354 case SessionError::kTransport:
6355 return "ERROR_TRANSPORT";
6356 }
6357 RTC_NOTREACHED();
6358 return "";
6359}
6360
Steve Anton75737c02017-11-06 10:37:17 -08006361std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006362 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006363 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6364 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006365 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006366}
6367
Steve Anton8e20f172018-03-06 10:55:04 -08006368void PeerConnection::ReportSdpFormatReceived(
6369 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006370 int num_audio_mlines = 0;
6371 int num_video_mlines = 0;
6372 int num_audio_tracks = 0;
6373 int num_video_tracks = 0;
6374 for (const ContentInfo& content : remote_offer.description()->contents()) {
6375 cricket::MediaType media_type = content.media_description()->type();
6376 int num_tracks = std::max(
6377 1, static_cast<int>(content.media_description()->streams().size()));
6378 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6379 num_audio_mlines += 1;
6380 num_audio_tracks += num_tracks;
6381 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6382 num_video_mlines += 1;
6383 num_video_tracks += num_tracks;
6384 }
6385 }
6386 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6387 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6388 format = kSdpFormatReceivedComplexUnifiedPlan;
6389 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6390 format = kSdpFormatReceivedComplexPlanB;
6391 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6392 format = kSdpFormatReceivedSimple;
6393 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006394 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6395 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006396}
6397
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006398void PeerConnection::NoteUsageEvent(UsageEvent event) {
6399 RTC_DCHECK_RUN_ON(signaling_thread());
6400 usage_event_accumulator_ |= static_cast<int>(event);
6401}
6402
6403void PeerConnection::ReportUsagePattern() const {
6404 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006405 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6406 usage_event_accumulator_,
6407 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006408 const int bad_bits =
6409 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6410 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6411 const int good_bits =
6412 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6413 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6414 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6415 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6416 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006417 // If called after close(), we can't report, because observer may have
6418 // been deallocated, and therefore pointer is null. Write to log instead.
6419 if (observer_) {
6420 Observer()->OnInterestingUsage(usage_event_accumulator_);
6421 } else {
6422 RTC_LOG(LS_INFO) << "Interesting usage signature "
6423 << usage_event_accumulator_
6424 << " observed after observer shutdown";
6425 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006426 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006427}
6428
Steve Anton0ffaaa22018-02-23 10:31:30 -08006429void PeerConnection::ReportNegotiatedSdpSemantics(
6430 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006431 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006432 switch (answer.description()->msid_signaling()) {
6433 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006434 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006435 break;
6436 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006437 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006438 break;
6439 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006440 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006441 break;
6442 case cricket::kMsidSignalingMediaSection |
6443 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006444 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006445 break;
6446 default:
6447 RTC_NOTREACHED();
6448 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6450 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006451}
6452
Steve Anton75737c02017-11-06 10:37:17 -08006453// We need to check the local/remote description for the Transport instead of
6454// the session, because a new Transport added during renegotiation may have
6455// them unset while the session has them set from the previous negotiation.
6456// Not doing so may trigger the auto generation of transport description and
6457// mess up DTLS identity information, ICE credential, etc.
6458bool PeerConnection::ReadyToUseRemoteCandidate(
6459 const IceCandidateInterface* candidate,
6460 const SessionDescriptionInterface* remote_desc,
6461 bool* valid) {
6462 *valid = true;
6463
6464 const SessionDescriptionInterface* current_remote_desc =
6465 remote_desc ? remote_desc : remote_description();
6466
6467 if (!current_remote_desc) {
6468 return false;
6469 }
6470
6471 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6472 size_t remote_content_size =
6473 current_remote_desc->description()->contents().size();
6474 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006475 RTC_LOG(LS_ERROR)
6476 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6477 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006478
6479 *valid = false;
6480 return false;
6481 }
6482
6483 cricket::ContentInfo content =
6484 current_remote_desc->description()->contents()[mediacontent_index];
6485
6486 const std::string transport_name = GetTransportName(content.name);
6487 if (transport_name.empty()) {
6488 return false;
6489 }
Zhi Huange830e682018-03-30 10:48:35 -07006490 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006491}
6492
6493bool PeerConnection::SrtpRequired() const {
6494 return dtls_enabled_ ||
6495 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6496}
6497
6498void PeerConnection::OnTransportControllerGatheringState(
6499 cricket::IceGatheringState state) {
6500 RTC_DCHECK(signaling_thread()->IsCurrent());
6501 if (state == cricket::kIceGatheringGathering) {
6502 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6503 } else if (state == cricket::kIceGatheringComplete) {
6504 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6505 }
6506}
6507
6508void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006509 std::map<std::string, std::set<cricket::MediaType>>
6510 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006511 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006512 if (transceiver->internal()->channel()) {
6513 const std::string& transport_name =
6514 transceiver->internal()->channel()->transport_name();
6515 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006516 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006517 }
Steve Anton75737c02017-11-06 10:37:17 -08006518 }
6519 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006520 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6521 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006522 }
Zhi Huange830e682018-03-30 10:48:35 -07006523
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006524 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006525 if (transport_name) {
6526 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006527 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006528 }
Zhi Huange830e682018-03-30 10:48:35 -07006529
Steve Antonc7b964c2018-02-01 14:39:45 -08006530 for (const auto& entry : media_types_by_transport_name) {
6531 const std::string& transport_name = entry.first;
6532 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006533 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006534 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006535 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006536 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006537 }
6538 }
6539}
6540// Walk through the ConnectionInfos to gather best connection usage
6541// for IPv4 and IPv6.
6542void PeerConnection::ReportBestConnectionState(
6543 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006544 for (const cricket::TransportChannelStats& channel_stats :
6545 stats.channel_stats) {
6546 for (const cricket::ConnectionInfo& connection_info :
6547 channel_stats.connection_infos) {
6548 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006549 continue;
6550 }
6551
Steve Antonc7b964c2018-02-01 14:39:45 -08006552 const cricket::Candidate& local = connection_info.local_candidate;
6553 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006554
6555 // Increment the counter for IceCandidatePairType.
6556 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6557 (local.type() == RELAY_PORT_TYPE &&
6558 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006559 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6560 GetIceCandidatePairCounter(local, remote),
6561 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006562 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006563 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6564 GetIceCandidatePairCounter(local, remote),
6565 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006566 } else {
6567 RTC_CHECK(0);
6568 }
Steve Anton75737c02017-11-06 10:37:17 -08006569
6570 // Increment the counter for IP type.
6571 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006572 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6573 kBestConnections_IPv4,
6574 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006575 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006576 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6577 kBestConnections_IPv6,
6578 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006579 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006580 RTC_CHECK(!local.address().hostname().empty() &&
6581 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006582 }
6583
6584 return;
6585 }
6586 }
6587}
6588
6589void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006590 const cricket::TransportStats& stats,
6591 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006592 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6593 return;
6594 }
6595
6596 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6597 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6598 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6599 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6600 return;
6601 }
6602
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006603 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6604 for (cricket::MediaType media_type : media_types) {
6605 switch (media_type) {
6606 case cricket::MEDIA_TYPE_AUDIO:
6607 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6608 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6609 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6610 break;
6611 case cricket::MEDIA_TYPE_VIDEO:
6612 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6613 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6614 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6615 break;
6616 case cricket::MEDIA_TYPE_DATA:
6617 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6618 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6619 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6620 break;
6621 default:
6622 RTC_NOTREACHED();
6623 continue;
6624 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006625 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006626 }
6627
6628 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6629 for (cricket::MediaType media_type : media_types) {
6630 switch (media_type) {
6631 case cricket::MEDIA_TYPE_AUDIO:
6632 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6633 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6634 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6635 break;
6636 case cricket::MEDIA_TYPE_VIDEO:
6637 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6638 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6639 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6640 break;
6641 case cricket::MEDIA_TYPE_DATA:
6642 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6643 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6644 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6645 break;
6646 default:
6647 RTC_NOTREACHED();
6648 continue;
6649 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006650 }
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
6652}
6653
6654void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6655 RTC_DCHECK(worker_thread()->IsCurrent());
6656 RTC_DCHECK(call_);
6657 call_->OnSentPacket(sent_packet);
6658}
6659
6660const std::string PeerConnection::GetTransportName(
6661 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006662 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006663 if (channel) {
6664 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006665 }
Steve Anton6fec8802017-12-04 10:37:29 -08006666 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006667 RTC_DCHECK(sctp_mid_);
6668 if (content_name == *sctp_mid_) {
6669 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006670 }
6671 }
6672 // Return an empty string if failed to retrieve the transport name.
6673 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006674}
6675
Steve Anton6fec8802017-12-04 10:37:29 -08006676void PeerConnection::DestroyTransceiverChannel(
6677 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6678 transceiver) {
6679 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006680
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006681 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006682 if (channel) {
6683 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006684 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006685 }
6686}
6687
6688void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006689 if (rtp_data_channel_) {
6690 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006691 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006692 rtp_data_channel_ = nullptr;
6693 }
6694
6695 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6696 // grab a reference to this PeerConnection. If this is called from the
6697 // PeerConnection destructor, the RefCountedObject vtable will have already
6698 // been destroyed (since it is a subclass of PeerConnection) and using
6699 // rtc::Bind will cause "Pure virtual function called" error to appear.
6700
6701 if (sctp_transport_) {
6702 OnDataChannelDestroyed();
6703 network_thread()->Invoke<void>(RTC_FROM_HERE,
6704 [this] { DestroySctpTransport_n(); });
6705 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006706
6707 if (media_transport_) {
6708 OnDataChannelDestroyed();
6709 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6710 RTC_DCHECK_RUN_ON(network_thread());
6711 TeardownMediaTransportForDataChannels_n();
6712 });
6713 }
Steve Anton6fec8802017-12-04 10:37:29 -08006714}
6715
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006716void PeerConnection::DestroyChannelInterface(
6717 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006718 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006719 switch (channel->media_type()) {
6720 case cricket::MEDIA_TYPE_AUDIO:
6721 channel_manager()->DestroyVoiceChannel(
6722 static_cast<cricket::VoiceChannel*>(channel));
6723 break;
6724 case cricket::MEDIA_TYPE_VIDEO:
6725 channel_manager()->DestroyVideoChannel(
6726 static_cast<cricket::VideoChannel*>(channel));
6727 break;
6728 case cricket::MEDIA_TYPE_DATA:
6729 channel_manager()->DestroyRtpDataChannel(
6730 static_cast<cricket::RtpDataChannel*>(channel));
6731 break;
6732 default:
6733 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6734 break;
6735 }
Zhi Huange830e682018-03-30 10:48:35 -07006736}
Steve Anton6fec8802017-12-04 10:37:29 -08006737
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006738bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006739 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006740 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006741 cricket::DtlsTransportInternal* dtls_transport,
6742 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006743 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006744 auto base_channel = GetChannel(mid);
6745 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006746 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006747 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006748 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006749 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006750 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006751
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006752 if (configuration_.use_media_transport) {
6753 // Only pass media transport to call object if media transport is used
6754 // for media (and not data channel).
6755 call_->MediaTransportChange(media_transport);
6756 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006757
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006758 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006759}
6760
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006761PeerConnectionObserver* PeerConnection::Observer() const {
6762 // In earlier production code, the pointer was not cleared on close,
6763 // which might have led to undefined behavior if the observer was not
6764 // deallocated, or strange crashes if it was.
6765 // We use CHECK in order to catch such behavior if it exists.
6766 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6767 RTC_CHECK(observer_);
6768 return observer_;
6769}
6770
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006771CryptoOptions PeerConnection::GetCryptoOptions() {
6772 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6773 // after it has been removed.
6774 return configuration_.crypto_options.has_value()
6775 ? *configuration_.crypto_options
6776 : factory_->options().crypto_options;
6777}
6778
Harald Alvestrand89061872018-01-02 14:08:34 +01006779void PeerConnection::ClearStatsCache() {
6780 if (stats_collector_) {
6781 stats_collector_->ClearCachedStatsReport();
6782 }
6783}
6784
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006785void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006786 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6787 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006788}
6789
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006790} // namespace webrtc