blob: bec13a5886c1b4bf16e9d17462afec54b5d6d6e9 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
kwiberg0eb15ed2015-12-17 03:04:15 -080014#include <utility>
15#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "api/jsepicecandidate.h"
18#include "api/jsepsessiondescription.h"
19#include "api/mediaconstraintsinterface.h"
20#include "api/mediastreamproxy.h"
21#include "api/mediastreamtrackproxy.h"
22#include "call/call.h"
Elad Alon83ccca12017-10-04 13:18:26 +020023#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "logging/rtc_event_log/rtc_event_log.h"
25#include "media/sctp/sctptransport.h"
26#include "pc/audiotrack.h"
27#include "pc/channelmanager.h"
28#include "pc/dtmfsender.h"
29#include "pc/mediastream.h"
30#include "pc/mediastreamobserver.h"
31#include "pc/remoteaudiosource.h"
32#include "pc/rtpreceiver.h"
33#include "pc/rtpsender.h"
34#include "pc/streamcollection.h"
35#include "pc/videocapturertracksource.h"
36#include "pc/videotrack.h"
37#include "rtc_base/bind.h"
38#include "rtc_base/checks.h"
39#include "rtc_base/logging.h"
Elad Alon83ccca12017-10-04 13:18:26 +020040#include "rtc_base/ptr_util.h"
41#include "rtc_base/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/stringencode.h"
43#include "rtc_base/stringutils.h"
44#include "rtc_base/trace_event.h"
45#include "system_wrappers/include/clock.h"
46#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047
48namespace {
49
deadbeefab9b2d12015-10-14 11:33:11 -070050using webrtc::DataChannel;
51using webrtc::MediaConstraintsInterface;
52using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080054using webrtc::RTCError;
55using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070056using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080057using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070058using webrtc::RtpSenderProxy;
59using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070060using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061
deadbeefab9b2d12015-10-14 11:33:11 -070062static const char kDefaultStreamLabel[] = "default";
63static const char kDefaultAudioTrackLabel[] = "defaulta0";
64static const char kDefaultVideoTrackLabel[] = "defaultv0";
65
zhihuang8f65cdf2016-05-06 18:40:30 -070066// The length of RTCP CNAMEs.
67static const int kRtcpCnameLength = 16;
68
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000070 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070072 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080074 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075};
76
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000077struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078 explicit SetSessionDescriptionMsg(
79 webrtc::SetSessionDescriptionObserver* observer)
80 : observer(observer) {
81 }
82
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000083 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000084 std::string error;
85};
86
deadbeefab9b2d12015-10-14 11:33:11 -070087struct CreateSessionDescriptionMsg : public rtc::MessageData {
88 explicit CreateSessionDescriptionMsg(
89 webrtc::CreateSessionDescriptionObserver* observer)
90 : observer(observer) {}
91
92 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
93 std::string error;
94};
95
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000096struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000097 GetStatsMsg(webrtc::StatsObserver* observer,
98 webrtc::MediaStreamTrackInterface* track)
99 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000101 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000102 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103};
104
deadbeefab9b2d12015-10-14 11:33:11 -0700105// Check if we can send |new_stream| on a PeerConnection.
106bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
107 webrtc::MediaStreamInterface* new_stream) {
108 if (!new_stream || !current_streams) {
109 return false;
110 }
111 if (current_streams->find(new_stream->label()) != nullptr) {
112 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
113 << " is already added.";
114 return false;
115 }
116 return true;
117}
118
119bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
120 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
121}
122
deadbeef5e97fb52015-10-15 12:49:08 -0700123// If the direction is "recvonly" or "inactive", treat the description
124// as containing no streams.
125// See: https://code.google.com/p/webrtc/issues/detail?id=5054
126std::vector<cricket::StreamParams> GetActiveStreams(
127 const cricket::MediaContentDescription* desc) {
128 return MediaContentDirectionHasSend(desc->direction())
129 ? desc->streams()
130 : std::vector<cricket::StreamParams>();
131}
132
deadbeefab9b2d12015-10-14 11:33:11 -0700133bool IsValidOfferToReceiveMedia(int value) {
134 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
135 return (value >= Options::kUndefined) &&
136 (value <= Options::kMaxOfferToReceiveMedia);
137}
138
zhihuang1c378ed2017-08-17 14:10:50 -0700139// Add options to |[audio/video]_media_description_options| from |senders|.
140void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700141 const std::vector<rtc::scoped_refptr<
142 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700143 cricket::MediaDescriptionOptions* audio_media_description_options,
144 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700145 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700146 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
147 if (audio_media_description_options) {
148 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700149 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700150 }
151 } else {
152 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
153 if (video_media_description_options) {
154 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700155 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700156 }
157 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700158 }
zhihuang1c378ed2017-08-17 14:10:50 -0700159}
olka3c747662017-08-17 06:50:32 -0700160
zhihuang1c378ed2017-08-17 14:10:50 -0700161// Add options to |session_options| from |rtp_data_channels|.
162void AddRtpDataChannelOptions(
163 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
164 rtp_data_channels,
165 cricket::MediaDescriptionOptions* data_media_description_options) {
166 if (!data_media_description_options) {
167 return;
168 }
deadbeefab9b2d12015-10-14 11:33:11 -0700169 // Check for data channels.
170 for (const auto& kv : rtp_data_channels) {
171 const DataChannel* channel = kv.second;
172 if (channel->state() == DataChannel::kConnecting ||
173 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700174 // Legacy RTP data channels are signaled with the track/stream ID set to
175 // the data channel's label.
176 data_media_description_options->AddRtpDataChannel(channel->label(),
177 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700178 }
179 }
180}
181
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700182uint32_t ConvertIceTransportTypeToCandidateFilter(
183 PeerConnectionInterface::IceTransportsType type) {
184 switch (type) {
185 case PeerConnectionInterface::kNone:
186 return cricket::CF_NONE;
187 case PeerConnectionInterface::kRelay:
188 return cricket::CF_RELAY;
189 case PeerConnectionInterface::kNoHost:
190 return (cricket::CF_ALL & ~cricket::CF_HOST);
191 case PeerConnectionInterface::kAll:
192 return cricket::CF_ALL;
193 default:
nissec80e7412017-01-11 05:56:46 -0800194 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700195 }
196 return cricket::CF_NONE;
197}
198
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700199// Helper method to set a voice/video channel on all applicable senders
200// and receivers when one is created/destroyed by WebRtcSession.
201//
202// Used by On(Voice|Video)Channel(Created|Destroyed)
203template <class SENDER,
204 class RECEIVER,
205 class CHANNEL,
206 class SENDERS,
207 class RECEIVERS>
208void SetChannelOnSendersAndReceivers(CHANNEL* channel,
209 SENDERS& senders,
210 RECEIVERS& receivers,
211 cricket::MediaType media_type) {
212 for (auto& sender : senders) {
213 if (sender->media_type() == media_type) {
214 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
215 }
216 }
217 for (auto& receiver : receivers) {
218 if (receiver->media_type() == media_type) {
219 if (!channel) {
220 receiver->internal()->Stop();
221 }
222 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
223 }
224 }
225}
226
deadbeef293e9262017-01-11 12:28:30 -0800227// Helper to set an error and return from a method.
228bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
229 if (error) {
230 error->set_type(type);
231 }
232 return type == webrtc::RTCErrorType::NONE;
233}
234
Steve Anton038834f2017-07-14 15:59:59 -0700235bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
236 if (error_out) {
237 *error_out = std::move(error);
238 }
239 return error.ok();
240}
241
deadbeef0a6c4ca2015-10-06 11:38:28 -0700242} // namespace
243
244namespace webrtc {
245
deadbeef293e9262017-01-11 12:28:30 -0800246bool PeerConnectionInterface::RTCConfiguration::operator==(
247 const PeerConnectionInterface::RTCConfiguration& o) const {
248 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700249 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800250 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000251 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700252 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800253 BundlePolicy bundle_policy;
254 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700255 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
256 int ice_candidate_pool_size;
257 bool disable_ipv6;
258 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700259 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700260 bool enable_rtp_data_channel;
261 rtc::Optional<int> screencast_min_bitrate;
262 rtc::Optional<bool> combined_audio_video_bwe;
263 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800264 TcpCandidatePolicy tcp_candidate_policy;
265 CandidateNetworkPolicy candidate_network_policy;
266 int audio_jitter_buffer_max_packets;
267 bool audio_jitter_buffer_fast_accelerate;
268 int ice_connection_receiving_timeout;
269 int ice_backup_candidate_pair_ping_interval;
270 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800271 bool prioritize_most_likely_ice_candidate_pairs;
272 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800273 bool enable_quic;
deadbeef293e9262017-01-11 12:28:30 -0800274 bool prune_turn_ports;
275 bool presume_writable_when_fully_relayed;
276 bool enable_ice_renomination;
277 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800278 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700279 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200280 webrtc::TurnCustomizer* turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800281 };
282 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
283 "Did you add something to RTCConfiguration and forget to "
284 "update operator==?");
285 return type == o.type && servers == o.servers &&
286 bundle_policy == o.bundle_policy &&
287 rtcp_mux_policy == o.rtcp_mux_policy &&
288 tcp_candidate_policy == o.tcp_candidate_policy &&
289 candidate_network_policy == o.candidate_network_policy &&
290 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
291 audio_jitter_buffer_fast_accelerate ==
292 o.audio_jitter_buffer_fast_accelerate &&
293 ice_connection_receiving_timeout ==
294 o.ice_connection_receiving_timeout &&
295 ice_backup_candidate_pair_ping_interval ==
296 o.ice_backup_candidate_pair_ping_interval &&
297 continual_gathering_policy == o.continual_gathering_policy &&
298 certificates == o.certificates &&
299 prioritize_most_likely_ice_candidate_pairs ==
300 o.prioritize_most_likely_ice_candidate_pairs &&
301 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800302 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700303 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800304 enable_rtp_data_channel == o.enable_rtp_data_channel &&
305 enable_quic == o.enable_quic &&
306 screencast_min_bitrate == o.screencast_min_bitrate &&
307 combined_audio_video_bwe == o.combined_audio_video_bwe &&
308 enable_dtls_srtp == o.enable_dtls_srtp &&
309 ice_candidate_pool_size == o.ice_candidate_pool_size &&
310 prune_turn_ports == o.prune_turn_ports &&
311 presume_writable_when_fully_relayed ==
312 o.presume_writable_when_fully_relayed &&
313 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800314 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700315 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200316 ice_regather_interval_range == o.ice_regather_interval_range &&
317 turn_customizer == o.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800318}
319
320bool PeerConnectionInterface::RTCConfiguration::operator!=(
321 const PeerConnectionInterface::RTCConfiguration& o) const {
322 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800323}
324
zhihuang8f65cdf2016-05-06 18:40:30 -0700325// Generate a RTCP CNAME when a PeerConnection is created.
326std::string GenerateRtcpCname() {
327 std::string cname;
328 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
329 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800330 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700331 }
332 return cname;
333}
334
zhihuang1c378ed2017-08-17 14:10:50 -0700335bool ValidateOfferAnswerOptions(
336 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
337 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
338 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700339}
340
zhihuang1c378ed2017-08-17 14:10:50 -0700341// From |rtc_options|, fill parts of |session_options| shared by all generated
342// m= sections (in other words, nothing that involves a map/array).
343void ExtractSharedMediaSessionOptions(
344 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
345 cricket::MediaSessionOptions* session_options) {
346 session_options->vad_enabled = rtc_options.voice_activity_detection;
347 session_options->bundle_enabled = rtc_options.use_rtp_mux;
348}
zhihuanga77e6bb2017-08-14 18:17:48 -0700349
zhihuang1c378ed2017-08-17 14:10:50 -0700350bool ConvertConstraintsToOfferAnswerOptions(
351 const MediaConstraintsInterface* constraints,
352 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700353 if (!constraints) {
354 return true;
355 }
zhihuang1c378ed2017-08-17 14:10:50 -0700356
357 bool value = false;
358 size_t mandatory_constraints_satisfied = 0;
359
360 if (FindConstraint(constraints,
361 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
362 &mandatory_constraints_satisfied)) {
363 offer_answer_options->offer_to_receive_audio =
364 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
365 kOfferToReceiveMediaTrue
366 : 0;
367 }
368
369 if (FindConstraint(constraints,
370 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
371 &mandatory_constraints_satisfied)) {
372 offer_answer_options->offer_to_receive_video =
373 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
374 kOfferToReceiveMediaTrue
375 : 0;
376 }
377 if (FindConstraint(constraints,
378 MediaConstraintsInterface::kVoiceActivityDetection, &value,
379 &mandatory_constraints_satisfied)) {
380 offer_answer_options->voice_activity_detection = value;
381 }
382 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
383 &mandatory_constraints_satisfied)) {
384 offer_answer_options->use_rtp_mux = value;
385 }
386 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
387 &value, &mandatory_constraints_satisfied)) {
388 offer_answer_options->ice_restart = value;
389 }
390
deadbeefab9b2d12015-10-14 11:33:11 -0700391 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
392}
393
zhihuang38ede132017-06-15 12:52:32 -0700394PeerConnection::PeerConnection(PeerConnectionFactory* factory,
395 std::unique_ptr<RtcEventLog> event_log,
396 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397 : factory_(factory),
398 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000399 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700400 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000401 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000402 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700403 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700404 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700405 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700406 remote_streams_(StreamCollection::Create()),
407 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000408
409PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100410 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700411 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700412 // Need to detach RTP senders/receivers from WebRtcSession,
413 // since it's about to be destroyed.
414 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700415 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700416 }
417 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700418 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700419 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700420 // Destroy stats_ because it depends on session_.
421 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800422 if (stats_collector_) {
423 stats_collector_->WaitForPendingRequest();
424 stats_collector_ = nullptr;
425 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700426 // Now destroy session_ before destroying other members,
427 // because its destruction fires signals (such as VoiceChannelDestroyed)
428 // which will trigger some final actions in PeerConnection...
Steve Anton978b8762017-09-29 12:15:02 -0700429 owned_session_.reset(nullptr);
430 session_ = nullptr;
deadbeef91dd5672016-05-18 16:55:30 -0700431 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700432 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700433 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700434 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700435 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700436 call_.reset();
437 event_log_.reset();
438 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000439}
440
441bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000442 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700443 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200444 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800445 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100446 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700447
448 RTCError config_error = ValidateConfiguration(configuration);
449 if (!config_error.ok()) {
450 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
451 return false;
452 }
453
deadbeef293e9262017-01-11 12:28:30 -0800454 if (!allocator) {
455 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
456 << "This shouldn't happen if using PeerConnectionFactory.";
457 return false;
458 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200459
deadbeef653b8e02015-11-11 12:55:10 -0800460 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800461 // TODO(deadbeef): Why do we do this?
462 LOG(LS_ERROR) << "PeerConnection initialized without a "
463 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800464 return false;
465 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000466 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800467 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800468
deadbeef91dd5672016-05-18 16:55:30 -0700469 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700470 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700471 if (!network_thread()->Invoke<bool>(
472 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
473 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000474 return false;
475 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000476
Steve Anton978b8762017-09-29 12:15:02 -0700477 owned_session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700478 call_.get(), factory_->channel_manager(), configuration.media_config,
Steve Anton978b8762017-09-29 12:15:02 -0700479 event_log_.get(), network_thread(), worker_thread(), signaling_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700480 port_allocator_.get(),
481 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700482 factory_->CreateTransportController(
483 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800484 configuration.redetermine_role_on_ice_restart)),
485#ifdef HAVE_SCTP
486 std::unique_ptr<cricket::SctpTransportInternalFactory>(
Steve Anton978b8762017-09-29 12:15:02 -0700487 new cricket::SctpTransportFactory(network_thread()))
deadbeef953c2ce2017-01-09 14:53:41 -0800488#else
489 nullptr
490#endif
491 ));
Steve Anton978b8762017-09-29 12:15:02 -0700492 session_ = owned_session_.get();
zhihuang29ff8442016-07-27 11:07:25 -0700493
deadbeefab9b2d12015-10-14 11:33:11 -0700494 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700495 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000496
497 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200498 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800499 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000500 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700501 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000502
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000503 // Register PeerConnection as receiver of local ice candidates.
504 // All the callbacks will be posted to the application from PeerConnection.
505 session_->RegisterIceObserver(this);
506 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700507 session_->SignalVoiceChannelCreated.connect(
508 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700509 session_->SignalVoiceChannelDestroyed.connect(
510 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700511 session_->SignalVideoChannelCreated.connect(
512 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700513 session_->SignalVideoChannelDestroyed.connect(
514 this, &PeerConnection::OnVideoChannelDestroyed);
515 session_->SignalDataChannelCreated.connect(
516 this, &PeerConnection::OnDataChannelCreated);
517 session_->SignalDataChannelDestroyed.connect(
518 this, &PeerConnection::OnDataChannelDestroyed);
519 session_->SignalDataChannelOpenMessage.connect(
520 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800521
522 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000523 return true;
524}
525
Steve Anton038834f2017-07-14 15:59:59 -0700526RTCError PeerConnection::ValidateConfiguration(
527 const RTCConfiguration& config) const {
528 if (config.ice_regather_interval_range &&
529 config.continual_gathering_policy == GATHER_ONCE) {
530 return RTCError(RTCErrorType::INVALID_PARAMETER,
531 "ice_regather_interval_range specified but continual "
532 "gathering policy is GATHER_ONCE");
533 }
534 return RTCError::OK();
535}
536
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000537rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000538PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700539 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540}
541
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000542rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000543PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700544 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000545}
546
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000547bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100548 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000549 if (IsClosed()) {
550 return false;
551 }
deadbeefab9b2d12015-10-14 11:33:11 -0700552 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000553 return false;
554 }
deadbeefab9b2d12015-10-14 11:33:11 -0700555
556 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800557 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
558 observer->SignalAudioTrackAdded.connect(this,
559 &PeerConnection::OnAudioTrackAdded);
560 observer->SignalAudioTrackRemoved.connect(
561 this, &PeerConnection::OnAudioTrackRemoved);
562 observer->SignalVideoTrackAdded.connect(this,
563 &PeerConnection::OnVideoTrackAdded);
564 observer->SignalVideoTrackRemoved.connect(
565 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700566 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700567
deadbeefab9b2d12015-10-14 11:33:11 -0700568 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700569 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700570 }
571 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700572 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700573 }
574
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000575 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576 observer_->OnRenegotiationNeeded();
577 return true;
578}
579
580void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100581 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700582 if (!IsClosed()) {
583 for (const auto& track : local_stream->GetAudioTracks()) {
584 RemoveAudioTrack(track.get(), local_stream);
585 }
586 for (const auto& track : local_stream->GetVideoTracks()) {
587 RemoveVideoTrack(track.get(), local_stream);
588 }
deadbeefab9b2d12015-10-14 11:33:11 -0700589 }
deadbeefab9b2d12015-10-14 11:33:11 -0700590 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800591 stream_observers_.erase(
592 std::remove_if(
593 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700594 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800595 return observer->stream()->label().compare(local_stream->label()) ==
596 0;
597 }),
598 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700599
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000600 if (IsClosed()) {
601 return;
602 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603 observer_->OnRenegotiationNeeded();
604}
605
deadbeefe1f9d832016-01-14 15:35:42 -0800606rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
607 MediaStreamTrackInterface* track,
608 std::vector<MediaStreamInterface*> streams) {
609 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
610 if (IsClosed()) {
611 return nullptr;
612 }
613 if (streams.size() >= 2) {
614 LOG(LS_ERROR)
615 << "Adding a track with two streams is not currently supported.";
616 return nullptr;
617 }
618 // TODO(deadbeef): Support adding a track to two different senders.
619 if (FindSenderForTrack(track) != senders_.end()) {
620 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
621 return nullptr;
622 }
623
624 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700625 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800626 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700627 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800628 signaling_thread(),
629 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700630 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800631 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700632 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800633 }
634 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700635 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800636 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700637 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800638 }
639 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700640 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800641 signaling_thread(),
642 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700643 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800644 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700645 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800646 }
647 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700648 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800649 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700650 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800651 }
652 } else {
653 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
654 return rtc::scoped_refptr<RtpSenderInterface>();
655 }
656
657 senders_.push_back(new_sender);
658 observer_->OnRenegotiationNeeded();
659 return new_sender;
660}
661
662bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
663 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
664 if (IsClosed()) {
665 return false;
666 }
667
668 auto it = std::find(senders_.begin(), senders_.end(), sender);
669 if (it == senders_.end()) {
670 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
671 return false;
672 }
deadbeefa601f5c2016-06-06 14:27:39 -0700673 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800674 senders_.erase(it);
675
676 observer_->OnRenegotiationNeeded();
677 return true;
678}
679
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000680rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100682 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700683 if (IsClosed()) {
684 return nullptr;
685 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000686 if (!track) {
687 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800688 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 }
deadbeef20cb0c12017-02-01 20:27:00 -0800690 auto it = FindSenderForTrack(track);
691 if (it == senders_.end()) {
692 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
693 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000694 }
695
deadbeef20cb0c12017-02-01 20:27:00 -0800696 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000697}
698
deadbeeffac06552015-11-25 11:26:01 -0800699rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800700 const std::string& kind,
701 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100702 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700703 if (IsClosed()) {
704 return nullptr;
705 }
deadbeefa601f5c2016-06-06 14:27:39 -0700706 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800707 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700708 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700709 signaling_thread(),
710 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800711 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700712 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700713 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800714 } else {
715 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800716 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800717 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800718 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700719 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800720 }
deadbeeffac06552015-11-25 11:26:01 -0800721 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800722 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800723}
724
deadbeef70ab1a12015-09-28 16:53:55 -0700725std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
726 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700727 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
728 for (const auto& sender : senders_) {
729 ret.push_back(sender.get());
730 }
731 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700732}
733
734std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
735PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700736 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
737 for (const auto& receiver : receivers_) {
738 ret.push_back(receiver.get());
739 }
740 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700741}
742
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000744 MediaStreamTrackInterface* track,
745 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100746 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700747 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800748 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 LOG(LS_ERROR) << "GetStats - observer is NULL.";
750 return false;
751 }
752
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000753 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700754 // The StatsCollector is used to tell if a track is valid because it may
755 // remember tracks that the PeerConnection previously removed.
756 if (track && !stats_->IsValidTrack(track->id())) {
757 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
758 << track->id();
759 return false;
760 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700761 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000762 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763 return true;
764}
765
hbos74e1a4f2016-09-15 23:33:01 -0700766void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
767 RTC_DCHECK(stats_collector_);
768 stats_collector_->GetStatsReport(callback);
769}
770
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
772 return signaling_state_;
773}
774
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000775PeerConnectionInterface::IceConnectionState
776PeerConnection::ice_connection_state() {
777 return ice_connection_state_;
778}
779
780PeerConnectionInterface::IceGatheringState
781PeerConnection::ice_gathering_state() {
782 return ice_gathering_state_;
783}
784
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000785rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000786PeerConnection::CreateDataChannel(
787 const std::string& label,
788 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100789 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700790#ifdef HAVE_QUIC
791 if (session_->data_channel_type() == cricket::DCT_QUIC) {
792 // TODO(zhihuang): Handle case when config is NULL.
793 if (!config) {
794 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
795 return nullptr;
796 }
797 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
798 if (!config->reliable || config->ordered) {
799 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
800 "ordered delivery.";
801 return nullptr;
802 }
803 return session_->quic_data_transport()->CreateDataChannel(label, config);
804 }
805#endif // HAVE_QUIC
806
deadbeefab9b2d12015-10-14 11:33:11 -0700807 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000808
kwibergd1fe2812016-04-27 06:47:29 -0700809 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000810 if (config) {
811 internal_config.reset(new InternalDataChannelInit(*config));
812 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000813 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700814 InternalCreateDataChannel(label, internal_config.get()));
815 if (!channel.get()) {
816 return nullptr;
817 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000819 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
820 // the first SCTP DataChannel.
821 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
822 observer_->OnRenegotiationNeeded();
823 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000824
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 return DataChannelProxy::Create(signaling_thread(), channel.get());
826}
827
828void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
829 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton3df5dca2017-10-19 16:11:30 -0700831
zhihuang1c378ed2017-08-17 14:10:50 -0700832 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
833 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
834 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
835 // compares the mandatory fields parsed with the mandatory fields added in the
836 // |constraints| and some downstream applications might create offers with
837 // mandatory fields which would not be parsed in the helper method. For
838 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
839 // |constraints| as a mandatory field but it is not parsed.
840 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000841
zhihuang1c378ed2017-08-17 14:10:50 -0700842 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000843}
844
845void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
846 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100847 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton3df5dca2017-10-19 16:11:30 -0700848
nisse7ce109a2017-01-31 00:57:56 -0800849 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000850 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
851 return;
852 }
deadbeefab9b2d12015-10-14 11:33:11 -0700853
Steve Anton3df5dca2017-10-19 16:11:30 -0700854 if (IsClosed()) {
855 std::string error = "CreateOffer called when PeerConnection is closed.";
856 LOG(LS_ERROR) << error;
857 PostCreateSessionDescriptionFailure(observer, error);
858 return;
859 }
860
zhihuang1c378ed2017-08-17 14:10:50 -0700861 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700862 std::string error = "CreateOffer called with invalid options.";
863 LOG(LS_ERROR) << error;
864 PostCreateSessionDescriptionFailure(observer, error);
865 return;
866 }
867
zhihuang1c378ed2017-08-17 14:10:50 -0700868 cricket::MediaSessionOptions session_options;
869 GetOptionsForOffer(options, &session_options);
deadbeefab9b2d12015-10-14 11:33:11 -0700870 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871}
872
873void PeerConnection::CreateAnswer(
874 CreateSessionDescriptionObserver* observer,
875 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100876 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton3df5dca2017-10-19 16:11:30 -0700877
nisse7ce109a2017-01-31 00:57:56 -0800878 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
880 return;
881 }
deadbeefab9b2d12015-10-14 11:33:11 -0700882
zhihuang1c378ed2017-08-17 14:10:50 -0700883 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
884 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
885 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700886 std::string error = "CreateAnswer called with invalid constraints.";
887 LOG(LS_ERROR) << error;
888 PostCreateSessionDescriptionFailure(observer, error);
889 return;
890 }
891
Steve Anton3df5dca2017-10-19 16:11:30 -0700892 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -0800893}
894
895void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
896 const RTCOfferAnswerOptions& options) {
897 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800898 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800899 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
900 return;
901 }
902
Steve Anton3df5dca2017-10-19 16:11:30 -0700903 if (IsClosed()) {
904 std::string error = "CreateAnswer called when PeerConnection is closed.";
905 LOG(LS_ERROR) << error;
906 PostCreateSessionDescriptionFailure(observer, error);
907 return;
908 }
909
910 if (!session_->remote_description() ||
911 session_->remote_description()->type() !=
912 SessionDescriptionInterface::kOffer) {
913 std::string error = "CreateAnswer called without remote offer.";
914 LOG(LS_ERROR) << error;
915 PostCreateSessionDescriptionFailure(observer, error);
916 return;
917 }
918
htaa2a49d92016-03-04 02:51:39 -0800919 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -0700920 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800921
922 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923}
924
925void PeerConnection::SetLocalDescription(
926 SetSessionDescriptionObserver* observer,
927 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100928 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -0800929 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
931 return;
932 }
933 if (!desc) {
934 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
935 return;
936 }
Steve Anton3df5dca2017-10-19 16:11:30 -0700937
938 // Takes the ownership of |desc| regardless of the result.
939 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
940
941 if (IsClosed()) {
942 std::string error = "Failed to set local " + desc->type() +
943 " SDP: Called in wrong state: STATE_CLOSED";
944 LOG(LS_ERROR) << error;
945 PostSetSessionDescriptionFailure(observer, error);
946 return;
947 }
948
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 // Update stats here so that we have the most recent stats for tracks and
950 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000951 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 std::string error;
Steve Anton3df5dca2017-10-19 16:11:30 -0700953 if (!session_->SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 PostSetSessionDescriptionFailure(observer, error);
955 return;
956 }
deadbeefab9b2d12015-10-14 11:33:11 -0700957
958 // If setting the description decided our SSL role, allocate any necessary
959 // SCTP sids.
960 rtc::SSLRole role;
961 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800962 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700963 AllocateSctpSids(role);
964 }
965
966 // Update state and SSRC of local MediaStreams and DataChannels based on the
967 // local session description.
968 const cricket::ContentInfo* audio_content =
969 GetFirstAudioContent(desc->description());
970 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800971 if (audio_content->rejected) {
972 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
973 } else {
974 const cricket::AudioContentDescription* audio_desc =
975 static_cast<const cricket::AudioContentDescription*>(
976 audio_content->description);
977 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
978 }
deadbeefab9b2d12015-10-14 11:33:11 -0700979 }
980
981 const cricket::ContentInfo* video_content =
982 GetFirstVideoContent(desc->description());
983 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800984 if (video_content->rejected) {
985 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
986 } else {
987 const cricket::VideoContentDescription* video_desc =
988 static_cast<const cricket::VideoContentDescription*>(
989 video_content->description);
990 UpdateLocalTracks(video_desc->streams(), video_desc->type());
991 }
deadbeefab9b2d12015-10-14 11:33:11 -0700992 }
993
994 const cricket::ContentInfo* data_content =
995 GetFirstDataContent(desc->description());
996 if (data_content) {
997 const cricket::DataContentDescription* data_desc =
998 static_cast<const cricket::DataContentDescription*>(
999 data_content->description);
1000 if (rtc::starts_with(data_desc->protocol().data(),
1001 cricket::kMediaProtocolRtpPrefix)) {
1002 UpdateLocalRtpDataChannels(data_desc->streams());
1003 }
1004 }
1005
1006 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001007 signaling_thread()->Post(RTC_FROM_HERE, this,
1008 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001009
deadbeef42a42632017-03-10 15:18:00 -08001010 // According to JSEP, after setLocalDescription, changing the candidate pool
1011 // size is not allowed, and changing the set of ICE servers will not result
1012 // in new candidates being gathered.
1013 port_allocator_->FreezeCandidatePool();
1014
deadbeefcbecd352015-09-23 11:50:27 -07001015 // MaybeStartGathering needs to be called after posting
1016 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1017 // before signaling that SetLocalDescription completed.
1018 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001019
1020 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1021 // TODO(deadbeef): We already had to hop to the network thread for
1022 // MaybeStartGathering...
1023 network_thread()->Invoke<void>(
1024 RTC_FROM_HERE,
1025 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1026 port_allocator_.get()));
1027 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028}
1029
1030void PeerConnection::SetRemoteDescription(
1031 SetSessionDescriptionObserver* observer,
1032 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001033 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001034 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1036 return;
1037 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 if (!desc) {
1039 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1040 return;
1041 }
Steve Anton3df5dca2017-10-19 16:11:30 -07001042
1043 // Takes the ownership of |desc| regardless of the result.
1044 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1045
1046 if (IsClosed()) {
1047 std::string error = "Failed to set remote " + desc->type() +
1048 " SDP: Called in wrong state: STATE_CLOSED";
1049 LOG(LS_ERROR) << error;
1050 PostSetSessionDescriptionFailure(observer, error);
1051 return;
1052 }
1053
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054 // Update stats here so that we have the most recent stats for tracks and
1055 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001056 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001057 std::string error;
Steve Anton3df5dca2017-10-19 16:11:30 -07001058 if (!session_->SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059 PostSetSessionDescriptionFailure(observer, error);
1060 return;
1061 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062
deadbeefab9b2d12015-10-14 11:33:11 -07001063 // If setting the description decided our SSL role, allocate any necessary
1064 // SCTP sids.
1065 rtc::SSLRole role;
1066 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001067 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001068 AllocateSctpSids(role);
1069 }
1070
1071 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001072 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1073 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1074 const cricket::AudioContentDescription* audio_desc =
1075 GetFirstAudioContentDescription(remote_desc);
1076 const cricket::VideoContentDescription* video_desc =
1077 GetFirstVideoContentDescription(remote_desc);
1078 const cricket::DataContentDescription* data_desc =
1079 GetFirstDataContentDescription(remote_desc);
1080
1081 // Check if the descriptions include streams, just in case the peer supports
1082 // MSID, but doesn't indicate so with "a=msid-semantic".
1083 if (remote_desc->msid_supported() ||
1084 (audio_desc && !audio_desc->streams().empty()) ||
1085 (video_desc && !video_desc->streams().empty())) {
1086 remote_peer_supports_msid_ = true;
1087 }
deadbeefab9b2d12015-10-14 11:33:11 -07001088
1089 // We wait to signal new streams until we finish processing the description,
1090 // since only at that point will new streams have all their tracks.
1091 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1092
Steve Anton3df5dca2017-10-19 16:11:30 -07001093 // TODO(steveanton): When removing RTP senders/receivers in response to a
1094 // rejected media section, there is some cleanup logic that expects the voice/
1095 // video channel to still be set. But in this method the voice/video channel
1096 // would have been destroyed by WebRtcSession's SetRemoteDescription method
1097 // above, so the cleanup that relies on them fails to run. This is hard to fix
1098 // with WebRtcSession and PeerConnection separated, but once the classes are
1099 // merged it will be easy to call RemoveTracks right before destroying the
1100 // voice/video channels.
1101
deadbeefab9b2d12015-10-14 11:33:11 -07001102 // Find all audio rtp streams and create corresponding remote AudioTracks
1103 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001104 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001105 if (audio_content->rejected) {
1106 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1107 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001108 bool default_audio_track_needed =
1109 !remote_peer_supports_msid_ &&
1110 MediaContentDirectionHasSend(audio_desc->direction());
1111 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1112 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001113 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001114 }
deadbeefab9b2d12015-10-14 11:33:11 -07001115 }
1116
1117 // Find all video rtp streams and create corresponding remote VideoTracks
1118 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001119 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001120 if (video_content->rejected) {
1121 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1122 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001123 bool default_video_track_needed =
1124 !remote_peer_supports_msid_ &&
1125 MediaContentDirectionHasSend(video_desc->direction());
1126 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1127 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001128 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001129 }
deadbeefab9b2d12015-10-14 11:33:11 -07001130 }
1131
1132 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001133 if (data_desc) {
1134 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001135 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001136 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001137 }
1138 }
1139
1140 // Iterate new_streams and notify the observer about new MediaStreams.
1141 for (size_t i = 0; i < new_streams->count(); ++i) {
1142 MediaStreamInterface* new_stream = new_streams->at(i);
1143 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001144 observer_->OnAddStream(
1145 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001146 }
1147
deadbeefbda7e0b2015-12-08 17:13:40 -08001148 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001149
1150 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001151 signaling_thread()->Post(RTC_FROM_HERE, this,
1152 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001153
1154 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1155 // TODO(deadbeef): We already had to hop to the network thread for
1156 // MaybeStartGathering...
1157 network_thread()->Invoke<void>(
1158 RTC_FROM_HERE,
1159 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1160 port_allocator_.get()));
1161 }
deadbeeffc648b62015-10-13 16:42:33 -07001162}
1163
deadbeef46c73892016-11-16 19:42:04 -08001164PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1165 return configuration_;
1166}
1167
deadbeef293e9262017-01-11 12:28:30 -08001168bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1169 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001170 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001171
1172 if (session_->local_description() &&
1173 configuration.ice_candidate_pool_size !=
1174 configuration_.ice_candidate_pool_size) {
1175 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1176 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001177 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001178 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001179
deadbeef293e9262017-01-11 12:28:30 -08001180 // The simplest (and most future-compatible) way to tell if the config was
1181 // modified in an invalid way is to copy each property we do support
1182 // modifying, then use operator==. There are far more properties we don't
1183 // support modifying than those we do, and more could be added.
1184 RTCConfiguration modified_config = configuration_;
1185 modified_config.servers = configuration.servers;
1186 modified_config.type = configuration.type;
1187 modified_config.ice_candidate_pool_size =
1188 configuration.ice_candidate_pool_size;
1189 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001190 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001191 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001192 if (configuration != modified_config) {
1193 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1194 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1195 }
1196
Steve Anton038834f2017-07-14 15:59:59 -07001197 // Validate the modified configuration.
1198 RTCError validate_error = ValidateConfiguration(modified_config);
1199 if (!validate_error.ok()) {
1200 return SafeSetError(std::move(validate_error), error);
1201 }
1202
deadbeef293e9262017-01-11 12:28:30 -08001203 // Note that this isn't possible through chromium, since it's an unsigned
1204 // short in WebIDL.
1205 if (configuration.ice_candidate_pool_size < 0 ||
1206 configuration.ice_candidate_pool_size > UINT16_MAX) {
1207 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1208 }
1209
1210 // Parse ICE servers before hopping to network thread.
1211 cricket::ServerAddresses stun_servers;
1212 std::vector<cricket::RelayServerConfig> turn_servers;
1213 RTCErrorType parse_error =
1214 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1215 if (parse_error != RTCErrorType::NONE) {
1216 return SafeSetError(parse_error, error);
1217 }
1218
1219 // In theory this shouldn't fail.
1220 if (!network_thread()->Invoke<bool>(
1221 RTC_FROM_HERE,
1222 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1223 stun_servers, turn_servers, modified_config.type,
1224 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001225 modified_config.prune_turn_ports,
1226 modified_config.turn_customizer))) {
deadbeef293e9262017-01-11 12:28:30 -08001227 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1228 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1229 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001230
deadbeefd1a38b52016-12-10 13:15:33 -08001231 // As described in JSEP, calling setConfiguration with new ICE servers or
1232 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1233 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001234 if (modified_config.servers != configuration_.servers ||
1235 modified_config.type != configuration_.type ||
1236 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001237 session_->SetNeedsIceRestartFlag();
1238 }
skvladd1f5fda2017-02-03 16:54:05 -08001239
1240 if (modified_config.ice_check_min_interval !=
1241 configuration_.ice_check_min_interval) {
1242 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1243 }
1244
deadbeef293e9262017-01-11 12:28:30 -08001245 configuration_ = modified_config;
1246 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001247}
1248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001249bool PeerConnection::AddIceCandidate(
1250 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001251 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001252 if (IsClosed()) {
1253 return false;
1254 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001255 return session_->ProcessIceMessage(ice_candidate);
1256}
1257
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001258bool PeerConnection::RemoveIceCandidates(
1259 const std::vector<cricket::Candidate>& candidates) {
1260 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1261 return session_->RemoveRemoteIceCandidates(candidates);
1262}
1263
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001264void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001265 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001266 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001267
1268 if (session_) {
1269 session_->set_metrics_observer(uma_observer_);
1270 }
1271
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001272 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001273 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001274 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001275 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001276 uma_observer_->IncrementEnumCounter(
1277 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1278 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001279 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001280 uma_observer_->IncrementEnumCounter(
1281 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1282 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001283 }
1284 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001285}
1286
zstein4b979802017-06-02 14:37:37 -07001287RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001288 if (!worker_thread()->IsCurrent()) {
1289 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001290 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1291 }
1292
1293 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1294 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1295 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1296 if (has_min && *bitrate.min_bitrate_bps < 0) {
1297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1298 "min_bitrate_bps <= 0");
1299 }
1300 if (has_current) {
1301 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1302 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1303 "current_bitrate_bps < min_bitrate_bps");
1304 } else if (*bitrate.current_bitrate_bps < 0) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1306 "curent_bitrate_bps < 0");
1307 }
1308 }
1309 if (has_max) {
1310 if (has_current &&
1311 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1312 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1313 "max_bitrate_bps < current_bitrate_bps");
1314 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1315 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1316 "max_bitrate_bps < min_bitrate_bps");
1317 } else if (*bitrate.max_bitrate_bps < 0) {
1318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1319 "max_bitrate_bps < 0");
1320 }
1321 }
1322
1323 Call::Config::BitrateConfigMask mask;
1324 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1325 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1326 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1327
1328 RTC_DCHECK(call_.get());
1329 call_->SetBitrateConfigMask(mask);
1330
1331 return RTCError::OK();
1332}
1333
Steve Anton8c0f7a72017-10-03 10:03:10 -07001334std::unique_ptr<rtc::SSLCertificate>
1335PeerConnection::GetRemoteAudioSSLCertificate() {
1336 if (!session_) {
1337 return nullptr;
1338 }
1339 auto* voice_channel = session_->voice_channel();
1340 if (!voice_channel) {
1341 return nullptr;
1342 }
1343 return GetRemoteSSLCertificate(voice_channel->transport_name());
1344}
1345
ivoc14d5dbe2016-07-04 07:06:55 -07001346bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1347 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001348 // TODO(eladalon): It would be better to not allow negative values into PC.
1349 const size_t max_size = (max_size_bytes < 0)
1350 ? RtcEventLog::kUnlimitedOutput
1351 : rtc::saturated_cast<size_t>(max_size_bytes);
1352 return StartRtcEventLog(
1353 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
1354}
1355
1356bool PeerConnection::StartRtcEventLog(
1357 std::unique_ptr<RtcEventLogOutput> output) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001358 // TODO(eladalon): In C++14, this can be done with a lambda.
1359 struct Functor {
1360 bool operator()() { return pc->StartRtcEventLog_w(std::move(output)); }
1361 PeerConnection* const pc;
1362 std::unique_ptr<RtcEventLogOutput> output;
Elad Alon99c3fe52017-10-13 16:29:40 +02001363 };
Karl Wibergd6b48192017-10-16 23:01:06 +02001364 return worker_thread()->Invoke<bool>(RTC_FROM_HERE,
1365 Functor{this, std::move(output)});
ivoc14d5dbe2016-07-04 07:06:55 -07001366}
1367
1368void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001369 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001370 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1371}
1372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373const SessionDescriptionInterface* PeerConnection::local_description() const {
1374 return session_->local_description();
1375}
1376
1377const SessionDescriptionInterface* PeerConnection::remote_description() const {
1378 return session_->remote_description();
1379}
1380
deadbeeffe4a8a42016-12-20 17:56:17 -08001381const SessionDescriptionInterface* PeerConnection::current_local_description()
1382 const {
1383 return session_->current_local_description();
1384}
1385
1386const SessionDescriptionInterface* PeerConnection::current_remote_description()
1387 const {
1388 return session_->current_remote_description();
1389}
1390
1391const SessionDescriptionInterface* PeerConnection::pending_local_description()
1392 const {
1393 return session_->pending_local_description();
1394}
1395
1396const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1397 const {
1398 return session_->pending_remote_description();
1399}
1400
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001402 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403 // Update stats here so that we have the most recent stats for tracks and
1404 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001405 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406
deadbeefd59daf82015-10-14 15:02:44 -07001407 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001408 network_thread()->Invoke<void>(
1409 RTC_FROM_HERE,
1410 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1411 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001412
Steve Anton978b8762017-09-29 12:15:02 -07001413 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001414 call_.reset();
1415 // The event log must outlive call (and any other object that uses it).
1416 event_log_.reset();
1417 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001418}
1419
deadbeefd59daf82015-10-14 15:02:44 -07001420void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1421 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001423 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001424 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001425 break;
deadbeefd59daf82015-10-14 15:02:44 -07001426 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1428 break;
deadbeefd59daf82015-10-14 15:02:44 -07001429 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1431 break;
deadbeefd59daf82015-10-14 15:02:44 -07001432 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1434 break;
deadbeefd59daf82015-10-14 15:02:44 -07001435 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1437 break;
deadbeefd59daf82015-10-14 15:02:44 -07001438 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439 ChangeSignalingState(PeerConnectionInterface::kStable);
1440 break;
deadbeefd59daf82015-10-14 15:02:44 -07001441 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442 ChangeSignalingState(PeerConnectionInterface::kClosed);
1443 break;
1444 default:
1445 break;
1446 }
1447}
1448
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001449void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1452 SetSessionDescriptionMsg* param =
1453 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1454 param->observer->OnSuccess();
1455 delete param;
1456 break;
1457 }
1458 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1459 SetSessionDescriptionMsg* param =
1460 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1461 param->observer->OnFailure(param->error);
1462 delete param;
1463 break;
1464 }
deadbeefab9b2d12015-10-14 11:33:11 -07001465 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1466 CreateSessionDescriptionMsg* param =
1467 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1468 param->observer->OnFailure(param->error);
1469 delete param;
1470 break;
1471 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 case MSG_GETSTATS: {
1473 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001474 StatsReports reports;
1475 stats_->GetStats(param->track, &reports);
1476 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477 delete param;
1478 break;
1479 }
deadbeefbd292462015-12-14 18:15:29 -08001480 case MSG_FREE_DATACHANNELS: {
1481 sctp_data_channels_to_free_.clear();
1482 break;
1483 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001484 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001485 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486 break;
1487 }
1488}
1489
deadbeefab9b2d12015-10-14 11:33:11 -07001490void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001491 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001492 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001493 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1494 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001495 signaling_thread(),
1496 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1497 stream->AddTrack(
1498 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001499 receivers_.push_back(receiver);
1500 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1501 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1502 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503}
1504
deadbeefab9b2d12015-10-14 11:33:11 -07001505void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001506 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001507 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001508 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1509 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001510 signaling_thread(),
Steve Anton978b8762017-09-29 12:15:02 -07001511 new VideoRtpReceiver(track_id, worker_thread(), ssrc,
deadbeefe814a0d2017-02-25 18:15:09 -08001512 session_->video_channel()));
1513 stream->AddTrack(
1514 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001515 receivers_.push_back(receiver);
1516 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1517 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1518 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519}
1520
deadbeef70ab1a12015-09-28 16:53:55 -07001521// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1522// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07001523rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
1524 const std::string& track_id) {
perkjd61bf802016-03-24 03:16:19 -07001525 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001526 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001527 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001528 << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07001529 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07001530 }
Henrik Boström933d8b02017-10-10 10:05:16 -07001531 (*it)->internal()->Stop();
1532 rtc::scoped_refptr<RtpReceiverInterface> receiver = *it;
1533 receivers_.erase(it);
1534 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535}
1536
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001537void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1538 MediaStreamInterface* stream) {
1539 RTC_DCHECK(!IsClosed());
1540 auto sender = FindSenderForTrack(track);
1541 if (sender != senders_.end()) {
1542 // We already have a sender for this track, so just change the stream_id
1543 // so that it's correct in the next call to CreateOffer.
1544 (*sender)->internal()->set_stream_id(stream->label());
1545 return;
1546 }
1547
1548 // Normal case; we've never seen this track before.
1549 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1550 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1551 signaling_thread(),
Steve Anton8ffb9c32017-08-31 15:45:38 -07001552 new AudioRtpSender(track, {stream->label()},
1553 session_->voice_channel(), stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001554 senders_.push_back(new_sender);
1555 // If the sender has already been configured in SDP, we call SetSsrc,
1556 // which will connect the sender to the underlying transport. This can
1557 // occur if a local session description that contains the ID of the sender
1558 // is set before AddStream is called. It can also occur if the local
1559 // session description is not changed and RemoveStream is called, and
1560 // later AddStream is called again with the same stream.
1561 const TrackInfo* track_info =
1562 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1563 if (track_info) {
1564 new_sender->internal()->SetSsrc(track_info->ssrc);
1565 }
1566}
1567
1568// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1569// indefinitely, when we have unified plan SDP.
1570void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1571 MediaStreamInterface* stream) {
1572 RTC_DCHECK(!IsClosed());
1573 auto sender = FindSenderForTrack(track);
1574 if (sender == senders_.end()) {
1575 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1576 << " doesn't exist.";
1577 return;
1578 }
1579 (*sender)->internal()->Stop();
1580 senders_.erase(sender);
1581}
1582
1583void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1584 MediaStreamInterface* stream) {
1585 RTC_DCHECK(!IsClosed());
1586 auto sender = FindSenderForTrack(track);
1587 if (sender != senders_.end()) {
1588 // We already have a sender for this track, so just change the stream_id
1589 // so that it's correct in the next call to CreateOffer.
1590 (*sender)->internal()->set_stream_id(stream->label());
1591 return;
1592 }
1593
1594 // Normal case; we've never seen this track before.
1595 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1596 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton8ffb9c32017-08-31 15:45:38 -07001597 signaling_thread(), new VideoRtpSender(track, {stream->label()},
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001598 session_->video_channel()));
1599 senders_.push_back(new_sender);
1600 const TrackInfo* track_info =
1601 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1602 if (track_info) {
1603 new_sender->internal()->SetSsrc(track_info->ssrc);
1604 }
1605}
1606
1607void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1608 MediaStreamInterface* stream) {
1609 RTC_DCHECK(!IsClosed());
1610 auto sender = FindSenderForTrack(track);
1611 if (sender == senders_.end()) {
1612 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1613 << " doesn't exist.";
1614 return;
1615 }
1616 (*sender)->internal()->Stop();
1617 senders_.erase(sender);
1618}
1619
zstein6dfd53a2017-03-06 13:49:03 -08001620void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001622 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001623 // After transitioning to "closed", ignore any additional states from
1624 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001625 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001626 return;
1627 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001628 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001629 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630}
1631
1632void PeerConnection::OnIceGatheringChange(
1633 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001634 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001635 if (IsClosed()) {
1636 return;
1637 }
1638 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001639 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640}
1641
jbauch81bf7b02017-03-25 08:31:12 -07001642void PeerConnection::OnIceCandidate(
1643 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001644 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001645 if (IsClosed()) {
1646 return;
1647 }
jbauch81bf7b02017-03-25 08:31:12 -07001648 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001649}
1650
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001651void PeerConnection::OnIceCandidatesRemoved(
1652 const std::vector<cricket::Candidate>& candidates) {
1653 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001654 if (IsClosed()) {
1655 return;
1656 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001657 observer_->OnIceCandidatesRemoved(candidates);
1658}
1659
Peter Thatcher54360512015-07-08 11:08:35 -07001660void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001661 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001662 if (IsClosed()) {
1663 return;
1664 }
Peter Thatcher54360512015-07-08 11:08:35 -07001665 observer_->OnIceConnectionReceivingChange(receiving);
1666}
1667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001668void PeerConnection::ChangeSignalingState(
1669 PeerConnectionInterface::SignalingState signaling_state) {
1670 signaling_state_ = signaling_state;
1671 if (signaling_state == kClosed) {
1672 ice_connection_state_ = kIceConnectionClosed;
1673 observer_->OnIceConnectionChange(ice_connection_state_);
1674 if (ice_gathering_state_ != kIceGatheringComplete) {
1675 ice_gathering_state_ = kIceGatheringComplete;
1676 observer_->OnIceGatheringChange(ice_gathering_state_);
1677 }
1678 }
1679 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680}
1681
deadbeefeb459812015-12-15 19:24:43 -08001682void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1683 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001684 if (IsClosed()) {
1685 return;
1686 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001687 AddAudioTrack(track, stream);
1688 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001689}
1690
deadbeefeb459812015-12-15 19:24:43 -08001691void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1692 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001693 if (IsClosed()) {
1694 return;
1695 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001696 RemoveAudioTrack(track, stream);
1697 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001698}
1699
1700void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1701 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001702 if (IsClosed()) {
1703 return;
1704 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001705 AddVideoTrack(track, stream);
1706 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001707}
1708
1709void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1710 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001711 if (IsClosed()) {
1712 return;
1713 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001714 RemoveVideoTrack(track, stream);
1715 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001716}
1717
deadbeefab9b2d12015-10-14 11:33:11 -07001718void PeerConnection::PostSetSessionDescriptionFailure(
1719 SetSessionDescriptionObserver* observer,
1720 const std::string& error) {
1721 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1722 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001723 signaling_thread()->Post(RTC_FROM_HERE, this,
1724 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001725}
1726
1727void PeerConnection::PostCreateSessionDescriptionFailure(
1728 CreateSessionDescriptionObserver* observer,
1729 const std::string& error) {
1730 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1731 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001732 signaling_thread()->Post(RTC_FROM_HERE, this,
1733 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001734}
1735
zhihuang1c378ed2017-08-17 14:10:50 -07001736void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001737 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1738 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001739 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1740
1741 // Figure out transceiver directional preferences.
1742 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1743 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1744
1745 // By default, generate sendrecv/recvonly m= sections.
1746 bool recv_audio = true;
1747 bool recv_video = true;
1748
1749 // By default, only offer a new m= section if we have media to send with it.
1750 bool offer_new_audio_description = send_audio;
1751 bool offer_new_video_description = send_video;
1752 bool offer_new_data_description = HasDataChannels();
1753
1754 // The "offer_to_receive_X" options allow those defaults to be overridden.
1755 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1756 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1757 offer_new_audio_description =
1758 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1759 }
1760 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1761 recv_video = (rtc_options.offer_to_receive_video > 0);
1762 offer_new_video_description =
1763 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1764 }
1765
1766 rtc::Optional<size_t> audio_index;
1767 rtc::Optional<size_t> video_index;
1768 rtc::Optional<size_t> data_index;
1769 // If a current description exists, generate m= sections in the same order,
1770 // using the first audio/video/data section that appears and rejecting
1771 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001772 if (session_->local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07001773 GenerateMediaDescriptionOptions(
1774 session_->local_description(),
1775 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1776 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1777 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001778 }
1779
zhihuang1c378ed2017-08-17 14:10:50 -07001780 // Add audio/video/data m= sections to the end if needed.
1781 if (!audio_index && offer_new_audio_description) {
1782 session_options->media_description_options.push_back(
1783 cricket::MediaDescriptionOptions(
1784 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1785 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1786 audio_index = rtc::Optional<size_t>(
1787 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001788 }
zhihuang1c378ed2017-08-17 14:10:50 -07001789 if (!video_index && offer_new_video_description) {
1790 session_options->media_description_options.push_back(
1791 cricket::MediaDescriptionOptions(
1792 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1793 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1794 video_index = rtc::Optional<size_t>(
1795 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001796 }
zhihuang1c378ed2017-08-17 14:10:50 -07001797 if (!data_index && offer_new_data_description) {
1798 session_options->media_description_options.push_back(
1799 cricket::MediaDescriptionOptions(
1800 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1801 cricket::RtpTransceiverDirection(true, true), false));
1802 data_index = rtc::Optional<size_t>(
1803 session_options->media_description_options.size() - 1);
1804 }
1805
1806 cricket::MediaDescriptionOptions* audio_media_description_options =
1807 !audio_index ? nullptr
1808 : &session_options->media_description_options[*audio_index];
1809 cricket::MediaDescriptionOptions* video_media_description_options =
1810 !video_index ? nullptr
1811 : &session_options->media_description_options[*video_index];
1812 cricket::MediaDescriptionOptions* data_media_description_options =
1813 !data_index ? nullptr
1814 : &session_options->media_description_options[*data_index];
1815
1816 // Apply ICE restart flag and renomination flag.
1817 for (auto& options : session_options->media_description_options) {
1818 options.transport_options.ice_restart = rtc_options.ice_restart;
1819 options.transport_options.enable_ice_renomination =
1820 configuration_.enable_ice_renomination;
1821 }
1822
1823 AddRtpSenderOptions(senders_, audio_media_description_options,
1824 video_media_description_options);
1825 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001826
zhihuang9763d562016-08-05 11:14:50 -07001827 // Intentionally unset the data channel type for RTP data channel with the
1828 // second condition. Otherwise the RTP data channels would be successfully
1829 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1830 // when building with chromium. We want to leave RTP data channels broken, so
1831 // people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001832 if (!rtp_data_channels_.empty() ||
1833 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001834 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001835 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001836
1837 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001838 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001839}
1840
zhihuang1c378ed2017-08-17 14:10:50 -07001841void PeerConnection::GetOptionsForAnswer(
1842 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001843 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001844 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001845
zhihuang1c378ed2017-08-17 14:10:50 -07001846 // Figure out transceiver directional preferences.
1847 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1848 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1849
1850 // By default, generate sendrecv/recvonly m= sections. The direction is also
1851 // restricted by the direction in the offer.
1852 bool recv_audio = true;
1853 bool recv_video = true;
1854
1855 // The "offer_to_receive_X" options allow those defaults to be overridden.
1856 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1857 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001858 }
zhihuang1c378ed2017-08-17 14:10:50 -07001859 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1860 recv_video = (rtc_options.offer_to_receive_video > 0);
1861 }
1862
1863 rtc::Optional<size_t> audio_index;
1864 rtc::Optional<size_t> video_index;
1865 rtc::Optional<size_t> data_index;
zhihuang141aacb2017-08-29 13:23:53 -07001866 if (session_->remote_description()) {
1867 // The pending remote description should be an offer.
1868 RTC_DCHECK(session_->remote_description()->type() ==
1869 SessionDescriptionInterface::kOffer);
1870 // Generate m= sections that match those in the offer.
1871 // Note that mediasession.cc will handle intersection our preferred
1872 // direction with the offered direction.
1873 GenerateMediaDescriptionOptions(
1874 session_->remote_description(),
1875 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1876 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1877 &video_index, &data_index, session_options);
1878 }
zhihuang1c378ed2017-08-17 14:10:50 -07001879
1880 cricket::MediaDescriptionOptions* audio_media_description_options =
1881 !audio_index ? nullptr
1882 : &session_options->media_description_options[*audio_index];
1883 cricket::MediaDescriptionOptions* video_media_description_options =
1884 !video_index ? nullptr
1885 : &session_options->media_description_options[*video_index];
1886 cricket::MediaDescriptionOptions* data_media_description_options =
1887 !data_index ? nullptr
1888 : &session_options->media_description_options[*data_index];
1889
1890 // Apply ICE renomination flag.
1891 for (auto& options : session_options->media_description_options) {
1892 options.transport_options.enable_ice_renomination =
1893 configuration_.enable_ice_renomination;
1894 }
1895
1896 AddRtpSenderOptions(senders_, audio_media_description_options,
1897 video_media_description_options);
1898 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
1899
zhihuang9763d562016-08-05 11:14:50 -07001900 // Intentionally unset the data channel type for RTP data channel. Otherwise
1901 // the RTP data channels would be successfully negotiated by default and the
1902 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1903 // We want to leave RTP data channels broken, so people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001904 if (!rtp_data_channels_.empty() ||
1905 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001906 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001907 }
zhihuangaf388472016-11-02 16:49:48 -07001908
zhihuang1c378ed2017-08-17 14:10:50 -07001909 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001910 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001911}
1912
zhihuang1c378ed2017-08-17 14:10:50 -07001913void PeerConnection::GenerateMediaDescriptionOptions(
1914 const SessionDescriptionInterface* session_desc,
1915 cricket::RtpTransceiverDirection audio_direction,
1916 cricket::RtpTransceiverDirection video_direction,
1917 rtc::Optional<size_t>* audio_index,
1918 rtc::Optional<size_t>* video_index,
1919 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08001920 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001921 for (const cricket::ContentInfo& content :
1922 session_desc->description()->contents()) {
1923 if (IsAudioContent(&content)) {
1924 // If we already have an audio m= section, reject this extra one.
1925 if (*audio_index) {
1926 session_options->media_description_options.push_back(
1927 cricket::MediaDescriptionOptions(
1928 cricket::MEDIA_TYPE_AUDIO, content.name,
1929 cricket::RtpTransceiverDirection(false, false), true));
1930 } else {
1931 session_options->media_description_options.push_back(
1932 cricket::MediaDescriptionOptions(
1933 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
1934 !audio_direction.send && !audio_direction.recv));
1935 *audio_index = rtc::Optional<size_t>(
1936 session_options->media_description_options.size() - 1);
1937 }
1938 } else if (IsVideoContent(&content)) {
1939 // If we already have an video m= section, reject this extra one.
1940 if (*video_index) {
1941 session_options->media_description_options.push_back(
1942 cricket::MediaDescriptionOptions(
1943 cricket::MEDIA_TYPE_VIDEO, content.name,
1944 cricket::RtpTransceiverDirection(false, false), true));
1945 } else {
1946 session_options->media_description_options.push_back(
1947 cricket::MediaDescriptionOptions(
1948 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1949 !video_direction.send && !video_direction.recv));
1950 *video_index = rtc::Optional<size_t>(
1951 session_options->media_description_options.size() - 1);
1952 }
1953 } else {
1954 RTC_DCHECK(IsDataContent(&content));
1955 // If we already have an data m= section, reject this extra one.
1956 if (*data_index) {
1957 session_options->media_description_options.push_back(
1958 cricket::MediaDescriptionOptions(
1959 cricket::MEDIA_TYPE_DATA, content.name,
1960 cricket::RtpTransceiverDirection(false, false), true));
1961 } else {
1962 session_options->media_description_options.push_back(
1963 cricket::MediaDescriptionOptions(
1964 cricket::MEDIA_TYPE_DATA, content.name,
1965 // Direction for data sections is meaningless, but legacy
1966 // endpoints might expect sendrecv.
1967 cricket::RtpTransceiverDirection(true, true), false));
1968 *data_index = rtc::Optional<size_t>(
1969 session_options->media_description_options.size() - 1);
1970 }
1971 }
htaa2a49d92016-03-04 02:51:39 -08001972 }
deadbeefab9b2d12015-10-14 11:33:11 -07001973}
1974
deadbeeffaac4972015-11-12 15:33:07 -08001975void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1976 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001977 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1978 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001979}
1980
deadbeefab9b2d12015-10-14 11:33:11 -07001981void PeerConnection::UpdateRemoteStreamsList(
1982 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001983 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001984 cricket::MediaType media_type,
1985 StreamCollection* new_streams) {
1986 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1987
1988 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001989 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001990 auto track_it = current_tracks->begin();
1991 while (track_it != current_tracks->end()) {
1992 const TrackInfo& info = *track_it;
1993 const cricket::StreamParams* params =
1994 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001995 bool track_exists = params && params->id == info.track_id;
1996 // If this is a default track, and we still need it, don't remove it.
1997 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1998 track_exists) {
1999 ++track_it;
2000 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07002001 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
2002 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002003 }
2004 }
2005
2006 // Find new and active tracks.
2007 for (const cricket::StreamParams& params : streams) {
2008 // The sync_label is the MediaStream label and the |stream.id| is the
2009 // track id.
2010 const std::string& stream_label = params.sync_label;
2011 const std::string& track_id = params.id;
2012 uint32_t ssrc = params.first_ssrc();
2013
2014 rtc::scoped_refptr<MediaStreamInterface> stream =
2015 remote_streams_->find(stream_label);
2016 if (!stream) {
2017 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002018 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2019 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002020 remote_streams_->AddStream(stream);
2021 new_streams->AddStream(stream);
2022 }
2023
2024 const TrackInfo* track_info =
2025 FindTrackInfo(*current_tracks, stream_label, track_id);
2026 if (!track_info) {
2027 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2028 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2029 }
2030 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002031
2032 // Add default track if necessary.
2033 if (default_track_needed) {
2034 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2035 remote_streams_->find(kDefaultStreamLabel);
2036 if (!default_stream) {
2037 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002038 default_stream = MediaStreamProxy::Create(
2039 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002040 remote_streams_->AddStream(default_stream);
2041 new_streams->AddStream(default_stream);
2042 }
2043 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2044 ? kDefaultAudioTrackLabel
2045 : kDefaultVideoTrackLabel;
2046 const TrackInfo* default_track_info =
2047 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2048 if (!default_track_info) {
2049 current_tracks->push_back(
2050 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2051 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2052 }
2053 }
deadbeefab9b2d12015-10-14 11:33:11 -07002054}
2055
2056void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2057 const std::string& track_id,
2058 uint32_t ssrc,
2059 cricket::MediaType media_type) {
2060 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2061
2062 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002063 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002064 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002065 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002066 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002067 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002068 }
2069}
2070
2071void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2072 const std::string& track_id,
2073 cricket::MediaType media_type) {
2074 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2075
Henrik Boström933d8b02017-10-10 10:05:16 -07002076 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002077 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002078 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2079 // will be notified which will end the AudioRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002080 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002081 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2082 stream->FindAudioTrack(track_id);
2083 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002084 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002085 }
2086 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002087 // Stopping or destroying a VideoRtpReceiver will end the
2088 // VideoRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002089 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002090 rtc::scoped_refptr<VideoTrackInterface> video_track =
2091 stream->FindVideoTrack(track_id);
2092 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002093 // There's no guarantee the track is still available, e.g. the track may
2094 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002095 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002096 }
2097 } else {
nisseede5da42017-01-12 05:15:36 -08002098 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002099 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002100 if (receiver) {
2101 observer_->OnRemoveTrack(receiver);
2102 }
deadbeefab9b2d12015-10-14 11:33:11 -07002103}
2104
2105void PeerConnection::UpdateEndedRemoteMediaStreams() {
2106 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2107 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2108 MediaStreamInterface* stream = remote_streams_->at(i);
2109 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2110 streams_to_remove.push_back(stream);
2111 }
2112 }
2113
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002114 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002115 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002116 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002117 }
2118}
2119
deadbeefab9b2d12015-10-14 11:33:11 -07002120void PeerConnection::UpdateLocalTracks(
2121 const std::vector<cricket::StreamParams>& streams,
2122 cricket::MediaType media_type) {
2123 TrackInfos* current_tracks = GetLocalTracks(media_type);
2124
2125 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2126 // don't match the new StreamParam.
2127 TrackInfos::iterator track_it = current_tracks->begin();
2128 while (track_it != current_tracks->end()) {
2129 const TrackInfo& info = *track_it;
2130 const cricket::StreamParams* params =
2131 cricket::GetStreamBySsrc(streams, info.ssrc);
2132 if (!params || params->id != info.track_id ||
2133 params->sync_label != info.stream_label) {
2134 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2135 media_type);
2136 track_it = current_tracks->erase(track_it);
2137 } else {
2138 ++track_it;
2139 }
2140 }
2141
2142 // Find new and active tracks.
2143 for (const cricket::StreamParams& params : streams) {
2144 // The sync_label is the MediaStream label and the |stream.id| is the
2145 // track id.
2146 const std::string& stream_label = params.sync_label;
2147 const std::string& track_id = params.id;
2148 uint32_t ssrc = params.first_ssrc();
2149 const TrackInfo* track_info =
2150 FindTrackInfo(*current_tracks, stream_label, track_id);
2151 if (!track_info) {
2152 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2153 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2154 }
2155 }
2156}
2157
2158void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2159 const std::string& track_id,
2160 uint32_t ssrc,
2161 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002162 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002163 if (!sender) {
2164 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2165 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002166 return;
2167 }
2168
deadbeeffac06552015-11-25 11:26:01 -08002169 if (sender->media_type() != media_type) {
2170 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2171 << " description with an unexpected media type.";
2172 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002173 }
deadbeeffac06552015-11-25 11:26:01 -08002174
2175 sender->set_stream_id(stream_label);
2176 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002177}
2178
2179void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2180 const std::string& track_id,
2181 uint32_t ssrc,
2182 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002183 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002184 if (!sender) {
2185 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002186 // SessionDescriptions has been renegotiated.
2187 return;
2188 }
deadbeeffac06552015-11-25 11:26:01 -08002189
2190 // A sender has been removed from the SessionDescription but it's still
2191 // associated with the PeerConnection. This only occurs if the SDP doesn't
2192 // match with the calls to CreateSender, AddStream and RemoveStream.
2193 if (sender->media_type() != media_type) {
2194 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2195 << " description with an unexpected media type.";
2196 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002197 }
deadbeeffac06552015-11-25 11:26:01 -08002198
2199 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002200}
2201
2202void PeerConnection::UpdateLocalRtpDataChannels(
2203 const cricket::StreamParamsVec& streams) {
2204 std::vector<std::string> existing_channels;
2205
2206 // Find new and active data channels.
2207 for (const cricket::StreamParams& params : streams) {
2208 // |it->sync_label| is actually the data channel label. The reason is that
2209 // we use the same naming of data channels as we do for
2210 // MediaStreams and Tracks.
2211 // For MediaStreams, the sync_label is the MediaStream label and the
2212 // track label is the same as |streamid|.
2213 const std::string& channel_label = params.sync_label;
2214 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002215 if (data_channel_it == rtp_data_channels_.end()) {
2216 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002217 continue;
2218 }
2219 // Set the SSRC the data channel should use for sending.
2220 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2221 existing_channels.push_back(data_channel_it->first);
2222 }
2223
2224 UpdateClosingRtpDataChannels(existing_channels, true);
2225}
2226
2227void PeerConnection::UpdateRemoteRtpDataChannels(
2228 const cricket::StreamParamsVec& streams) {
2229 std::vector<std::string> existing_channels;
2230
2231 // Find new and active data channels.
2232 for (const cricket::StreamParams& params : streams) {
2233 // The data channel label is either the mslabel or the SSRC if the mslabel
2234 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2235 std::string label = params.sync_label.empty()
2236 ? rtc::ToString(params.first_ssrc())
2237 : params.sync_label;
2238 auto data_channel_it = rtp_data_channels_.find(label);
2239 if (data_channel_it == rtp_data_channels_.end()) {
2240 // This is a new data channel.
2241 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2242 } else {
2243 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2244 }
2245 existing_channels.push_back(label);
2246 }
2247
2248 UpdateClosingRtpDataChannels(existing_channels, false);
2249}
2250
2251void PeerConnection::UpdateClosingRtpDataChannels(
2252 const std::vector<std::string>& active_channels,
2253 bool is_local_update) {
2254 auto it = rtp_data_channels_.begin();
2255 while (it != rtp_data_channels_.end()) {
2256 DataChannel* data_channel = it->second;
2257 if (std::find(active_channels.begin(), active_channels.end(),
2258 data_channel->label()) != active_channels.end()) {
2259 ++it;
2260 continue;
2261 }
2262
2263 if (is_local_update) {
2264 data_channel->SetSendSsrc(0);
2265 } else {
2266 data_channel->RemotePeerRequestClose();
2267 }
2268
2269 if (data_channel->state() == DataChannel::kClosed) {
2270 rtp_data_channels_.erase(it);
2271 it = rtp_data_channels_.begin();
2272 } else {
2273 ++it;
2274 }
2275 }
2276}
2277
2278void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2279 uint32_t remote_ssrc) {
2280 rtc::scoped_refptr<DataChannel> channel(
2281 InternalCreateDataChannel(label, nullptr));
2282 if (!channel.get()) {
2283 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2284 << "CreateDataChannel failed.";
2285 return;
2286 }
2287 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002288 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2289 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002290 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002291}
2292
2293rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2294 const std::string& label,
2295 const InternalDataChannelInit* config) {
2296 if (IsClosed()) {
2297 return nullptr;
2298 }
2299 if (session_->data_channel_type() == cricket::DCT_NONE) {
2300 LOG(LS_ERROR)
2301 << "InternalCreateDataChannel: Data is not supported in this call.";
2302 return nullptr;
2303 }
2304 InternalDataChannelInit new_config =
2305 config ? (*config) : InternalDataChannelInit();
2306 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2307 if (new_config.id < 0) {
2308 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002309 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002310 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2311 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2312 return nullptr;
2313 }
2314 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2315 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2316 << "because the id is already in use or out of range.";
2317 return nullptr;
2318 }
2319 }
2320
2321 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
Steve Anton978b8762017-09-29 12:15:02 -07002322 session_, session_->data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002323 if (!channel) {
2324 sid_allocator_.ReleaseSid(new_config.id);
2325 return nullptr;
2326 }
2327
2328 if (channel->data_channel_type() == cricket::DCT_RTP) {
2329 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2330 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2331 << " already exists.";
2332 return nullptr;
2333 }
2334 rtp_data_channels_[channel->label()] = channel;
2335 } else {
2336 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2337 sctp_data_channels_.push_back(channel);
2338 channel->SignalClosed.connect(this,
2339 &PeerConnection::OnSctpDataChannelClosed);
2340 }
2341
hbos82ebe022016-11-14 01:41:09 -08002342 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002343 return channel;
2344}
2345
2346bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002347#ifdef HAVE_QUIC
2348 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2349 (session_->quic_data_transport() &&
2350 session_->quic_data_transport()->HasDataChannels());
2351#else
deadbeefab9b2d12015-10-14 11:33:11 -07002352 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002353#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002354}
2355
2356void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2357 for (const auto& channel : sctp_data_channels_) {
2358 if (channel->id() < 0) {
2359 int sid;
2360 if (!sid_allocator_.AllocateSid(role, &sid)) {
2361 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2362 continue;
2363 }
2364 channel->SetSctpSid(sid);
2365 }
2366 }
2367}
2368
2369void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002370 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002371 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2372 ++it) {
2373 if (it->get() == channel) {
2374 if (channel->id() >= 0) {
2375 sid_allocator_.ReleaseSid(channel->id());
2376 }
deadbeefbd292462015-12-14 18:15:29 -08002377 // Since this method is triggered by a signal from the DataChannel,
2378 // we can't free it directly here; we need to free it asynchronously.
2379 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002380 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002381 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2382 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002383 return;
2384 }
2385 }
2386}
2387
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002388void PeerConnection::OnVoiceChannelCreated() {
2389 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2390 session_->voice_channel(), senders_, receivers_,
2391 cricket::MEDIA_TYPE_AUDIO);
2392}
2393
deadbeefab9b2d12015-10-14 11:33:11 -07002394void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002395 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2396 cricket::VoiceChannel>(
2397 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2398}
2399
2400void PeerConnection::OnVideoChannelCreated() {
2401 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2402 session_->video_channel(), senders_, receivers_,
2403 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002404}
2405
2406void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002407 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2408 cricket::VideoChannel>(
2409 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002410}
2411
2412void PeerConnection::OnDataChannelCreated() {
2413 for (const auto& channel : sctp_data_channels_) {
2414 channel->OnTransportChannelCreated();
2415 }
2416}
2417
2418void PeerConnection::OnDataChannelDestroyed() {
2419 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2420 // DataChannel may callback to us and try to modify the list.
2421 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2422 temp_rtp_dcs.swap(rtp_data_channels_);
2423 for (const auto& kv : temp_rtp_dcs) {
2424 kv.second->OnTransportChannelDestroyed();
2425 }
2426
2427 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2428 temp_sctp_dcs.swap(sctp_data_channels_);
2429 for (const auto& channel : temp_sctp_dcs) {
2430 channel->OnTransportChannelDestroyed();
2431 }
2432}
2433
2434void PeerConnection::OnDataChannelOpenMessage(
2435 const std::string& label,
2436 const InternalDataChannelInit& config) {
2437 rtc::scoped_refptr<DataChannel> channel(
2438 InternalCreateDataChannel(label, &config));
2439 if (!channel.get()) {
2440 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2441 return;
2442 }
2443
deadbeefa601f5c2016-06-06 14:27:39 -07002444 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2445 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002446 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002447}
2448
zhihuang1c378ed2017-08-17 14:10:50 -07002449bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2450 return std::find_if(
2451 senders_.begin(), senders_.end(),
2452 [type](const rtc::scoped_refptr<
2453 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2454 return sender->media_type() == type;
2455 }) != senders_.end();
2456}
2457
deadbeefa601f5c2016-06-06 14:27:39 -07002458RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2459 auto it = std::find_if(
2460 senders_.begin(), senders_.end(),
2461 [id](const rtc::scoped_refptr<
2462 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2463 return sender->id() == id;
2464 });
2465 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002466}
2467
deadbeefa601f5c2016-06-06 14:27:39 -07002468std::vector<
2469 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002470PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2471 return std::find_if(
2472 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002473 [track](const rtc::scoped_refptr<
2474 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002475 return sender->track() == track;
2476 });
2477}
2478
deadbeefa601f5c2016-06-06 14:27:39 -07002479std::vector<rtc::scoped_refptr<
2480 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002481PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002482 return std::find_if(
2483 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002484 [track_id](const rtc::scoped_refptr<
2485 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002486 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002487 });
2488}
2489
deadbeefab9b2d12015-10-14 11:33:11 -07002490PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2491 cricket::MediaType media_type) {
2492 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2493 media_type == cricket::MEDIA_TYPE_VIDEO);
2494 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2495 : &remote_video_tracks_;
2496}
2497
2498PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2499 cricket::MediaType media_type) {
2500 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2501 media_type == cricket::MEDIA_TYPE_VIDEO);
2502 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2503 : &local_video_tracks_;
2504}
2505
2506const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2507 const PeerConnection::TrackInfos& infos,
2508 const std::string& stream_label,
2509 const std::string track_id) const {
2510 for (const TrackInfo& track_info : infos) {
2511 if (track_info.stream_label == stream_label &&
2512 track_info.track_id == track_id) {
2513 return &track_info;
2514 }
2515 }
2516 return nullptr;
2517}
2518
2519DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2520 for (const auto& channel : sctp_data_channels_) {
2521 if (channel->id() == sid) {
2522 return channel;
2523 }
2524 }
2525 return nullptr;
2526}
2527
deadbeef91dd5672016-05-18 16:55:30 -07002528bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002529 const RTCConfiguration& configuration) {
2530 cricket::ServerAddresses stun_servers;
2531 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002532 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2533 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002534 return false;
2535 }
2536
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002537 port_allocator_->Initialize();
2538
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002539 // To handle both internal and externally created port allocator, we will
2540 // enable BUNDLE here.
2541 int portallocator_flags = port_allocator_->flags();
2542 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002543 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2544 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002545 // If the disable-IPv6 flag was specified, we'll not override it
2546 // by experiment.
2547 if (configuration.disable_ipv6) {
2548 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002549 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2550 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002551 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2552 }
2553
zhihuangb09b3f92017-03-07 14:40:51 -08002554 if (configuration.disable_ipv6_on_wifi) {
2555 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2556 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2557 }
2558
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002559 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2560 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2561 LOG(LS_INFO) << "TCP candidates are disabled.";
2562 }
2563
honghaiz60347052016-05-31 18:29:12 -07002564 if (configuration.candidate_network_policy ==
2565 kCandidateNetworkPolicyLowCost) {
2566 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2567 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2568 }
2569
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002570 port_allocator_->set_flags(portallocator_flags);
2571 // No step delay is used while allocating ports.
2572 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2573 port_allocator_->set_candidate_filter(
2574 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002575 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002576
2577 // Call this last since it may create pooled allocator sessions using the
2578 // properties set above.
2579 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002580 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002581 configuration.prune_turn_ports,
2582 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002583 return true;
2584}
2585
deadbeef91dd5672016-05-18 16:55:30 -07002586bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002587 const cricket::ServerAddresses& stun_servers,
2588 const std::vector<cricket::RelayServerConfig>& turn_servers,
2589 IceTransportsType type,
2590 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002591 bool prune_turn_ports,
2592 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002593 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002594 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002595 // Call this last since it may create pooled allocator sessions using the
2596 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002597 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02002598 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
2599 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002600}
2601
Elad Alon99c3fe52017-10-13 16:29:40 +02002602bool PeerConnection::StartRtcEventLog_w(
2603 std::unique_ptr<RtcEventLogOutput> output) {
zhihuang77985012017-02-07 15:45:16 -08002604 if (!event_log_) {
2605 return false;
2606 }
Elad Alon99c3fe52017-10-13 16:29:40 +02002607 return event_log_->StartLogging(std::move(output));
ivoc14d5dbe2016-07-04 07:06:55 -07002608}
2609
2610void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002611 if (event_log_) {
2612 event_log_->StopLogging();
2613 }
ivoc14d5dbe2016-07-04 07:06:55 -07002614}
nisseeaabdf62017-05-05 02:23:02 -07002615
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616} // namespace webrtc