blob: e8e428dd4f3c1f1aae1db83b8010219f1af630fa [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;
deadbeef293e9262017-01-11 12:28:30 -0800280 };
281 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
282 "Did you add something to RTCConfiguration and forget to "
283 "update operator==?");
284 return type == o.type && servers == o.servers &&
285 bundle_policy == o.bundle_policy &&
286 rtcp_mux_policy == o.rtcp_mux_policy &&
287 tcp_candidate_policy == o.tcp_candidate_policy &&
288 candidate_network_policy == o.candidate_network_policy &&
289 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
290 audio_jitter_buffer_fast_accelerate ==
291 o.audio_jitter_buffer_fast_accelerate &&
292 ice_connection_receiving_timeout ==
293 o.ice_connection_receiving_timeout &&
294 ice_backup_candidate_pair_ping_interval ==
295 o.ice_backup_candidate_pair_ping_interval &&
296 continual_gathering_policy == o.continual_gathering_policy &&
297 certificates == o.certificates &&
298 prioritize_most_likely_ice_candidate_pairs ==
299 o.prioritize_most_likely_ice_candidate_pairs &&
300 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800301 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700302 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800303 enable_rtp_data_channel == o.enable_rtp_data_channel &&
304 enable_quic == o.enable_quic &&
305 screencast_min_bitrate == o.screencast_min_bitrate &&
306 combined_audio_video_bwe == o.combined_audio_video_bwe &&
307 enable_dtls_srtp == o.enable_dtls_srtp &&
308 ice_candidate_pool_size == o.ice_candidate_pool_size &&
309 prune_turn_ports == o.prune_turn_ports &&
310 presume_writable_when_fully_relayed ==
311 o.presume_writable_when_fully_relayed &&
312 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800313 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700314 ice_check_min_interval == o.ice_check_min_interval &&
Guido Urdaneta604427b2017-10-09 09:53:49 +0000315 ice_regather_interval_range == o.ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800316}
317
318bool PeerConnectionInterface::RTCConfiguration::operator!=(
319 const PeerConnectionInterface::RTCConfiguration& o) const {
320 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800321}
322
zhihuang8f65cdf2016-05-06 18:40:30 -0700323// Generate a RTCP CNAME when a PeerConnection is created.
324std::string GenerateRtcpCname() {
325 std::string cname;
326 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
327 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800328 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700329 }
330 return cname;
331}
332
zhihuang1c378ed2017-08-17 14:10:50 -0700333bool ValidateOfferAnswerOptions(
334 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
335 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
336 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700337}
338
zhihuang1c378ed2017-08-17 14:10:50 -0700339// From |rtc_options|, fill parts of |session_options| shared by all generated
340// m= sections (in other words, nothing that involves a map/array).
341void ExtractSharedMediaSessionOptions(
342 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
343 cricket::MediaSessionOptions* session_options) {
344 session_options->vad_enabled = rtc_options.voice_activity_detection;
345 session_options->bundle_enabled = rtc_options.use_rtp_mux;
346}
zhihuanga77e6bb2017-08-14 18:17:48 -0700347
zhihuang1c378ed2017-08-17 14:10:50 -0700348bool ConvertConstraintsToOfferAnswerOptions(
349 const MediaConstraintsInterface* constraints,
350 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700351 if (!constraints) {
352 return true;
353 }
zhihuang1c378ed2017-08-17 14:10:50 -0700354
355 bool value = false;
356 size_t mandatory_constraints_satisfied = 0;
357
358 if (FindConstraint(constraints,
359 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
360 &mandatory_constraints_satisfied)) {
361 offer_answer_options->offer_to_receive_audio =
362 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
363 kOfferToReceiveMediaTrue
364 : 0;
365 }
366
367 if (FindConstraint(constraints,
368 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
369 &mandatory_constraints_satisfied)) {
370 offer_answer_options->offer_to_receive_video =
371 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
372 kOfferToReceiveMediaTrue
373 : 0;
374 }
375 if (FindConstraint(constraints,
376 MediaConstraintsInterface::kVoiceActivityDetection, &value,
377 &mandatory_constraints_satisfied)) {
378 offer_answer_options->voice_activity_detection = value;
379 }
380 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
381 &mandatory_constraints_satisfied)) {
382 offer_answer_options->use_rtp_mux = value;
383 }
384 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
385 &value, &mandatory_constraints_satisfied)) {
386 offer_answer_options->ice_restart = value;
387 }
388
deadbeefab9b2d12015-10-14 11:33:11 -0700389 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
390}
391
zhihuang38ede132017-06-15 12:52:32 -0700392PeerConnection::PeerConnection(PeerConnectionFactory* factory,
393 std::unique_ptr<RtcEventLog> event_log,
394 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000395 : factory_(factory),
396 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000397 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700398 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000399 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700401 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700402 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700403 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700404 remote_streams_(StreamCollection::Create()),
405 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000406
407PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100408 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700409 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700410 // Need to detach RTP senders/receivers from WebRtcSession,
411 // since it's about to be destroyed.
412 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700413 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700414 }
415 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700416 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700417 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700418 // Destroy stats_ because it depends on session_.
419 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800420 if (stats_collector_) {
421 stats_collector_->WaitForPendingRequest();
422 stats_collector_ = nullptr;
423 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700424 // Now destroy session_ before destroying other members,
425 // because its destruction fires signals (such as VoiceChannelDestroyed)
426 // which will trigger some final actions in PeerConnection...
Steve Anton978b8762017-09-29 12:15:02 -0700427 owned_session_.reset(nullptr);
428 session_ = nullptr;
deadbeef91dd5672016-05-18 16:55:30 -0700429 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700430 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700431 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700432 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700433 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700434 call_.reset();
435 event_log_.reset();
436 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000437}
438
439bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000440 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700441 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200442 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800443 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100444 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700445
446 RTCError config_error = ValidateConfiguration(configuration);
447 if (!config_error.ok()) {
448 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
449 return false;
450 }
451
deadbeef293e9262017-01-11 12:28:30 -0800452 if (!allocator) {
453 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
454 << "This shouldn't happen if using PeerConnectionFactory.";
455 return false;
456 }
deadbeef653b8e02015-11-11 12:55:10 -0800457 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800458 // TODO(deadbeef): Why do we do this?
459 LOG(LS_ERROR) << "PeerConnection initialized without a "
460 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800461 return false;
462 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000463 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800464 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800465
deadbeef91dd5672016-05-18 16:55:30 -0700466 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700467 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700468 if (!network_thread()->Invoke<bool>(
469 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
470 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000471 return false;
472 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000473
Steve Anton978b8762017-09-29 12:15:02 -0700474 owned_session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700475 call_.get(), factory_->channel_manager(), configuration.media_config,
Steve Anton978b8762017-09-29 12:15:02 -0700476 event_log_.get(), network_thread(), worker_thread(), signaling_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700477 port_allocator_.get(),
478 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700479 factory_->CreateTransportController(
480 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800481 configuration.redetermine_role_on_ice_restart)),
482#ifdef HAVE_SCTP
483 std::unique_ptr<cricket::SctpTransportInternalFactory>(
Steve Anton978b8762017-09-29 12:15:02 -0700484 new cricket::SctpTransportFactory(network_thread()))
deadbeef953c2ce2017-01-09 14:53:41 -0800485#else
486 nullptr
487#endif
488 ));
Steve Anton978b8762017-09-29 12:15:02 -0700489 session_ = owned_session_.get();
zhihuang29ff8442016-07-27 11:07:25 -0700490
deadbeefab9b2d12015-10-14 11:33:11 -0700491 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700492 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493
494 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200495 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800496 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700498 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000499
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000500 // Register PeerConnection as receiver of local ice candidates.
501 // All the callbacks will be posted to the application from PeerConnection.
502 session_->RegisterIceObserver(this);
503 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700504 session_->SignalVoiceChannelCreated.connect(
505 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700506 session_->SignalVoiceChannelDestroyed.connect(
507 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700508 session_->SignalVideoChannelCreated.connect(
509 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700510 session_->SignalVideoChannelDestroyed.connect(
511 this, &PeerConnection::OnVideoChannelDestroyed);
512 session_->SignalDataChannelCreated.connect(
513 this, &PeerConnection::OnDataChannelCreated);
514 session_->SignalDataChannelDestroyed.connect(
515 this, &PeerConnection::OnDataChannelDestroyed);
516 session_->SignalDataChannelOpenMessage.connect(
517 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800518
519 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000520 return true;
521}
522
Steve Anton038834f2017-07-14 15:59:59 -0700523RTCError PeerConnection::ValidateConfiguration(
524 const RTCConfiguration& config) const {
525 if (config.ice_regather_interval_range &&
526 config.continual_gathering_policy == GATHER_ONCE) {
527 return RTCError(RTCErrorType::INVALID_PARAMETER,
528 "ice_regather_interval_range specified but continual "
529 "gathering policy is GATHER_ONCE");
530 }
531 return RTCError::OK();
532}
533
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000534rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000535PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700536 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000537}
538
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000539rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700541 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000542}
543
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000544bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100545 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000546 if (IsClosed()) {
547 return false;
548 }
deadbeefab9b2d12015-10-14 11:33:11 -0700549 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000550 return false;
551 }
deadbeefab9b2d12015-10-14 11:33:11 -0700552
553 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800554 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
555 observer->SignalAudioTrackAdded.connect(this,
556 &PeerConnection::OnAudioTrackAdded);
557 observer->SignalAudioTrackRemoved.connect(
558 this, &PeerConnection::OnAudioTrackRemoved);
559 observer->SignalVideoTrackAdded.connect(this,
560 &PeerConnection::OnVideoTrackAdded);
561 observer->SignalVideoTrackRemoved.connect(
562 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700563 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700564
deadbeefab9b2d12015-10-14 11:33:11 -0700565 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700566 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700567 }
568 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700569 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700570 }
571
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000572 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573 observer_->OnRenegotiationNeeded();
574 return true;
575}
576
577void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100578 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700579 if (!IsClosed()) {
580 for (const auto& track : local_stream->GetAudioTracks()) {
581 RemoveAudioTrack(track.get(), local_stream);
582 }
583 for (const auto& track : local_stream->GetVideoTracks()) {
584 RemoveVideoTrack(track.get(), local_stream);
585 }
deadbeefab9b2d12015-10-14 11:33:11 -0700586 }
deadbeefab9b2d12015-10-14 11:33:11 -0700587 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800588 stream_observers_.erase(
589 std::remove_if(
590 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700591 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800592 return observer->stream()->label().compare(local_stream->label()) ==
593 0;
594 }),
595 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700596
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597 if (IsClosed()) {
598 return;
599 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000600 observer_->OnRenegotiationNeeded();
601}
602
deadbeefe1f9d832016-01-14 15:35:42 -0800603rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
604 MediaStreamTrackInterface* track,
605 std::vector<MediaStreamInterface*> streams) {
606 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
607 if (IsClosed()) {
608 return nullptr;
609 }
610 if (streams.size() >= 2) {
611 LOG(LS_ERROR)
612 << "Adding a track with two streams is not currently supported.";
613 return nullptr;
614 }
615 // TODO(deadbeef): Support adding a track to two different senders.
616 if (FindSenderForTrack(track) != senders_.end()) {
617 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
618 return nullptr;
619 }
620
621 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700622 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800623 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700624 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800625 signaling_thread(),
626 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700627 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800628 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700629 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800630 }
631 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700632 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800633 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700634 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800635 }
636 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700637 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800638 signaling_thread(),
639 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700640 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800641 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700642 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800643 }
644 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700645 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800646 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700647 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800648 }
649 } else {
650 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
651 return rtc::scoped_refptr<RtpSenderInterface>();
652 }
653
654 senders_.push_back(new_sender);
655 observer_->OnRenegotiationNeeded();
656 return new_sender;
657}
658
659bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
660 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
661 if (IsClosed()) {
662 return false;
663 }
664
665 auto it = std::find(senders_.begin(), senders_.end(), sender);
666 if (it == senders_.end()) {
667 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
668 return false;
669 }
deadbeefa601f5c2016-06-06 14:27:39 -0700670 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800671 senders_.erase(it);
672
673 observer_->OnRenegotiationNeeded();
674 return true;
675}
676
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000677rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100679 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700680 if (IsClosed()) {
681 return nullptr;
682 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683 if (!track) {
684 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800685 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000686 }
deadbeef20cb0c12017-02-01 20:27:00 -0800687 auto it = FindSenderForTrack(track);
688 if (it == senders_.end()) {
689 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
690 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691 }
692
deadbeef20cb0c12017-02-01 20:27:00 -0800693 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000694}
695
deadbeeffac06552015-11-25 11:26:01 -0800696rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800697 const std::string& kind,
698 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100699 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700700 if (IsClosed()) {
701 return nullptr;
702 }
deadbeefa601f5c2016-06-06 14:27:39 -0700703 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800704 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700705 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700706 signaling_thread(),
707 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800708 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700709 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700710 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800711 } else {
712 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800713 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800714 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800715 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700716 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800717 }
deadbeeffac06552015-11-25 11:26:01 -0800718 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800719 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800720}
721
deadbeef70ab1a12015-09-28 16:53:55 -0700722std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
723 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700724 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
725 for (const auto& sender : senders_) {
726 ret.push_back(sender.get());
727 }
728 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700729}
730
731std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
732PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700733 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
734 for (const auto& receiver : receivers_) {
735 ret.push_back(receiver.get());
736 }
737 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700738}
739
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000741 MediaStreamTrackInterface* track,
742 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100743 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700744 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800745 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746 LOG(LS_ERROR) << "GetStats - observer is NULL.";
747 return false;
748 }
749
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000750 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700751 // The StatsCollector is used to tell if a track is valid because it may
752 // remember tracks that the PeerConnection previously removed.
753 if (track && !stats_->IsValidTrack(track->id())) {
754 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
755 << track->id();
756 return false;
757 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700758 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000759 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000760 return true;
761}
762
hbos74e1a4f2016-09-15 23:33:01 -0700763void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
764 RTC_DCHECK(stats_collector_);
765 stats_collector_->GetStatsReport(callback);
766}
767
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000768PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
769 return signaling_state_;
770}
771
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000772PeerConnectionInterface::IceConnectionState
773PeerConnection::ice_connection_state() {
774 return ice_connection_state_;
775}
776
777PeerConnectionInterface::IceGatheringState
778PeerConnection::ice_gathering_state() {
779 return ice_gathering_state_;
780}
781
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000782rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783PeerConnection::CreateDataChannel(
784 const std::string& label,
785 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100786 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700787#ifdef HAVE_QUIC
788 if (session_->data_channel_type() == cricket::DCT_QUIC) {
789 // TODO(zhihuang): Handle case when config is NULL.
790 if (!config) {
791 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
792 return nullptr;
793 }
794 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
795 if (!config->reliable || config->ordered) {
796 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
797 "ordered delivery.";
798 return nullptr;
799 }
800 return session_->quic_data_transport()->CreateDataChannel(label, config);
801 }
802#endif // HAVE_QUIC
803
deadbeefab9b2d12015-10-14 11:33:11 -0700804 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000805
kwibergd1fe2812016-04-27 06:47:29 -0700806 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000807 if (config) {
808 internal_config.reset(new InternalDataChannelInit(*config));
809 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000810 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700811 InternalCreateDataChannel(label, internal_config.get()));
812 if (!channel.get()) {
813 return nullptr;
814 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000815
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000816 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
817 // the first SCTP DataChannel.
818 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
819 observer_->OnRenegotiationNeeded();
820 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000821
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 return DataChannelProxy::Create(signaling_thread(), channel.get());
823}
824
825void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
826 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100827 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800828 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
830 return;
831 }
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");
nisse7ce109a2017-01-31 00:57:56 -0800848 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000849 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
850 return;
851 }
deadbeefab9b2d12015-10-14 11:33:11 -0700852
zhihuang1c378ed2017-08-17 14:10:50 -0700853 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700854 std::string error = "CreateOffer called with invalid options.";
855 LOG(LS_ERROR) << error;
856 PostCreateSessionDescriptionFailure(observer, error);
857 return;
858 }
859
zhihuang1c378ed2017-08-17 14:10:50 -0700860 cricket::MediaSessionOptions session_options;
861 GetOptionsForOffer(options, &session_options);
deadbeefab9b2d12015-10-14 11:33:11 -0700862 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000863}
864
865void PeerConnection::CreateAnswer(
866 CreateSessionDescriptionObserver* observer,
867 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100868 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800869 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
871 return;
872 }
deadbeefab9b2d12015-10-14 11:33:11 -0700873
zhihuang1c378ed2017-08-17 14:10:50 -0700874 if (!session_->remote_description() ||
875 session_->remote_description()->type() !=
876 SessionDescriptionInterface::kOffer) {
877 std::string error = "CreateAnswer called without remote offer.";
878 LOG(LS_ERROR) << error;
879 PostCreateSessionDescriptionFailure(observer, error);
880 return;
881 }
882
883 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
zhihuang1c378ed2017-08-17 14:10:50 -0700892 cricket::MediaSessionOptions session_options;
893 GetOptionsForAnswer(offer_answer_options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800894 session_->CreateAnswer(observer, session_options);
895}
896
897void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
898 const RTCOfferAnswerOptions& options) {
899 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800900 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800901 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
902 return;
903 }
904
905 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -0700906 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800907
908 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909}
910
911void PeerConnection::SetLocalDescription(
912 SetSessionDescriptionObserver* observer,
913 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100914 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700915 if (IsClosed()) {
916 return;
917 }
nisse7ce109a2017-01-31 00:57:56 -0800918 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
920 return;
921 }
922 if (!desc) {
923 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
924 return;
925 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926 // Update stats here so that we have the most recent stats for tracks and
927 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000928 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929 std::string error;
930 if (!session_->SetLocalDescription(desc, &error)) {
931 PostSetSessionDescriptionFailure(observer, error);
932 return;
933 }
deadbeefab9b2d12015-10-14 11:33:11 -0700934
935 // If setting the description decided our SSL role, allocate any necessary
936 // SCTP sids.
937 rtc::SSLRole role;
938 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800939 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700940 AllocateSctpSids(role);
941 }
942
943 // Update state and SSRC of local MediaStreams and DataChannels based on the
944 // local session description.
945 const cricket::ContentInfo* audio_content =
946 GetFirstAudioContent(desc->description());
947 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800948 if (audio_content->rejected) {
949 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
950 } else {
951 const cricket::AudioContentDescription* audio_desc =
952 static_cast<const cricket::AudioContentDescription*>(
953 audio_content->description);
954 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
955 }
deadbeefab9b2d12015-10-14 11:33:11 -0700956 }
957
958 const cricket::ContentInfo* video_content =
959 GetFirstVideoContent(desc->description());
960 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800961 if (video_content->rejected) {
962 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
963 } else {
964 const cricket::VideoContentDescription* video_desc =
965 static_cast<const cricket::VideoContentDescription*>(
966 video_content->description);
967 UpdateLocalTracks(video_desc->streams(), video_desc->type());
968 }
deadbeefab9b2d12015-10-14 11:33:11 -0700969 }
970
971 const cricket::ContentInfo* data_content =
972 GetFirstDataContent(desc->description());
973 if (data_content) {
974 const cricket::DataContentDescription* data_desc =
975 static_cast<const cricket::DataContentDescription*>(
976 data_content->description);
977 if (rtc::starts_with(data_desc->protocol().data(),
978 cricket::kMediaProtocolRtpPrefix)) {
979 UpdateLocalRtpDataChannels(data_desc->streams());
980 }
981 }
982
983 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700984 signaling_thread()->Post(RTC_FROM_HERE, this,
985 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700986
deadbeef42a42632017-03-10 15:18:00 -0800987 // According to JSEP, after setLocalDescription, changing the candidate pool
988 // size is not allowed, and changing the set of ICE servers will not result
989 // in new candidates being gathered.
990 port_allocator_->FreezeCandidatePool();
991
deadbeefcbecd352015-09-23 11:50:27 -0700992 // MaybeStartGathering needs to be called after posting
993 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
994 // before signaling that SetLocalDescription completed.
995 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -0800996
997 if (desc->type() == SessionDescriptionInterface::kAnswer) {
998 // TODO(deadbeef): We already had to hop to the network thread for
999 // MaybeStartGathering...
1000 network_thread()->Invoke<void>(
1001 RTC_FROM_HERE,
1002 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1003 port_allocator_.get()));
1004 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005}
1006
1007void PeerConnection::SetRemoteDescription(
1008 SetSessionDescriptionObserver* observer,
1009 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001010 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001011 if (IsClosed()) {
1012 return;
1013 }
nisse7ce109a2017-01-31 00:57:56 -08001014 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1016 return;
1017 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018 if (!desc) {
1019 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1020 return;
1021 }
1022 // Update stats here so that we have the most recent stats for tracks and
1023 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001024 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025 std::string error;
1026 if (!session_->SetRemoteDescription(desc, &error)) {
1027 PostSetSessionDescriptionFailure(observer, error);
1028 return;
1029 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030
deadbeefab9b2d12015-10-14 11:33:11 -07001031 // If setting the description decided our SSL role, allocate any necessary
1032 // SCTP sids.
1033 rtc::SSLRole role;
1034 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001035 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001036 AllocateSctpSids(role);
1037 }
1038
1039 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001040 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1041 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1042 const cricket::AudioContentDescription* audio_desc =
1043 GetFirstAudioContentDescription(remote_desc);
1044 const cricket::VideoContentDescription* video_desc =
1045 GetFirstVideoContentDescription(remote_desc);
1046 const cricket::DataContentDescription* data_desc =
1047 GetFirstDataContentDescription(remote_desc);
1048
1049 // Check if the descriptions include streams, just in case the peer supports
1050 // MSID, but doesn't indicate so with "a=msid-semantic".
1051 if (remote_desc->msid_supported() ||
1052 (audio_desc && !audio_desc->streams().empty()) ||
1053 (video_desc && !video_desc->streams().empty())) {
1054 remote_peer_supports_msid_ = true;
1055 }
deadbeefab9b2d12015-10-14 11:33:11 -07001056
1057 // We wait to signal new streams until we finish processing the description,
1058 // since only at that point will new streams have all their tracks.
1059 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1060
1061 // Find all audio rtp streams and create corresponding remote AudioTracks
1062 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001063 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001064 if (audio_content->rejected) {
1065 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1066 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001067 bool default_audio_track_needed =
1068 !remote_peer_supports_msid_ &&
1069 MediaContentDirectionHasSend(audio_desc->direction());
1070 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1071 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001072 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001073 }
deadbeefab9b2d12015-10-14 11:33:11 -07001074 }
1075
1076 // Find all video rtp streams and create corresponding remote VideoTracks
1077 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001078 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001079 if (video_content->rejected) {
1080 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1081 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001082 bool default_video_track_needed =
1083 !remote_peer_supports_msid_ &&
1084 MediaContentDirectionHasSend(video_desc->direction());
1085 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1086 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001087 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001088 }
deadbeefab9b2d12015-10-14 11:33:11 -07001089 }
1090
1091 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001092 if (data_desc) {
1093 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001094 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001095 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001096 }
1097 }
1098
1099 // Iterate new_streams and notify the observer about new MediaStreams.
1100 for (size_t i = 0; i < new_streams->count(); ++i) {
1101 MediaStreamInterface* new_stream = new_streams->at(i);
1102 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001103 observer_->OnAddStream(
1104 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001105 }
1106
deadbeefbda7e0b2015-12-08 17:13:40 -08001107 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001108
1109 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001110 signaling_thread()->Post(RTC_FROM_HERE, this,
1111 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001112
1113 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1114 // TODO(deadbeef): We already had to hop to the network thread for
1115 // MaybeStartGathering...
1116 network_thread()->Invoke<void>(
1117 RTC_FROM_HERE,
1118 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1119 port_allocator_.get()));
1120 }
deadbeeffc648b62015-10-13 16:42:33 -07001121}
1122
deadbeef46c73892016-11-16 19:42:04 -08001123PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1124 return configuration_;
1125}
1126
deadbeef293e9262017-01-11 12:28:30 -08001127bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1128 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001129 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001130
1131 if (session_->local_description() &&
1132 configuration.ice_candidate_pool_size !=
1133 configuration_.ice_candidate_pool_size) {
1134 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1135 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001136 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001137 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001138
deadbeef293e9262017-01-11 12:28:30 -08001139 // The simplest (and most future-compatible) way to tell if the config was
1140 // modified in an invalid way is to copy each property we do support
1141 // modifying, then use operator==. There are far more properties we don't
1142 // support modifying than those we do, and more could be added.
1143 RTCConfiguration modified_config = configuration_;
1144 modified_config.servers = configuration.servers;
1145 modified_config.type = configuration.type;
1146 modified_config.ice_candidate_pool_size =
1147 configuration.ice_candidate_pool_size;
1148 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001149 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001150 if (configuration != modified_config) {
1151 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1152 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1153 }
1154
Steve Anton038834f2017-07-14 15:59:59 -07001155 // Validate the modified configuration.
1156 RTCError validate_error = ValidateConfiguration(modified_config);
1157 if (!validate_error.ok()) {
1158 return SafeSetError(std::move(validate_error), error);
1159 }
1160
deadbeef293e9262017-01-11 12:28:30 -08001161 // Note that this isn't possible through chromium, since it's an unsigned
1162 // short in WebIDL.
1163 if (configuration.ice_candidate_pool_size < 0 ||
1164 configuration.ice_candidate_pool_size > UINT16_MAX) {
1165 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1166 }
1167
1168 // Parse ICE servers before hopping to network thread.
1169 cricket::ServerAddresses stun_servers;
1170 std::vector<cricket::RelayServerConfig> turn_servers;
1171 RTCErrorType parse_error =
1172 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1173 if (parse_error != RTCErrorType::NONE) {
1174 return SafeSetError(parse_error, error);
1175 }
1176
1177 // In theory this shouldn't fail.
1178 if (!network_thread()->Invoke<bool>(
1179 RTC_FROM_HERE,
1180 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1181 stun_servers, turn_servers, modified_config.type,
1182 modified_config.ice_candidate_pool_size,
Guido Urdaneta604427b2017-10-09 09:53:49 +00001183 modified_config.prune_turn_ports))) {
deadbeef293e9262017-01-11 12:28:30 -08001184 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1185 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1186 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001187
deadbeefd1a38b52016-12-10 13:15:33 -08001188 // As described in JSEP, calling setConfiguration with new ICE servers or
1189 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1190 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001191 if (modified_config.servers != configuration_.servers ||
1192 modified_config.type != configuration_.type ||
1193 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001194 session_->SetNeedsIceRestartFlag();
1195 }
skvladd1f5fda2017-02-03 16:54:05 -08001196
1197 if (modified_config.ice_check_min_interval !=
1198 configuration_.ice_check_min_interval) {
1199 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1200 }
1201
deadbeef293e9262017-01-11 12:28:30 -08001202 configuration_ = modified_config;
1203 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001204}
1205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206bool PeerConnection::AddIceCandidate(
1207 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001208 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001209 if (IsClosed()) {
1210 return false;
1211 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212 return session_->ProcessIceMessage(ice_candidate);
1213}
1214
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001215bool PeerConnection::RemoveIceCandidates(
1216 const std::vector<cricket::Candidate>& candidates) {
1217 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1218 return session_->RemoveRemoteIceCandidates(candidates);
1219}
1220
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001221void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001222 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001223 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001224
1225 if (session_) {
1226 session_->set_metrics_observer(uma_observer_);
1227 }
1228
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001229 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001230 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001231 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001232 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001233 uma_observer_->IncrementEnumCounter(
1234 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1235 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001236 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001237 uma_observer_->IncrementEnumCounter(
1238 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1239 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001240 }
1241 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001242}
1243
zstein4b979802017-06-02 14:37:37 -07001244RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001245 if (!worker_thread()->IsCurrent()) {
1246 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001247 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1248 }
1249
1250 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1251 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1252 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1253 if (has_min && *bitrate.min_bitrate_bps < 0) {
1254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1255 "min_bitrate_bps <= 0");
1256 }
1257 if (has_current) {
1258 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1260 "current_bitrate_bps < min_bitrate_bps");
1261 } else if (*bitrate.current_bitrate_bps < 0) {
1262 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1263 "curent_bitrate_bps < 0");
1264 }
1265 }
1266 if (has_max) {
1267 if (has_current &&
1268 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1269 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1270 "max_bitrate_bps < current_bitrate_bps");
1271 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1272 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1273 "max_bitrate_bps < min_bitrate_bps");
1274 } else if (*bitrate.max_bitrate_bps < 0) {
1275 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1276 "max_bitrate_bps < 0");
1277 }
1278 }
1279
1280 Call::Config::BitrateConfigMask mask;
1281 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1282 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1283 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1284
1285 RTC_DCHECK(call_.get());
1286 call_->SetBitrateConfigMask(mask);
1287
1288 return RTCError::OK();
1289}
1290
Steve Anton8c0f7a72017-10-03 10:03:10 -07001291std::unique_ptr<rtc::SSLCertificate>
1292PeerConnection::GetRemoteAudioSSLCertificate() {
1293 if (!session_) {
1294 return nullptr;
1295 }
1296 auto* voice_channel = session_->voice_channel();
1297 if (!voice_channel) {
1298 return nullptr;
1299 }
1300 return GetRemoteSSLCertificate(voice_channel->transport_name());
1301}
1302
ivoc14d5dbe2016-07-04 07:06:55 -07001303bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1304 int64_t max_size_bytes) {
Steve Anton978b8762017-09-29 12:15:02 -07001305 return worker_thread()->Invoke<bool>(
ivoc14d5dbe2016-07-04 07:06:55 -07001306 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1307 max_size_bytes));
1308}
1309
1310void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001311 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001312 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1313}
1314
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315const SessionDescriptionInterface* PeerConnection::local_description() const {
1316 return session_->local_description();
1317}
1318
1319const SessionDescriptionInterface* PeerConnection::remote_description() const {
1320 return session_->remote_description();
1321}
1322
deadbeeffe4a8a42016-12-20 17:56:17 -08001323const SessionDescriptionInterface* PeerConnection::current_local_description()
1324 const {
1325 return session_->current_local_description();
1326}
1327
1328const SessionDescriptionInterface* PeerConnection::current_remote_description()
1329 const {
1330 return session_->current_remote_description();
1331}
1332
1333const SessionDescriptionInterface* PeerConnection::pending_local_description()
1334 const {
1335 return session_->pending_local_description();
1336}
1337
1338const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1339 const {
1340 return session_->pending_remote_description();
1341}
1342
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001344 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 // Update stats here so that we have the most recent stats for tracks and
1346 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001347 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348
deadbeefd59daf82015-10-14 15:02:44 -07001349 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001350 network_thread()->Invoke<void>(
1351 RTC_FROM_HERE,
1352 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1353 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001354
Steve Anton978b8762017-09-29 12:15:02 -07001355 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001356 call_.reset();
1357 // The event log must outlive call (and any other object that uses it).
1358 event_log_.reset();
1359 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360}
1361
deadbeefd59daf82015-10-14 15:02:44 -07001362void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1363 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001367 break;
deadbeefd59daf82015-10-14 15:02:44 -07001368 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1370 break;
deadbeefd59daf82015-10-14 15:02:44 -07001371 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1373 break;
deadbeefd59daf82015-10-14 15:02:44 -07001374 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1376 break;
deadbeefd59daf82015-10-14 15:02:44 -07001377 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1379 break;
deadbeefd59daf82015-10-14 15:02:44 -07001380 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381 ChangeSignalingState(PeerConnectionInterface::kStable);
1382 break;
deadbeefd59daf82015-10-14 15:02:44 -07001383 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384 ChangeSignalingState(PeerConnectionInterface::kClosed);
1385 break;
1386 default:
1387 break;
1388 }
1389}
1390
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001391void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1394 SetSessionDescriptionMsg* param =
1395 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1396 param->observer->OnSuccess();
1397 delete param;
1398 break;
1399 }
1400 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1401 SetSessionDescriptionMsg* param =
1402 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1403 param->observer->OnFailure(param->error);
1404 delete param;
1405 break;
1406 }
deadbeefab9b2d12015-10-14 11:33:11 -07001407 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1408 CreateSessionDescriptionMsg* param =
1409 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1410 param->observer->OnFailure(param->error);
1411 delete param;
1412 break;
1413 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 case MSG_GETSTATS: {
1415 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001416 StatsReports reports;
1417 stats_->GetStats(param->track, &reports);
1418 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001419 delete param;
1420 break;
1421 }
deadbeefbd292462015-12-14 18:15:29 -08001422 case MSG_FREE_DATACHANNELS: {
1423 sctp_data_channels_to_free_.clear();
1424 break;
1425 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001427 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001428 break;
1429 }
1430}
1431
deadbeefab9b2d12015-10-14 11:33:11 -07001432void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001433 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001434 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001435 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1436 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001437 signaling_thread(),
1438 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1439 stream->AddTrack(
1440 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001441 receivers_.push_back(receiver);
1442 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1443 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1444 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445}
1446
deadbeefab9b2d12015-10-14 11:33:11 -07001447void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001448 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001449 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001450 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1451 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001452 signaling_thread(),
Steve Anton978b8762017-09-29 12:15:02 -07001453 new VideoRtpReceiver(track_id, worker_thread(), ssrc,
deadbeefe814a0d2017-02-25 18:15:09 -08001454 session_->video_channel()));
1455 stream->AddTrack(
1456 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001457 receivers_.push_back(receiver);
1458 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1459 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1460 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461}
1462
deadbeef70ab1a12015-09-28 16:53:55 -07001463// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1464// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07001465rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
1466 const std::string& track_id) {
perkjd61bf802016-03-24 03:16:19 -07001467 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001468 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001469 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001470 << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07001471 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07001472 }
Henrik Boström933d8b02017-10-10 10:05:16 -07001473 (*it)->internal()->Stop();
1474 rtc::scoped_refptr<RtpReceiverInterface> receiver = *it;
1475 receivers_.erase(it);
1476 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477}
1478
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001479void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1480 MediaStreamInterface* stream) {
1481 RTC_DCHECK(!IsClosed());
1482 auto sender = FindSenderForTrack(track);
1483 if (sender != senders_.end()) {
1484 // We already have a sender for this track, so just change the stream_id
1485 // so that it's correct in the next call to CreateOffer.
1486 (*sender)->internal()->set_stream_id(stream->label());
1487 return;
1488 }
1489
1490 // Normal case; we've never seen this track before.
1491 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1492 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1493 signaling_thread(),
Steve Anton8ffb9c32017-08-31 15:45:38 -07001494 new AudioRtpSender(track, {stream->label()},
1495 session_->voice_channel(), stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001496 senders_.push_back(new_sender);
1497 // If the sender has already been configured in SDP, we call SetSsrc,
1498 // which will connect the sender to the underlying transport. This can
1499 // occur if a local session description that contains the ID of the sender
1500 // is set before AddStream is called. It can also occur if the local
1501 // session description is not changed and RemoveStream is called, and
1502 // later AddStream is called again with the same stream.
1503 const TrackInfo* track_info =
1504 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1505 if (track_info) {
1506 new_sender->internal()->SetSsrc(track_info->ssrc);
1507 }
1508}
1509
1510// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1511// indefinitely, when we have unified plan SDP.
1512void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1513 MediaStreamInterface* stream) {
1514 RTC_DCHECK(!IsClosed());
1515 auto sender = FindSenderForTrack(track);
1516 if (sender == senders_.end()) {
1517 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1518 << " doesn't exist.";
1519 return;
1520 }
1521 (*sender)->internal()->Stop();
1522 senders_.erase(sender);
1523}
1524
1525void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1526 MediaStreamInterface* stream) {
1527 RTC_DCHECK(!IsClosed());
1528 auto sender = FindSenderForTrack(track);
1529 if (sender != senders_.end()) {
1530 // We already have a sender for this track, so just change the stream_id
1531 // so that it's correct in the next call to CreateOffer.
1532 (*sender)->internal()->set_stream_id(stream->label());
1533 return;
1534 }
1535
1536 // Normal case; we've never seen this track before.
1537 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1538 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton8ffb9c32017-08-31 15:45:38 -07001539 signaling_thread(), new VideoRtpSender(track, {stream->label()},
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001540 session_->video_channel()));
1541 senders_.push_back(new_sender);
1542 const TrackInfo* track_info =
1543 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1544 if (track_info) {
1545 new_sender->internal()->SetSsrc(track_info->ssrc);
1546 }
1547}
1548
1549void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1550 MediaStreamInterface* stream) {
1551 RTC_DCHECK(!IsClosed());
1552 auto sender = FindSenderForTrack(track);
1553 if (sender == senders_.end()) {
1554 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1555 << " doesn't exist.";
1556 return;
1557 }
1558 (*sender)->internal()->Stop();
1559 senders_.erase(sender);
1560}
1561
zstein6dfd53a2017-03-06 13:49:03 -08001562void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001564 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001565 // After transitioning to "closed", ignore any additional states from
1566 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001567 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001568 return;
1569 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001571 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001572}
1573
1574void PeerConnection::OnIceGatheringChange(
1575 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001576 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001577 if (IsClosed()) {
1578 return;
1579 }
1580 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001581 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582}
1583
jbauch81bf7b02017-03-25 08:31:12 -07001584void PeerConnection::OnIceCandidate(
1585 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001586 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001587 if (IsClosed()) {
1588 return;
1589 }
jbauch81bf7b02017-03-25 08:31:12 -07001590 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591}
1592
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001593void PeerConnection::OnIceCandidatesRemoved(
1594 const std::vector<cricket::Candidate>& candidates) {
1595 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001596 if (IsClosed()) {
1597 return;
1598 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001599 observer_->OnIceCandidatesRemoved(candidates);
1600}
1601
Peter Thatcher54360512015-07-08 11:08:35 -07001602void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001603 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001604 if (IsClosed()) {
1605 return;
1606 }
Peter Thatcher54360512015-07-08 11:08:35 -07001607 observer_->OnIceConnectionReceivingChange(receiving);
1608}
1609
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001610void PeerConnection::ChangeSignalingState(
1611 PeerConnectionInterface::SignalingState signaling_state) {
1612 signaling_state_ = signaling_state;
1613 if (signaling_state == kClosed) {
1614 ice_connection_state_ = kIceConnectionClosed;
1615 observer_->OnIceConnectionChange(ice_connection_state_);
1616 if (ice_gathering_state_ != kIceGatheringComplete) {
1617 ice_gathering_state_ = kIceGatheringComplete;
1618 observer_->OnIceGatheringChange(ice_gathering_state_);
1619 }
1620 }
1621 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001622}
1623
deadbeefeb459812015-12-15 19:24:43 -08001624void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1625 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001626 if (IsClosed()) {
1627 return;
1628 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001629 AddAudioTrack(track, stream);
1630 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001631}
1632
deadbeefeb459812015-12-15 19:24:43 -08001633void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1634 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001635 if (IsClosed()) {
1636 return;
1637 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001638 RemoveAudioTrack(track, stream);
1639 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001640}
1641
1642void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1643 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001644 if (IsClosed()) {
1645 return;
1646 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001647 AddVideoTrack(track, stream);
1648 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001649}
1650
1651void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1652 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001653 if (IsClosed()) {
1654 return;
1655 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001656 RemoveVideoTrack(track, stream);
1657 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001658}
1659
deadbeefab9b2d12015-10-14 11:33:11 -07001660void PeerConnection::PostSetSessionDescriptionFailure(
1661 SetSessionDescriptionObserver* observer,
1662 const std::string& error) {
1663 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1664 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001665 signaling_thread()->Post(RTC_FROM_HERE, this,
1666 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001667}
1668
1669void PeerConnection::PostCreateSessionDescriptionFailure(
1670 CreateSessionDescriptionObserver* observer,
1671 const std::string& error) {
1672 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1673 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001674 signaling_thread()->Post(RTC_FROM_HERE, this,
1675 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001676}
1677
zhihuang1c378ed2017-08-17 14:10:50 -07001678void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001679 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1680 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001681 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1682
1683 // Figure out transceiver directional preferences.
1684 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1685 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1686
1687 // By default, generate sendrecv/recvonly m= sections.
1688 bool recv_audio = true;
1689 bool recv_video = true;
1690
1691 // By default, only offer a new m= section if we have media to send with it.
1692 bool offer_new_audio_description = send_audio;
1693 bool offer_new_video_description = send_video;
1694 bool offer_new_data_description = HasDataChannels();
1695
1696 // The "offer_to_receive_X" options allow those defaults to be overridden.
1697 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1698 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1699 offer_new_audio_description =
1700 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1701 }
1702 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1703 recv_video = (rtc_options.offer_to_receive_video > 0);
1704 offer_new_video_description =
1705 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1706 }
1707
1708 rtc::Optional<size_t> audio_index;
1709 rtc::Optional<size_t> video_index;
1710 rtc::Optional<size_t> data_index;
1711 // If a current description exists, generate m= sections in the same order,
1712 // using the first audio/video/data section that appears and rejecting
1713 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001714 if (session_->local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07001715 GenerateMediaDescriptionOptions(
1716 session_->local_description(),
1717 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1718 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1719 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001720 }
1721
zhihuang1c378ed2017-08-17 14:10:50 -07001722 // Add audio/video/data m= sections to the end if needed.
1723 if (!audio_index && offer_new_audio_description) {
1724 session_options->media_description_options.push_back(
1725 cricket::MediaDescriptionOptions(
1726 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1727 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1728 audio_index = rtc::Optional<size_t>(
1729 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001730 }
zhihuang1c378ed2017-08-17 14:10:50 -07001731 if (!video_index && offer_new_video_description) {
1732 session_options->media_description_options.push_back(
1733 cricket::MediaDescriptionOptions(
1734 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1735 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1736 video_index = rtc::Optional<size_t>(
1737 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001738 }
zhihuang1c378ed2017-08-17 14:10:50 -07001739 if (!data_index && offer_new_data_description) {
1740 session_options->media_description_options.push_back(
1741 cricket::MediaDescriptionOptions(
1742 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1743 cricket::RtpTransceiverDirection(true, true), false));
1744 data_index = rtc::Optional<size_t>(
1745 session_options->media_description_options.size() - 1);
1746 }
1747
1748 cricket::MediaDescriptionOptions* audio_media_description_options =
1749 !audio_index ? nullptr
1750 : &session_options->media_description_options[*audio_index];
1751 cricket::MediaDescriptionOptions* video_media_description_options =
1752 !video_index ? nullptr
1753 : &session_options->media_description_options[*video_index];
1754 cricket::MediaDescriptionOptions* data_media_description_options =
1755 !data_index ? nullptr
1756 : &session_options->media_description_options[*data_index];
1757
1758 // Apply ICE restart flag and renomination flag.
1759 for (auto& options : session_options->media_description_options) {
1760 options.transport_options.ice_restart = rtc_options.ice_restart;
1761 options.transport_options.enable_ice_renomination =
1762 configuration_.enable_ice_renomination;
1763 }
1764
1765 AddRtpSenderOptions(senders_, audio_media_description_options,
1766 video_media_description_options);
1767 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001768
zhihuang9763d562016-08-05 11:14:50 -07001769 // Intentionally unset the data channel type for RTP data channel with the
1770 // second condition. Otherwise the RTP data channels would be successfully
1771 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1772 // when building with chromium. We want to leave RTP data channels broken, so
1773 // people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001774 if (!rtp_data_channels_.empty() ||
1775 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001776 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001777 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001778
1779 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001780 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001781}
1782
zhihuang1c378ed2017-08-17 14:10:50 -07001783void PeerConnection::GetOptionsForAnswer(
1784 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001785 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001786 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001787
zhihuang1c378ed2017-08-17 14:10:50 -07001788 // Figure out transceiver directional preferences.
1789 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1790 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1791
1792 // By default, generate sendrecv/recvonly m= sections. The direction is also
1793 // restricted by the direction in the offer.
1794 bool recv_audio = true;
1795 bool recv_video = true;
1796
1797 // The "offer_to_receive_X" options allow those defaults to be overridden.
1798 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1799 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001800 }
zhihuang1c378ed2017-08-17 14:10:50 -07001801 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1802 recv_video = (rtc_options.offer_to_receive_video > 0);
1803 }
1804
1805 rtc::Optional<size_t> audio_index;
1806 rtc::Optional<size_t> video_index;
1807 rtc::Optional<size_t> data_index;
zhihuang141aacb2017-08-29 13:23:53 -07001808 if (session_->remote_description()) {
1809 // The pending remote description should be an offer.
1810 RTC_DCHECK(session_->remote_description()->type() ==
1811 SessionDescriptionInterface::kOffer);
1812 // Generate m= sections that match those in the offer.
1813 // Note that mediasession.cc will handle intersection our preferred
1814 // direction with the offered direction.
1815 GenerateMediaDescriptionOptions(
1816 session_->remote_description(),
1817 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1818 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1819 &video_index, &data_index, session_options);
1820 }
zhihuang1c378ed2017-08-17 14:10:50 -07001821
1822 cricket::MediaDescriptionOptions* audio_media_description_options =
1823 !audio_index ? nullptr
1824 : &session_options->media_description_options[*audio_index];
1825 cricket::MediaDescriptionOptions* video_media_description_options =
1826 !video_index ? nullptr
1827 : &session_options->media_description_options[*video_index];
1828 cricket::MediaDescriptionOptions* data_media_description_options =
1829 !data_index ? nullptr
1830 : &session_options->media_description_options[*data_index];
1831
1832 // Apply ICE renomination flag.
1833 for (auto& options : session_options->media_description_options) {
1834 options.transport_options.enable_ice_renomination =
1835 configuration_.enable_ice_renomination;
1836 }
1837
1838 AddRtpSenderOptions(senders_, audio_media_description_options,
1839 video_media_description_options);
1840 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
1841
zhihuang9763d562016-08-05 11:14:50 -07001842 // Intentionally unset the data channel type for RTP data channel. Otherwise
1843 // the RTP data channels would be successfully negotiated by default and the
1844 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1845 // We want to leave RTP data channels broken, so people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001846 if (!rtp_data_channels_.empty() ||
1847 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001848 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001849 }
zhihuangaf388472016-11-02 16:49:48 -07001850
zhihuang1c378ed2017-08-17 14:10:50 -07001851 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001852 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001853}
1854
zhihuang1c378ed2017-08-17 14:10:50 -07001855void PeerConnection::GenerateMediaDescriptionOptions(
1856 const SessionDescriptionInterface* session_desc,
1857 cricket::RtpTransceiverDirection audio_direction,
1858 cricket::RtpTransceiverDirection video_direction,
1859 rtc::Optional<size_t>* audio_index,
1860 rtc::Optional<size_t>* video_index,
1861 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08001862 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001863 for (const cricket::ContentInfo& content :
1864 session_desc->description()->contents()) {
1865 if (IsAudioContent(&content)) {
1866 // If we already have an audio m= section, reject this extra one.
1867 if (*audio_index) {
1868 session_options->media_description_options.push_back(
1869 cricket::MediaDescriptionOptions(
1870 cricket::MEDIA_TYPE_AUDIO, content.name,
1871 cricket::RtpTransceiverDirection(false, false), true));
1872 } else {
1873 session_options->media_description_options.push_back(
1874 cricket::MediaDescriptionOptions(
1875 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
1876 !audio_direction.send && !audio_direction.recv));
1877 *audio_index = rtc::Optional<size_t>(
1878 session_options->media_description_options.size() - 1);
1879 }
1880 } else if (IsVideoContent(&content)) {
1881 // If we already have an video m= section, reject this extra one.
1882 if (*video_index) {
1883 session_options->media_description_options.push_back(
1884 cricket::MediaDescriptionOptions(
1885 cricket::MEDIA_TYPE_VIDEO, content.name,
1886 cricket::RtpTransceiverDirection(false, false), true));
1887 } else {
1888 session_options->media_description_options.push_back(
1889 cricket::MediaDescriptionOptions(
1890 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1891 !video_direction.send && !video_direction.recv));
1892 *video_index = rtc::Optional<size_t>(
1893 session_options->media_description_options.size() - 1);
1894 }
1895 } else {
1896 RTC_DCHECK(IsDataContent(&content));
1897 // If we already have an data m= section, reject this extra one.
1898 if (*data_index) {
1899 session_options->media_description_options.push_back(
1900 cricket::MediaDescriptionOptions(
1901 cricket::MEDIA_TYPE_DATA, content.name,
1902 cricket::RtpTransceiverDirection(false, false), true));
1903 } else {
1904 session_options->media_description_options.push_back(
1905 cricket::MediaDescriptionOptions(
1906 cricket::MEDIA_TYPE_DATA, content.name,
1907 // Direction for data sections is meaningless, but legacy
1908 // endpoints might expect sendrecv.
1909 cricket::RtpTransceiverDirection(true, true), false));
1910 *data_index = rtc::Optional<size_t>(
1911 session_options->media_description_options.size() - 1);
1912 }
1913 }
htaa2a49d92016-03-04 02:51:39 -08001914 }
deadbeefab9b2d12015-10-14 11:33:11 -07001915}
1916
deadbeeffaac4972015-11-12 15:33:07 -08001917void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1918 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001919 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1920 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001921}
1922
deadbeefab9b2d12015-10-14 11:33:11 -07001923void PeerConnection::UpdateRemoteStreamsList(
1924 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001925 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001926 cricket::MediaType media_type,
1927 StreamCollection* new_streams) {
1928 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1929
1930 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001931 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001932 auto track_it = current_tracks->begin();
1933 while (track_it != current_tracks->end()) {
1934 const TrackInfo& info = *track_it;
1935 const cricket::StreamParams* params =
1936 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001937 bool track_exists = params && params->id == info.track_id;
1938 // If this is a default track, and we still need it, don't remove it.
1939 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1940 track_exists) {
1941 ++track_it;
1942 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001943 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1944 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001945 }
1946 }
1947
1948 // Find new and active tracks.
1949 for (const cricket::StreamParams& params : streams) {
1950 // The sync_label is the MediaStream label and the |stream.id| is the
1951 // track id.
1952 const std::string& stream_label = params.sync_label;
1953 const std::string& track_id = params.id;
1954 uint32_t ssrc = params.first_ssrc();
1955
1956 rtc::scoped_refptr<MediaStreamInterface> stream =
1957 remote_streams_->find(stream_label);
1958 if (!stream) {
1959 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001960 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1961 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001962 remote_streams_->AddStream(stream);
1963 new_streams->AddStream(stream);
1964 }
1965
1966 const TrackInfo* track_info =
1967 FindTrackInfo(*current_tracks, stream_label, track_id);
1968 if (!track_info) {
1969 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1970 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1971 }
1972 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001973
1974 // Add default track if necessary.
1975 if (default_track_needed) {
1976 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1977 remote_streams_->find(kDefaultStreamLabel);
1978 if (!default_stream) {
1979 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001980 default_stream = MediaStreamProxy::Create(
1981 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001982 remote_streams_->AddStream(default_stream);
1983 new_streams->AddStream(default_stream);
1984 }
1985 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1986 ? kDefaultAudioTrackLabel
1987 : kDefaultVideoTrackLabel;
1988 const TrackInfo* default_track_info =
1989 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1990 if (!default_track_info) {
1991 current_tracks->push_back(
1992 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1993 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1994 }
1995 }
deadbeefab9b2d12015-10-14 11:33:11 -07001996}
1997
1998void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1999 const std::string& track_id,
2000 uint32_t ssrc,
2001 cricket::MediaType media_type) {
2002 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2003
2004 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002005 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002006 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002007 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002008 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002009 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002010 }
2011}
2012
2013void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2014 const std::string& track_id,
2015 cricket::MediaType media_type) {
2016 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2017
Henrik Boström933d8b02017-10-10 10:05:16 -07002018 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002019 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002020 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2021 // will be notified which will end the AudioRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002022 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002023 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2024 stream->FindAudioTrack(track_id);
2025 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002026 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002027 }
2028 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002029 // Stopping or destroying a VideoRtpReceiver will end the
2030 // VideoRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002031 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002032 rtc::scoped_refptr<VideoTrackInterface> video_track =
2033 stream->FindVideoTrack(track_id);
2034 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002035 // There's no guarantee the track is still available, e.g. the track may
2036 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002037 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002038 }
2039 } else {
nisseede5da42017-01-12 05:15:36 -08002040 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002041 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002042 if (receiver) {
2043 observer_->OnRemoveTrack(receiver);
2044 }
deadbeefab9b2d12015-10-14 11:33:11 -07002045}
2046
2047void PeerConnection::UpdateEndedRemoteMediaStreams() {
2048 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2049 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2050 MediaStreamInterface* stream = remote_streams_->at(i);
2051 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2052 streams_to_remove.push_back(stream);
2053 }
2054 }
2055
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002056 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002057 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002058 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002059 }
2060}
2061
deadbeefab9b2d12015-10-14 11:33:11 -07002062void PeerConnection::UpdateLocalTracks(
2063 const std::vector<cricket::StreamParams>& streams,
2064 cricket::MediaType media_type) {
2065 TrackInfos* current_tracks = GetLocalTracks(media_type);
2066
2067 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2068 // don't match the new StreamParam.
2069 TrackInfos::iterator track_it = current_tracks->begin();
2070 while (track_it != current_tracks->end()) {
2071 const TrackInfo& info = *track_it;
2072 const cricket::StreamParams* params =
2073 cricket::GetStreamBySsrc(streams, info.ssrc);
2074 if (!params || params->id != info.track_id ||
2075 params->sync_label != info.stream_label) {
2076 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2077 media_type);
2078 track_it = current_tracks->erase(track_it);
2079 } else {
2080 ++track_it;
2081 }
2082 }
2083
2084 // Find new and active tracks.
2085 for (const cricket::StreamParams& params : streams) {
2086 // The sync_label is the MediaStream label and the |stream.id| is the
2087 // track id.
2088 const std::string& stream_label = params.sync_label;
2089 const std::string& track_id = params.id;
2090 uint32_t ssrc = params.first_ssrc();
2091 const TrackInfo* track_info =
2092 FindTrackInfo(*current_tracks, stream_label, track_id);
2093 if (!track_info) {
2094 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2095 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2096 }
2097 }
2098}
2099
2100void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2101 const std::string& track_id,
2102 uint32_t ssrc,
2103 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002104 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002105 if (!sender) {
2106 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2107 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002108 return;
2109 }
2110
deadbeeffac06552015-11-25 11:26:01 -08002111 if (sender->media_type() != media_type) {
2112 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2113 << " description with an unexpected media type.";
2114 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002115 }
deadbeeffac06552015-11-25 11:26:01 -08002116
2117 sender->set_stream_id(stream_label);
2118 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002119}
2120
2121void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2122 const std::string& track_id,
2123 uint32_t ssrc,
2124 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002125 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002126 if (!sender) {
2127 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002128 // SessionDescriptions has been renegotiated.
2129 return;
2130 }
deadbeeffac06552015-11-25 11:26:01 -08002131
2132 // A sender has been removed from the SessionDescription but it's still
2133 // associated with the PeerConnection. This only occurs if the SDP doesn't
2134 // match with the calls to CreateSender, AddStream and RemoveStream.
2135 if (sender->media_type() != media_type) {
2136 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2137 << " description with an unexpected media type.";
2138 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002139 }
deadbeeffac06552015-11-25 11:26:01 -08002140
2141 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002142}
2143
2144void PeerConnection::UpdateLocalRtpDataChannels(
2145 const cricket::StreamParamsVec& streams) {
2146 std::vector<std::string> existing_channels;
2147
2148 // Find new and active data channels.
2149 for (const cricket::StreamParams& params : streams) {
2150 // |it->sync_label| is actually the data channel label. The reason is that
2151 // we use the same naming of data channels as we do for
2152 // MediaStreams and Tracks.
2153 // For MediaStreams, the sync_label is the MediaStream label and the
2154 // track label is the same as |streamid|.
2155 const std::string& channel_label = params.sync_label;
2156 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002157 if (data_channel_it == rtp_data_channels_.end()) {
2158 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002159 continue;
2160 }
2161 // Set the SSRC the data channel should use for sending.
2162 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2163 existing_channels.push_back(data_channel_it->first);
2164 }
2165
2166 UpdateClosingRtpDataChannels(existing_channels, true);
2167}
2168
2169void PeerConnection::UpdateRemoteRtpDataChannels(
2170 const cricket::StreamParamsVec& streams) {
2171 std::vector<std::string> existing_channels;
2172
2173 // Find new and active data channels.
2174 for (const cricket::StreamParams& params : streams) {
2175 // The data channel label is either the mslabel or the SSRC if the mslabel
2176 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2177 std::string label = params.sync_label.empty()
2178 ? rtc::ToString(params.first_ssrc())
2179 : params.sync_label;
2180 auto data_channel_it = rtp_data_channels_.find(label);
2181 if (data_channel_it == rtp_data_channels_.end()) {
2182 // This is a new data channel.
2183 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2184 } else {
2185 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2186 }
2187 existing_channels.push_back(label);
2188 }
2189
2190 UpdateClosingRtpDataChannels(existing_channels, false);
2191}
2192
2193void PeerConnection::UpdateClosingRtpDataChannels(
2194 const std::vector<std::string>& active_channels,
2195 bool is_local_update) {
2196 auto it = rtp_data_channels_.begin();
2197 while (it != rtp_data_channels_.end()) {
2198 DataChannel* data_channel = it->second;
2199 if (std::find(active_channels.begin(), active_channels.end(),
2200 data_channel->label()) != active_channels.end()) {
2201 ++it;
2202 continue;
2203 }
2204
2205 if (is_local_update) {
2206 data_channel->SetSendSsrc(0);
2207 } else {
2208 data_channel->RemotePeerRequestClose();
2209 }
2210
2211 if (data_channel->state() == DataChannel::kClosed) {
2212 rtp_data_channels_.erase(it);
2213 it = rtp_data_channels_.begin();
2214 } else {
2215 ++it;
2216 }
2217 }
2218}
2219
2220void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2221 uint32_t remote_ssrc) {
2222 rtc::scoped_refptr<DataChannel> channel(
2223 InternalCreateDataChannel(label, nullptr));
2224 if (!channel.get()) {
2225 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2226 << "CreateDataChannel failed.";
2227 return;
2228 }
2229 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002230 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2231 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002232 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002233}
2234
2235rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2236 const std::string& label,
2237 const InternalDataChannelInit* config) {
2238 if (IsClosed()) {
2239 return nullptr;
2240 }
2241 if (session_->data_channel_type() == cricket::DCT_NONE) {
2242 LOG(LS_ERROR)
2243 << "InternalCreateDataChannel: Data is not supported in this call.";
2244 return nullptr;
2245 }
2246 InternalDataChannelInit new_config =
2247 config ? (*config) : InternalDataChannelInit();
2248 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2249 if (new_config.id < 0) {
2250 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002251 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002252 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2253 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2254 return nullptr;
2255 }
2256 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2257 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2258 << "because the id is already in use or out of range.";
2259 return nullptr;
2260 }
2261 }
2262
2263 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
Steve Anton978b8762017-09-29 12:15:02 -07002264 session_, session_->data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002265 if (!channel) {
2266 sid_allocator_.ReleaseSid(new_config.id);
2267 return nullptr;
2268 }
2269
2270 if (channel->data_channel_type() == cricket::DCT_RTP) {
2271 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2272 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2273 << " already exists.";
2274 return nullptr;
2275 }
2276 rtp_data_channels_[channel->label()] = channel;
2277 } else {
2278 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2279 sctp_data_channels_.push_back(channel);
2280 channel->SignalClosed.connect(this,
2281 &PeerConnection::OnSctpDataChannelClosed);
2282 }
2283
hbos82ebe022016-11-14 01:41:09 -08002284 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002285 return channel;
2286}
2287
2288bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002289#ifdef HAVE_QUIC
2290 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2291 (session_->quic_data_transport() &&
2292 session_->quic_data_transport()->HasDataChannels());
2293#else
deadbeefab9b2d12015-10-14 11:33:11 -07002294 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002295#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002296}
2297
2298void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2299 for (const auto& channel : sctp_data_channels_) {
2300 if (channel->id() < 0) {
2301 int sid;
2302 if (!sid_allocator_.AllocateSid(role, &sid)) {
2303 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2304 continue;
2305 }
2306 channel->SetSctpSid(sid);
2307 }
2308 }
2309}
2310
2311void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002312 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002313 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2314 ++it) {
2315 if (it->get() == channel) {
2316 if (channel->id() >= 0) {
2317 sid_allocator_.ReleaseSid(channel->id());
2318 }
deadbeefbd292462015-12-14 18:15:29 -08002319 // Since this method is triggered by a signal from the DataChannel,
2320 // we can't free it directly here; we need to free it asynchronously.
2321 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002322 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002323 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2324 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002325 return;
2326 }
2327 }
2328}
2329
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002330void PeerConnection::OnVoiceChannelCreated() {
2331 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2332 session_->voice_channel(), senders_, receivers_,
2333 cricket::MEDIA_TYPE_AUDIO);
2334}
2335
deadbeefab9b2d12015-10-14 11:33:11 -07002336void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002337 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2338 cricket::VoiceChannel>(
2339 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2340}
2341
2342void PeerConnection::OnVideoChannelCreated() {
2343 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2344 session_->video_channel(), senders_, receivers_,
2345 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002346}
2347
2348void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002349 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2350 cricket::VideoChannel>(
2351 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002352}
2353
2354void PeerConnection::OnDataChannelCreated() {
2355 for (const auto& channel : sctp_data_channels_) {
2356 channel->OnTransportChannelCreated();
2357 }
2358}
2359
2360void PeerConnection::OnDataChannelDestroyed() {
2361 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2362 // DataChannel may callback to us and try to modify the list.
2363 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2364 temp_rtp_dcs.swap(rtp_data_channels_);
2365 for (const auto& kv : temp_rtp_dcs) {
2366 kv.second->OnTransportChannelDestroyed();
2367 }
2368
2369 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2370 temp_sctp_dcs.swap(sctp_data_channels_);
2371 for (const auto& channel : temp_sctp_dcs) {
2372 channel->OnTransportChannelDestroyed();
2373 }
2374}
2375
2376void PeerConnection::OnDataChannelOpenMessage(
2377 const std::string& label,
2378 const InternalDataChannelInit& config) {
2379 rtc::scoped_refptr<DataChannel> channel(
2380 InternalCreateDataChannel(label, &config));
2381 if (!channel.get()) {
2382 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2383 return;
2384 }
2385
deadbeefa601f5c2016-06-06 14:27:39 -07002386 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2387 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002388 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002389}
2390
zhihuang1c378ed2017-08-17 14:10:50 -07002391bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2392 return std::find_if(
2393 senders_.begin(), senders_.end(),
2394 [type](const rtc::scoped_refptr<
2395 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2396 return sender->media_type() == type;
2397 }) != senders_.end();
2398}
2399
deadbeefa601f5c2016-06-06 14:27:39 -07002400RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2401 auto it = std::find_if(
2402 senders_.begin(), senders_.end(),
2403 [id](const rtc::scoped_refptr<
2404 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2405 return sender->id() == id;
2406 });
2407 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002408}
2409
deadbeefa601f5c2016-06-06 14:27:39 -07002410std::vector<
2411 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002412PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2413 return std::find_if(
2414 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002415 [track](const rtc::scoped_refptr<
2416 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002417 return sender->track() == track;
2418 });
2419}
2420
deadbeefa601f5c2016-06-06 14:27:39 -07002421std::vector<rtc::scoped_refptr<
2422 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002423PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002424 return std::find_if(
2425 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002426 [track_id](const rtc::scoped_refptr<
2427 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002428 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002429 });
2430}
2431
deadbeefab9b2d12015-10-14 11:33:11 -07002432PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2433 cricket::MediaType media_type) {
2434 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2435 media_type == cricket::MEDIA_TYPE_VIDEO);
2436 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2437 : &remote_video_tracks_;
2438}
2439
2440PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2441 cricket::MediaType media_type) {
2442 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2443 media_type == cricket::MEDIA_TYPE_VIDEO);
2444 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2445 : &local_video_tracks_;
2446}
2447
2448const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2449 const PeerConnection::TrackInfos& infos,
2450 const std::string& stream_label,
2451 const std::string track_id) const {
2452 for (const TrackInfo& track_info : infos) {
2453 if (track_info.stream_label == stream_label &&
2454 track_info.track_id == track_id) {
2455 return &track_info;
2456 }
2457 }
2458 return nullptr;
2459}
2460
2461DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2462 for (const auto& channel : sctp_data_channels_) {
2463 if (channel->id() == sid) {
2464 return channel;
2465 }
2466 }
2467 return nullptr;
2468}
2469
deadbeef91dd5672016-05-18 16:55:30 -07002470bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002471 const RTCConfiguration& configuration) {
2472 cricket::ServerAddresses stun_servers;
2473 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002474 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2475 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002476 return false;
2477 }
2478
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002479 port_allocator_->Initialize();
2480
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002481 // To handle both internal and externally created port allocator, we will
2482 // enable BUNDLE here.
2483 int portallocator_flags = port_allocator_->flags();
2484 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002485 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2486 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002487 // If the disable-IPv6 flag was specified, we'll not override it
2488 // by experiment.
2489 if (configuration.disable_ipv6) {
2490 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002491 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2492 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002493 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2494 }
2495
zhihuangb09b3f92017-03-07 14:40:51 -08002496 if (configuration.disable_ipv6_on_wifi) {
2497 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2498 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2499 }
2500
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002501 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2502 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2503 LOG(LS_INFO) << "TCP candidates are disabled.";
2504 }
2505
honghaiz60347052016-05-31 18:29:12 -07002506 if (configuration.candidate_network_policy ==
2507 kCandidateNetworkPolicyLowCost) {
2508 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2509 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2510 }
2511
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002512 port_allocator_->set_flags(portallocator_flags);
2513 // No step delay is used while allocating ports.
2514 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2515 port_allocator_->set_candidate_filter(
2516 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002517 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002518
2519 // Call this last since it may create pooled allocator sessions using the
2520 // properties set above.
2521 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002522 configuration.ice_candidate_pool_size,
Guido Urdaneta604427b2017-10-09 09:53:49 +00002523 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002524 return true;
2525}
2526
deadbeef91dd5672016-05-18 16:55:30 -07002527bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002528 const cricket::ServerAddresses& stun_servers,
2529 const std::vector<cricket::RelayServerConfig>& turn_servers,
2530 IceTransportsType type,
2531 int candidate_pool_size,
Guido Urdaneta604427b2017-10-09 09:53:49 +00002532 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002533 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002534 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002535 // Call this last since it may create pooled allocator sessions using the
2536 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002537 return port_allocator_->SetConfiguration(
Guido Urdaneta604427b2017-10-09 09:53:49 +00002538 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002539}
2540
ivoc14d5dbe2016-07-04 07:06:55 -07002541bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2542 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002543 if (!event_log_) {
2544 return false;
2545 }
Elad Alon83ccca12017-10-04 13:18:26 +02002546
2547 // TODO(eladalon): It would be better to not allow negative values into PC.
2548 const size_t max_size = (max_size_bytes < 0)
2549 ? RtcEventLog::kUnlimitedOutput
2550 : rtc::saturated_cast<size_t>(max_size_bytes);
2551
2552 return event_log_->StartLogging(
2553 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
ivoc14d5dbe2016-07-04 07:06:55 -07002554}
2555
2556void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002557 if (event_log_) {
2558 event_log_->StopLogging();
2559 }
ivoc14d5dbe2016-07-04 07:06:55 -07002560}
nisseeaabdf62017-05-05 02:23:02 -07002561
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002562} // namespace webrtc