blob: 3af56671af451927f6b1ecc4a687695a0c14cd41 [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
ossu7bb87ee2017-01-23 04:56:25 -080011#include "webrtc/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
Henrik Kjellander15583c12016-02-10 10:53:12 +010017#include "webrtc/api/jsepicecandidate.h"
18#include "webrtc/api/jsepsessiondescription.h"
19#include "webrtc/api/mediaconstraintsinterface.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010020#include "webrtc/api/mediastreamproxy.h"
21#include "webrtc/api/mediastreamtrackproxy.h"
ossuf515ab82016-12-07 04:52:58 -080022#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070023#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
deadbeef953c2ce2017-01-09 14:53:41 -080024#include "webrtc/media/sctp/sctptransport.h"
ossu7bb87ee2017-01-23 04:56:25 -080025#include "webrtc/pc/audiotrack.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010026#include "webrtc/pc/channelmanager.h"
ossu7bb87ee2017-01-23 04:56:25 -080027#include "webrtc/pc/dtmfsender.h"
28#include "webrtc/pc/mediastream.h"
29#include "webrtc/pc/mediastreamobserver.h"
30#include "webrtc/pc/remoteaudiosource.h"
31#include "webrtc/pc/rtpreceiver.h"
32#include "webrtc/pc/rtpsender.h"
33#include "webrtc/pc/streamcollection.h"
34#include "webrtc/pc/videocapturertracksource.h"
35#include "webrtc/pc/videotrack.h"
Edward Lemurc20978e2017-07-06 19:44:34 +020036#include "webrtc/rtc_base/bind.h"
37#include "webrtc/rtc_base/checks.h"
38#include "webrtc/rtc_base/logging.h"
39#include "webrtc/rtc_base/stringencode.h"
40#include "webrtc/rtc_base/stringutils.h"
41#include "webrtc/rtc_base/trace_event.h"
ossu7bb87ee2017-01-23 04:56:25 -080042#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
45namespace {
46
deadbeefab9b2d12015-10-14 11:33:11 -070047using webrtc::DataChannel;
48using webrtc::MediaConstraintsInterface;
49using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080051using webrtc::RTCError;
52using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070053using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080054using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070055using webrtc::RtpSenderProxy;
56using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070057using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
deadbeefab9b2d12015-10-14 11:33:11 -070059static const char kDefaultStreamLabel[] = "default";
60static const char kDefaultAudioTrackLabel[] = "defaulta0";
61static const char kDefaultVideoTrackLabel[] = "defaultv0";
62
zhihuang8f65cdf2016-05-06 18:40:30 -070063// The length of RTCP CNAMEs.
64static const int kRtcpCnameLength = 16;
65
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000067 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070069 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080071 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072};
73
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000074struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075 explicit SetSessionDescriptionMsg(
76 webrtc::SetSessionDescriptionObserver* observer)
77 : observer(observer) {
78 }
79
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000080 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081 std::string error;
82};
83
deadbeefab9b2d12015-10-14 11:33:11 -070084struct CreateSessionDescriptionMsg : public rtc::MessageData {
85 explicit CreateSessionDescriptionMsg(
86 webrtc::CreateSessionDescriptionObserver* observer)
87 : observer(observer) {}
88
89 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
90 std::string error;
91};
92
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000093struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000094 GetStatsMsg(webrtc::StatsObserver* observer,
95 webrtc::MediaStreamTrackInterface* track)
96 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000098 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000099 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100};
101
deadbeefab9b2d12015-10-14 11:33:11 -0700102// Check if we can send |new_stream| on a PeerConnection.
103bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
104 webrtc::MediaStreamInterface* new_stream) {
105 if (!new_stream || !current_streams) {
106 return false;
107 }
108 if (current_streams->find(new_stream->label()) != nullptr) {
109 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
110 << " is already added.";
111 return false;
112 }
113 return true;
114}
115
116bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
117 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
118}
119
deadbeef5e97fb52015-10-15 12:49:08 -0700120// If the direction is "recvonly" or "inactive", treat the description
121// as containing no streams.
122// See: https://code.google.com/p/webrtc/issues/detail?id=5054
123std::vector<cricket::StreamParams> GetActiveStreams(
124 const cricket::MediaContentDescription* desc) {
125 return MediaContentDirectionHasSend(desc->direction())
126 ? desc->streams()
127 : std::vector<cricket::StreamParams>();
128}
129
deadbeefab9b2d12015-10-14 11:33:11 -0700130bool IsValidOfferToReceiveMedia(int value) {
131 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
132 return (value >= Options::kUndefined) &&
133 (value <= Options::kMaxOfferToReceiveMedia);
134}
135
olka3c747662017-08-17 06:50:32 -0700136// Add the stream and RTP data channel info to |session_options|.
137void AddSendStreams(
138 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700139 const std::vector<rtc::scoped_refptr<
140 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuanga77e6bb2017-08-14 18:17:48 -0700141 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
olka3c747662017-08-17 06:50:32 -0700142 rtp_data_channels) {
143 session_options->streams.clear();
144 for (const auto& sender : senders) {
145 session_options->AddSendStream(sender->media_type(), sender->id(),
146 sender->internal()->stream_id());
zhihuanga77e6bb2017-08-14 18:17:48 -0700147 }
olka3c747662017-08-17 06:50:32 -0700148
deadbeefab9b2d12015-10-14 11:33:11 -0700149 // Check for data channels.
150 for (const auto& kv : rtp_data_channels) {
151 const DataChannel* channel = kv.second;
152 if (channel->state() == DataChannel::kConnecting ||
153 channel->state() == DataChannel::kOpen) {
olka3c747662017-08-17 06:50:32 -0700154 // |streamid| and |sync_label| are both set to the DataChannel label
155 // here so they can be signaled the same way as MediaStreams and Tracks.
156 // For MediaStreams, the sync_label is the MediaStream label and the
157 // track label is the same as |streamid|.
158 const std::string& streamid = channel->label();
159 const std::string& sync_label = channel->label();
160 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
161 sync_label);
deadbeefab9b2d12015-10-14 11:33:11 -0700162 }
163 }
164}
165
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700166uint32_t ConvertIceTransportTypeToCandidateFilter(
167 PeerConnectionInterface::IceTransportsType type) {
168 switch (type) {
169 case PeerConnectionInterface::kNone:
170 return cricket::CF_NONE;
171 case PeerConnectionInterface::kRelay:
172 return cricket::CF_RELAY;
173 case PeerConnectionInterface::kNoHost:
174 return (cricket::CF_ALL & ~cricket::CF_HOST);
175 case PeerConnectionInterface::kAll:
176 return cricket::CF_ALL;
177 default:
nissec80e7412017-01-11 05:56:46 -0800178 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700179 }
180 return cricket::CF_NONE;
181}
182
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700183// Helper method to set a voice/video channel on all applicable senders
184// and receivers when one is created/destroyed by WebRtcSession.
185//
186// Used by On(Voice|Video)Channel(Created|Destroyed)
187template <class SENDER,
188 class RECEIVER,
189 class CHANNEL,
190 class SENDERS,
191 class RECEIVERS>
192void SetChannelOnSendersAndReceivers(CHANNEL* channel,
193 SENDERS& senders,
194 RECEIVERS& receivers,
195 cricket::MediaType media_type) {
196 for (auto& sender : senders) {
197 if (sender->media_type() == media_type) {
198 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
199 }
200 }
201 for (auto& receiver : receivers) {
202 if (receiver->media_type() == media_type) {
203 if (!channel) {
204 receiver->internal()->Stop();
205 }
206 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
207 }
208 }
209}
210
deadbeef293e9262017-01-11 12:28:30 -0800211// Helper to set an error and return from a method.
212bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
213 if (error) {
214 error->set_type(type);
215 }
216 return type == webrtc::RTCErrorType::NONE;
217}
218
Steve Anton038834f2017-07-14 15:59:59 -0700219bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
220 if (error_out) {
221 *error_out = std::move(error);
222 }
223 return error.ok();
224}
225
deadbeef0a6c4ca2015-10-06 11:38:28 -0700226} // namespace
227
228namespace webrtc {
229
deadbeef293e9262017-01-11 12:28:30 -0800230bool PeerConnectionInterface::RTCConfiguration::operator==(
231 const PeerConnectionInterface::RTCConfiguration& o) const {
232 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700233 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800234 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000235 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700236 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800237 BundlePolicy bundle_policy;
238 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700239 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
240 int ice_candidate_pool_size;
241 bool disable_ipv6;
242 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700243 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700244 bool enable_rtp_data_channel;
245 rtc::Optional<int> screencast_min_bitrate;
246 rtc::Optional<bool> combined_audio_video_bwe;
247 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800248 TcpCandidatePolicy tcp_candidate_policy;
249 CandidateNetworkPolicy candidate_network_policy;
250 int audio_jitter_buffer_max_packets;
251 bool audio_jitter_buffer_fast_accelerate;
252 int ice_connection_receiving_timeout;
253 int ice_backup_candidate_pair_ping_interval;
254 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800255 bool prioritize_most_likely_ice_candidate_pairs;
256 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800257 bool enable_quic;
deadbeef293e9262017-01-11 12:28:30 -0800258 bool prune_turn_ports;
259 bool presume_writable_when_fully_relayed;
260 bool enable_ice_renomination;
261 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800262 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700263 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800264 };
265 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
266 "Did you add something to RTCConfiguration and forget to "
267 "update operator==?");
268 return type == o.type && servers == o.servers &&
269 bundle_policy == o.bundle_policy &&
270 rtcp_mux_policy == o.rtcp_mux_policy &&
271 tcp_candidate_policy == o.tcp_candidate_policy &&
272 candidate_network_policy == o.candidate_network_policy &&
273 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
274 audio_jitter_buffer_fast_accelerate ==
275 o.audio_jitter_buffer_fast_accelerate &&
276 ice_connection_receiving_timeout ==
277 o.ice_connection_receiving_timeout &&
278 ice_backup_candidate_pair_ping_interval ==
279 o.ice_backup_candidate_pair_ping_interval &&
280 continual_gathering_policy == o.continual_gathering_policy &&
281 certificates == o.certificates &&
282 prioritize_most_likely_ice_candidate_pairs ==
283 o.prioritize_most_likely_ice_candidate_pairs &&
284 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800285 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700286 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800287 enable_rtp_data_channel == o.enable_rtp_data_channel &&
288 enable_quic == o.enable_quic &&
289 screencast_min_bitrate == o.screencast_min_bitrate &&
290 combined_audio_video_bwe == o.combined_audio_video_bwe &&
291 enable_dtls_srtp == o.enable_dtls_srtp &&
292 ice_candidate_pool_size == o.ice_candidate_pool_size &&
293 prune_turn_ports == o.prune_turn_ports &&
294 presume_writable_when_fully_relayed ==
295 o.presume_writable_when_fully_relayed &&
296 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800297 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700298 ice_check_min_interval == o.ice_check_min_interval &&
299 ice_regather_interval_range == o.ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800300}
301
302bool PeerConnectionInterface::RTCConfiguration::operator!=(
303 const PeerConnectionInterface::RTCConfiguration& o) const {
304 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800305}
306
zhihuang8f65cdf2016-05-06 18:40:30 -0700307// Generate a RTCP CNAME when a PeerConnection is created.
308std::string GenerateRtcpCname() {
309 std::string cname;
310 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
311 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800312 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700313 }
314 return cname;
315}
316
olka3c747662017-08-17 06:50:32 -0700317bool ExtractMediaSessionOptions(
zhihuanga77e6bb2017-08-14 18:17:48 -0700318 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
olka3c747662017-08-17 06:50:32 -0700319 bool is_offer,
zhihuanga77e6bb2017-08-14 18:17:48 -0700320 cricket::MediaSessionOptions* session_options) {
olka3c747662017-08-17 06:50:32 -0700321 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
322 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
323 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
324 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700325 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700326
olka3c747662017-08-17 06:50:32 -0700327 // If constraints don't prevent us, we always accept video.
328 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
329 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
330 } else {
331 session_options->recv_audio = true;
332 }
333 // For offers, we only offer video if we have it or it's forced by options.
334 // For answers, we will always accept video (if offered).
335 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
336 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
337 } else if (is_offer) {
338 session_options->recv_video = false;
339 } else {
340 session_options->recv_video = true;
341 }
342
343 session_options->vad_enabled = rtc_options.voice_activity_detection;
344 session_options->bundle_enabled = rtc_options.use_rtp_mux;
345 for (auto& kv : session_options->transport_options) {
346 kv.second.ice_restart = rtc_options.ice_restart;
347 }
348
349 return true;
350}
351
352bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
353 cricket::MediaSessionOptions* session_options) {
zhihuanga77e6bb2017-08-14 18:17:48 -0700354 bool value = false;
355 size_t mandatory_constraints_satisfied = 0;
356
olka3c747662017-08-17 06:50:32 -0700357 // kOfferToReceiveAudio defaults to true according to spec.
358 if (!FindConstraint(constraints,
359 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
360 &mandatory_constraints_satisfied) ||
361 value) {
362 session_options->recv_audio = true;
zhihuanga77e6bb2017-08-14 18:17:48 -0700363 }
364
olka3c747662017-08-17 06:50:32 -0700365 // kOfferToReceiveVideo defaults to false according to spec. But
366 // if it is an answer and video is offered, we should still accept video
367 // per default.
368 value = false;
369 if (!FindConstraint(constraints,
370 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
371 &mandatory_constraints_satisfied) ||
372 value) {
373 session_options->recv_video = true;
zhihuanga77e6bb2017-08-14 18:17:48 -0700374 }
olka3c747662017-08-17 06:50:32 -0700375
zhihuanga77e6bb2017-08-14 18:17:48 -0700376 if (FindConstraint(constraints,
377 MediaConstraintsInterface::kVoiceActivityDetection, &value,
378 &mandatory_constraints_satisfied)) {
olka3c747662017-08-17 06:50:32 -0700379 session_options->vad_enabled = value;
zhihuanga77e6bb2017-08-14 18:17:48 -0700380 }
381
olka3c747662017-08-17 06:50:32 -0700382 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
383 &mandatory_constraints_satisfied)) {
384 session_options->bundle_enabled = value;
385 } else {
386 // kUseRtpMux defaults to true according to spec.
387 session_options->bundle_enabled = true;
388 }
389
390 bool ice_restart = false;
391 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
392 &value, &mandatory_constraints_satisfied)) {
393 // kIceRestart defaults to false according to spec.
394 ice_restart = true;
395 }
396 for (auto& kv : session_options->transport_options) {
397 kv.second.ice_restart = ice_restart;
398 }
399
400 if (!constraints) {
401 return true;
402 }
deadbeefab9b2d12015-10-14 11:33:11 -0700403 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
404}
405
zhihuang38ede132017-06-15 12:52:32 -0700406PeerConnection::PeerConnection(PeerConnectionFactory* factory,
407 std::unique_ptr<RtcEventLog> event_log,
408 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000409 : factory_(factory),
410 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000411 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700412 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000413 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000414 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700415 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700416 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700417 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700418 remote_streams_(StreamCollection::Create()),
419 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000420
421PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100422 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700423 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700424 // Need to detach RTP senders/receivers from WebRtcSession,
425 // since it's about to be destroyed.
426 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700427 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700428 }
429 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700430 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700431 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700432 // Destroy stats_ because it depends on session_.
433 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800434 if (stats_collector_) {
435 stats_collector_->WaitForPendingRequest();
436 stats_collector_ = nullptr;
437 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700438 // Now destroy session_ before destroying other members,
439 // because its destruction fires signals (such as VoiceChannelDestroyed)
440 // which will trigger some final actions in PeerConnection...
441 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700442 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700443 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700444 [this] { port_allocator_.reset(); });
445 // call_ must be destroyed on the worker thread.
446 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
447 [this] { call_.reset(); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000448}
449
450bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000451 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700452 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200453 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800454 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100455 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700456
457 RTCError config_error = ValidateConfiguration(configuration);
458 if (!config_error.ok()) {
459 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
460 return false;
461 }
462
deadbeef293e9262017-01-11 12:28:30 -0800463 if (!allocator) {
464 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
465 << "This shouldn't happen if using PeerConnectionFactory.";
466 return false;
467 }
deadbeef653b8e02015-11-11 12:55:10 -0800468 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800469 // TODO(deadbeef): Why do we do this?
470 LOG(LS_ERROR) << "PeerConnection initialized without a "
471 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800472 return false;
473 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000474 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800475 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800476
deadbeef91dd5672016-05-18 16:55:30 -0700477 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700478 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700479 if (!network_thread()->Invoke<bool>(
480 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
481 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000482 return false;
483 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000484
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000485
zhihuang29ff8442016-07-27 11:07:25 -0700486 session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700487 call_.get(), factory_->channel_manager(), configuration.media_config,
488 event_log_.get(),
489 factory_->network_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700490 factory_->worker_thread(), factory_->signaling_thread(),
491 port_allocator_.get(),
492 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700493 factory_->CreateTransportController(
494 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800495 configuration.redetermine_role_on_ice_restart)),
496#ifdef HAVE_SCTP
497 std::unique_ptr<cricket::SctpTransportInternalFactory>(
498 new cricket::SctpTransportFactory(factory_->network_thread()))
499#else
500 nullptr
501#endif
502 ));
zhihuang29ff8442016-07-27 11:07:25 -0700503
deadbeefab9b2d12015-10-14 11:33:11 -0700504 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700505 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000506
507 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200508 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800509 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000510 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700511 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000512
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000513 // Register PeerConnection as receiver of local ice candidates.
514 // All the callbacks will be posted to the application from PeerConnection.
515 session_->RegisterIceObserver(this);
516 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700517 session_->SignalVoiceChannelCreated.connect(
518 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700519 session_->SignalVoiceChannelDestroyed.connect(
520 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700521 session_->SignalVideoChannelCreated.connect(
522 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700523 session_->SignalVideoChannelDestroyed.connect(
524 this, &PeerConnection::OnVideoChannelDestroyed);
525 session_->SignalDataChannelCreated.connect(
526 this, &PeerConnection::OnDataChannelCreated);
527 session_->SignalDataChannelDestroyed.connect(
528 this, &PeerConnection::OnDataChannelDestroyed);
529 session_->SignalDataChannelOpenMessage.connect(
530 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800531
532 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533 return true;
534}
535
Steve Anton038834f2017-07-14 15:59:59 -0700536RTCError PeerConnection::ValidateConfiguration(
537 const RTCConfiguration& config) const {
538 if (config.ice_regather_interval_range &&
539 config.continual_gathering_policy == GATHER_ONCE) {
540 return RTCError(RTCErrorType::INVALID_PARAMETER,
541 "ice_regather_interval_range specified but continual "
542 "gathering policy is GATHER_ONCE");
543 }
544 return RTCError::OK();
545}
546
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000547rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000548PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700549 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000550}
551
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000552rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000553PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700554 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000555}
556
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000557bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100558 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000559 if (IsClosed()) {
560 return false;
561 }
deadbeefab9b2d12015-10-14 11:33:11 -0700562 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000563 return false;
564 }
deadbeefab9b2d12015-10-14 11:33:11 -0700565
566 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800567 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
568 observer->SignalAudioTrackAdded.connect(this,
569 &PeerConnection::OnAudioTrackAdded);
570 observer->SignalAudioTrackRemoved.connect(
571 this, &PeerConnection::OnAudioTrackRemoved);
572 observer->SignalVideoTrackAdded.connect(this,
573 &PeerConnection::OnVideoTrackAdded);
574 observer->SignalVideoTrackRemoved.connect(
575 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700576 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700577
deadbeefab9b2d12015-10-14 11:33:11 -0700578 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700579 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700580 }
581 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700582 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700583 }
584
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000585 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586 observer_->OnRenegotiationNeeded();
587 return true;
588}
589
590void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100591 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700592 if (!IsClosed()) {
593 for (const auto& track : local_stream->GetAudioTracks()) {
594 RemoveAudioTrack(track.get(), local_stream);
595 }
596 for (const auto& track : local_stream->GetVideoTracks()) {
597 RemoveVideoTrack(track.get(), local_stream);
598 }
deadbeefab9b2d12015-10-14 11:33:11 -0700599 }
deadbeefab9b2d12015-10-14 11:33:11 -0700600 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800601 stream_observers_.erase(
602 std::remove_if(
603 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700604 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800605 return observer->stream()->label().compare(local_stream->label()) ==
606 0;
607 }),
608 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700609
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 if (IsClosed()) {
611 return;
612 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613 observer_->OnRenegotiationNeeded();
614}
615
deadbeefe1f9d832016-01-14 15:35:42 -0800616rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
617 MediaStreamTrackInterface* track,
618 std::vector<MediaStreamInterface*> streams) {
619 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
620 if (IsClosed()) {
621 return nullptr;
622 }
623 if (streams.size() >= 2) {
624 LOG(LS_ERROR)
625 << "Adding a track with two streams is not currently supported.";
626 return nullptr;
627 }
628 // TODO(deadbeef): Support adding a track to two different senders.
629 if (FindSenderForTrack(track) != senders_.end()) {
630 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
631 return nullptr;
632 }
633
634 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700635 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800636 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700637 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800638 signaling_thread(),
639 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700640 session_->voice_channel(), stats_.get()));
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_audio_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 if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700650 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800651 signaling_thread(),
652 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700653 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800654 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700655 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800656 }
657 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700658 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800659 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700660 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800661 }
662 } else {
663 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
664 return rtc::scoped_refptr<RtpSenderInterface>();
665 }
666
667 senders_.push_back(new_sender);
668 observer_->OnRenegotiationNeeded();
669 return new_sender;
670}
671
672bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
673 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
674 if (IsClosed()) {
675 return false;
676 }
677
678 auto it = std::find(senders_.begin(), senders_.end(), sender);
679 if (it == senders_.end()) {
680 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
681 return false;
682 }
deadbeefa601f5c2016-06-06 14:27:39 -0700683 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800684 senders_.erase(it);
685
686 observer_->OnRenegotiationNeeded();
687 return true;
688}
689
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000690rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100692 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700693 if (IsClosed()) {
694 return nullptr;
695 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696 if (!track) {
697 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800698 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 }
deadbeef20cb0c12017-02-01 20:27:00 -0800700 auto it = FindSenderForTrack(track);
701 if (it == senders_.end()) {
702 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
703 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 }
705
deadbeef20cb0c12017-02-01 20:27:00 -0800706 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707}
708
deadbeeffac06552015-11-25 11:26:01 -0800709rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800710 const std::string& kind,
711 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100712 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700713 if (IsClosed()) {
714 return nullptr;
715 }
deadbeefa601f5c2016-06-06 14:27:39 -0700716 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800717 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700718 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700719 signaling_thread(),
720 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800721 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700722 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700723 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800724 } else {
725 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800726 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800727 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800728 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700729 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800730 }
deadbeeffac06552015-11-25 11:26:01 -0800731 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800732 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800733}
734
deadbeef70ab1a12015-09-28 16:53:55 -0700735std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
736 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700737 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
738 for (const auto& sender : senders_) {
739 ret.push_back(sender.get());
740 }
741 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700742}
743
744std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
745PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700746 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
747 for (const auto& receiver : receivers_) {
748 ret.push_back(receiver.get());
749 }
750 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700751}
752
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000754 MediaStreamTrackInterface* track,
755 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100756 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700757 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800758 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000759 LOG(LS_ERROR) << "GetStats - observer is NULL.";
760 return false;
761 }
762
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000763 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700764 // The StatsCollector is used to tell if a track is valid because it may
765 // remember tracks that the PeerConnection previously removed.
766 if (track && !stats_->IsValidTrack(track->id())) {
767 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
768 << track->id();
769 return false;
770 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700771 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000772 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000773 return true;
774}
775
hbos74e1a4f2016-09-15 23:33:01 -0700776void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
777 RTC_DCHECK(stats_collector_);
778 stats_collector_->GetStatsReport(callback);
779}
780
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000781PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
782 return signaling_state_;
783}
784
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785PeerConnectionInterface::IceConnectionState
786PeerConnection::ice_connection_state() {
787 return ice_connection_state_;
788}
789
790PeerConnectionInterface::IceGatheringState
791PeerConnection::ice_gathering_state() {
792 return ice_gathering_state_;
793}
794
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000795rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796PeerConnection::CreateDataChannel(
797 const std::string& label,
798 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100799 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700800#ifdef HAVE_QUIC
801 if (session_->data_channel_type() == cricket::DCT_QUIC) {
802 // TODO(zhihuang): Handle case when config is NULL.
803 if (!config) {
804 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
805 return nullptr;
806 }
807 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
808 if (!config->reliable || config->ordered) {
809 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
810 "ordered delivery.";
811 return nullptr;
812 }
813 return session_->quic_data_transport()->CreateDataChannel(label, config);
814 }
815#endif // HAVE_QUIC
816
deadbeefab9b2d12015-10-14 11:33:11 -0700817 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000818
kwibergd1fe2812016-04-27 06:47:29 -0700819 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000820 if (config) {
821 internal_config.reset(new InternalDataChannelInit(*config));
822 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000823 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700824 InternalCreateDataChannel(label, internal_config.get()));
825 if (!channel.get()) {
826 return nullptr;
827 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000829 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
830 // the first SCTP DataChannel.
831 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
832 observer_->OnRenegotiationNeeded();
833 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000834
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 return DataChannelProxy::Create(signaling_thread(), channel.get());
836}
837
838void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
839 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100840 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800841 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
843 return;
844 }
olka3c747662017-08-17 06:50:32 -0700845 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000846
olka3c747662017-08-17 06:50:32 -0700847 bool value;
848 size_t mandatory_constraints = 0;
849
850 if (FindConstraint(constraints,
851 MediaConstraintsInterface::kOfferToReceiveAudio,
852 &value,
853 &mandatory_constraints)) {
854 options.offer_to_receive_audio =
855 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
856 }
857
858 if (FindConstraint(constraints,
859 MediaConstraintsInterface::kOfferToReceiveVideo,
860 &value,
861 &mandatory_constraints)) {
862 options.offer_to_receive_video =
863 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
864 }
865
866 if (FindConstraint(constraints,
867 MediaConstraintsInterface::kVoiceActivityDetection,
868 &value,
869 &mandatory_constraints)) {
870 options.voice_activity_detection = value;
871 }
872
873 if (FindConstraint(constraints,
874 MediaConstraintsInterface::kIceRestart,
875 &value,
876 &mandatory_constraints)) {
877 options.ice_restart = value;
878 }
879
880 if (FindConstraint(constraints,
881 MediaConstraintsInterface::kUseRtpMux,
882 &value,
883 &mandatory_constraints)) {
884 options.use_rtp_mux = value;
885 }
886
887 CreateOffer(observer, options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000888}
889
890void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
891 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100892 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800893 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000894 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
895 return;
896 }
deadbeefab9b2d12015-10-14 11:33:11 -0700897
olka3c747662017-08-17 06:50:32 -0700898 cricket::MediaSessionOptions session_options;
899 if (!GetOptionsForOffer(options, &session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700900 std::string error = "CreateOffer called with invalid options.";
901 LOG(LS_ERROR) << error;
902 PostCreateSessionDescriptionFailure(observer, error);
903 return;
904 }
905
906 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907}
908
909void PeerConnection::CreateAnswer(
910 CreateSessionDescriptionObserver* observer,
911 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100912 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800913 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
915 return;
916 }
deadbeefab9b2d12015-10-14 11:33:11 -0700917
olka3c747662017-08-17 06:50:32 -0700918 cricket::MediaSessionOptions session_options;
919 if (!GetOptionsForAnswer(constraints, &session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700920 std::string error = "CreateAnswer called with invalid constraints.";
921 LOG(LS_ERROR) << error;
922 PostCreateSessionDescriptionFailure(observer, error);
923 return;
924 }
925
htaa2a49d92016-03-04 02:51:39 -0800926 session_->CreateAnswer(observer, session_options);
927}
928
929void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
930 const RTCOfferAnswerOptions& options) {
931 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800932 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800933 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
934 return;
935 }
936
937 cricket::MediaSessionOptions session_options;
olka3c747662017-08-17 06:50:32 -0700938 if (!GetOptionsForAnswer(options, &session_options)) {
939 std::string error = "CreateAnswer called with invalid options.";
940 LOG(LS_ERROR) << error;
941 PostCreateSessionDescriptionFailure(observer, error);
942 return;
943 }
htaa2a49d92016-03-04 02:51:39 -0800944
945 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946}
947
948void PeerConnection::SetLocalDescription(
949 SetSessionDescriptionObserver* observer,
950 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100951 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700952 if (IsClosed()) {
953 return;
954 }
nisse7ce109a2017-01-31 00:57:56 -0800955 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
957 return;
958 }
959 if (!desc) {
960 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
961 return;
962 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 // Update stats here so that we have the most recent stats for tracks and
964 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000965 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000966 std::string error;
967 if (!session_->SetLocalDescription(desc, &error)) {
968 PostSetSessionDescriptionFailure(observer, error);
969 return;
970 }
deadbeefab9b2d12015-10-14 11:33:11 -0700971
972 // If setting the description decided our SSL role, allocate any necessary
973 // SCTP sids.
974 rtc::SSLRole role;
975 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800976 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700977 AllocateSctpSids(role);
978 }
979
980 // Update state and SSRC of local MediaStreams and DataChannels based on the
981 // local session description.
982 const cricket::ContentInfo* audio_content =
983 GetFirstAudioContent(desc->description());
984 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800985 if (audio_content->rejected) {
986 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
987 } else {
988 const cricket::AudioContentDescription* audio_desc =
989 static_cast<const cricket::AudioContentDescription*>(
990 audio_content->description);
991 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
992 }
deadbeefab9b2d12015-10-14 11:33:11 -0700993 }
994
995 const cricket::ContentInfo* video_content =
996 GetFirstVideoContent(desc->description());
997 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800998 if (video_content->rejected) {
999 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1000 } else {
1001 const cricket::VideoContentDescription* video_desc =
1002 static_cast<const cricket::VideoContentDescription*>(
1003 video_content->description);
1004 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1005 }
deadbeefab9b2d12015-10-14 11:33:11 -07001006 }
1007
1008 const cricket::ContentInfo* data_content =
1009 GetFirstDataContent(desc->description());
1010 if (data_content) {
1011 const cricket::DataContentDescription* data_desc =
1012 static_cast<const cricket::DataContentDescription*>(
1013 data_content->description);
1014 if (rtc::starts_with(data_desc->protocol().data(),
1015 cricket::kMediaProtocolRtpPrefix)) {
1016 UpdateLocalRtpDataChannels(data_desc->streams());
1017 }
1018 }
1019
1020 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001021 signaling_thread()->Post(RTC_FROM_HERE, this,
1022 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001023
deadbeef42a42632017-03-10 15:18:00 -08001024 // According to JSEP, after setLocalDescription, changing the candidate pool
1025 // size is not allowed, and changing the set of ICE servers will not result
1026 // in new candidates being gathered.
1027 port_allocator_->FreezeCandidatePool();
1028
deadbeefcbecd352015-09-23 11:50:27 -07001029 // MaybeStartGathering needs to be called after posting
1030 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1031 // before signaling that SetLocalDescription completed.
1032 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001033
1034 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1035 // TODO(deadbeef): We already had to hop to the network thread for
1036 // MaybeStartGathering...
1037 network_thread()->Invoke<void>(
1038 RTC_FROM_HERE,
1039 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1040 port_allocator_.get()));
1041 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042}
1043
1044void PeerConnection::SetRemoteDescription(
1045 SetSessionDescriptionObserver* observer,
1046 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001047 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001048 if (IsClosed()) {
1049 return;
1050 }
nisse7ce109a2017-01-31 00:57:56 -08001051 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1053 return;
1054 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001055 if (!desc) {
1056 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1057 return;
1058 }
1059 // Update stats here so that we have the most recent stats for tracks and
1060 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001061 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062 std::string error;
1063 if (!session_->SetRemoteDescription(desc, &error)) {
1064 PostSetSessionDescriptionFailure(observer, error);
1065 return;
1066 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067
deadbeefab9b2d12015-10-14 11:33:11 -07001068 // If setting the description decided our SSL role, allocate any necessary
1069 // SCTP sids.
1070 rtc::SSLRole role;
1071 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001072 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001073 AllocateSctpSids(role);
1074 }
1075
1076 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001077 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1078 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1079 const cricket::AudioContentDescription* audio_desc =
1080 GetFirstAudioContentDescription(remote_desc);
1081 const cricket::VideoContentDescription* video_desc =
1082 GetFirstVideoContentDescription(remote_desc);
1083 const cricket::DataContentDescription* data_desc =
1084 GetFirstDataContentDescription(remote_desc);
1085
1086 // Check if the descriptions include streams, just in case the peer supports
1087 // MSID, but doesn't indicate so with "a=msid-semantic".
1088 if (remote_desc->msid_supported() ||
1089 (audio_desc && !audio_desc->streams().empty()) ||
1090 (video_desc && !video_desc->streams().empty())) {
1091 remote_peer_supports_msid_ = true;
1092 }
deadbeefab9b2d12015-10-14 11:33:11 -07001093
1094 // We wait to signal new streams until we finish processing the description,
1095 // since only at that point will new streams have all their tracks.
1096 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1097
1098 // Find all audio rtp streams and create corresponding remote AudioTracks
1099 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001100 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001101 if (audio_content->rejected) {
1102 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1103 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001104 bool default_audio_track_needed =
1105 !remote_peer_supports_msid_ &&
1106 MediaContentDirectionHasSend(audio_desc->direction());
1107 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1108 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001109 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001110 }
deadbeefab9b2d12015-10-14 11:33:11 -07001111 }
1112
1113 // Find all video rtp streams and create corresponding remote VideoTracks
1114 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001115 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001116 if (video_content->rejected) {
1117 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1118 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001119 bool default_video_track_needed =
1120 !remote_peer_supports_msid_ &&
1121 MediaContentDirectionHasSend(video_desc->direction());
1122 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1123 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001124 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001125 }
deadbeefab9b2d12015-10-14 11:33:11 -07001126 }
1127
1128 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001129 if (data_desc) {
1130 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001131 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001132 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001133 }
1134 }
1135
1136 // Iterate new_streams and notify the observer about new MediaStreams.
1137 for (size_t i = 0; i < new_streams->count(); ++i) {
1138 MediaStreamInterface* new_stream = new_streams->at(i);
1139 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001140 observer_->OnAddStream(
1141 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001142 }
1143
deadbeefbda7e0b2015-12-08 17:13:40 -08001144 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001145
1146 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001147 signaling_thread()->Post(RTC_FROM_HERE, this,
1148 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001149
1150 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1151 // TODO(deadbeef): We already had to hop to the network thread for
1152 // MaybeStartGathering...
1153 network_thread()->Invoke<void>(
1154 RTC_FROM_HERE,
1155 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1156 port_allocator_.get()));
1157 }
deadbeeffc648b62015-10-13 16:42:33 -07001158}
1159
deadbeef46c73892016-11-16 19:42:04 -08001160PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1161 return configuration_;
1162}
1163
deadbeef293e9262017-01-11 12:28:30 -08001164bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1165 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001166 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001167
1168 if (session_->local_description() &&
1169 configuration.ice_candidate_pool_size !=
1170 configuration_.ice_candidate_pool_size) {
1171 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1172 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001173 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001174 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001175
deadbeef293e9262017-01-11 12:28:30 -08001176 // The simplest (and most future-compatible) way to tell if the config was
1177 // modified in an invalid way is to copy each property we do support
1178 // modifying, then use operator==. There are far more properties we don't
1179 // support modifying than those we do, and more could be added.
1180 RTCConfiguration modified_config = configuration_;
1181 modified_config.servers = configuration.servers;
1182 modified_config.type = configuration.type;
1183 modified_config.ice_candidate_pool_size =
1184 configuration.ice_candidate_pool_size;
1185 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001186 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001187 if (configuration != modified_config) {
1188 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1189 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1190 }
1191
Steve Anton038834f2017-07-14 15:59:59 -07001192 // Validate the modified configuration.
1193 RTCError validate_error = ValidateConfiguration(modified_config);
1194 if (!validate_error.ok()) {
1195 return SafeSetError(std::move(validate_error), error);
1196 }
1197
deadbeef293e9262017-01-11 12:28:30 -08001198 // Note that this isn't possible through chromium, since it's an unsigned
1199 // short in WebIDL.
1200 if (configuration.ice_candidate_pool_size < 0 ||
1201 configuration.ice_candidate_pool_size > UINT16_MAX) {
1202 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1203 }
1204
1205 // Parse ICE servers before hopping to network thread.
1206 cricket::ServerAddresses stun_servers;
1207 std::vector<cricket::RelayServerConfig> turn_servers;
1208 RTCErrorType parse_error =
1209 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1210 if (parse_error != RTCErrorType::NONE) {
1211 return SafeSetError(parse_error, error);
1212 }
1213
1214 // In theory this shouldn't fail.
1215 if (!network_thread()->Invoke<bool>(
1216 RTC_FROM_HERE,
1217 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1218 stun_servers, turn_servers, modified_config.type,
1219 modified_config.ice_candidate_pool_size,
1220 modified_config.prune_turn_ports))) {
1221 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1222 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1223 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001224
deadbeefd1a38b52016-12-10 13:15:33 -08001225 // As described in JSEP, calling setConfiguration with new ICE servers or
1226 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1227 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001228 if (modified_config.servers != configuration_.servers ||
1229 modified_config.type != configuration_.type ||
1230 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001231 session_->SetNeedsIceRestartFlag();
1232 }
skvladd1f5fda2017-02-03 16:54:05 -08001233
1234 if (modified_config.ice_check_min_interval !=
1235 configuration_.ice_check_min_interval) {
1236 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1237 }
1238
deadbeef293e9262017-01-11 12:28:30 -08001239 configuration_ = modified_config;
1240 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001241}
1242
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243bool PeerConnection::AddIceCandidate(
1244 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001245 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001246 if (IsClosed()) {
1247 return false;
1248 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001249 return session_->ProcessIceMessage(ice_candidate);
1250}
1251
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001252bool PeerConnection::RemoveIceCandidates(
1253 const std::vector<cricket::Candidate>& candidates) {
1254 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1255 return session_->RemoveRemoteIceCandidates(candidates);
1256}
1257
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001258void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001259 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001260 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001261
1262 if (session_) {
1263 session_->set_metrics_observer(uma_observer_);
1264 }
1265
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001266 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001267 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001268 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001269 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001270 uma_observer_->IncrementEnumCounter(
1271 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1272 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001273 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001274 uma_observer_->IncrementEnumCounter(
1275 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1276 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001277 }
1278 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001279}
1280
zstein4b979802017-06-02 14:37:37 -07001281RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
1282 rtc::Thread* worker_thread = factory_->worker_thread();
1283 if (!worker_thread->IsCurrent()) {
1284 return worker_thread->Invoke<RTCError>(
1285 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1286 }
1287
1288 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1289 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1290 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1291 if (has_min && *bitrate.min_bitrate_bps < 0) {
1292 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1293 "min_bitrate_bps <= 0");
1294 }
1295 if (has_current) {
1296 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1298 "current_bitrate_bps < min_bitrate_bps");
1299 } else if (*bitrate.current_bitrate_bps < 0) {
1300 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1301 "curent_bitrate_bps < 0");
1302 }
1303 }
1304 if (has_max) {
1305 if (has_current &&
1306 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1308 "max_bitrate_bps < current_bitrate_bps");
1309 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1310 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1311 "max_bitrate_bps < min_bitrate_bps");
1312 } else if (*bitrate.max_bitrate_bps < 0) {
1313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1314 "max_bitrate_bps < 0");
1315 }
1316 }
1317
1318 Call::Config::BitrateConfigMask mask;
1319 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1320 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1321 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1322
1323 RTC_DCHECK(call_.get());
1324 call_->SetBitrateConfigMask(mask);
1325
1326 return RTCError::OK();
1327}
1328
ivoc14d5dbe2016-07-04 07:06:55 -07001329bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1330 int64_t max_size_bytes) {
1331 return factory_->worker_thread()->Invoke<bool>(
1332 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1333 max_size_bytes));
1334}
1335
1336void PeerConnection::StopRtcEventLog() {
1337 factory_->worker_thread()->Invoke<void>(
1338 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1339}
1340
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001341const SessionDescriptionInterface* PeerConnection::local_description() const {
1342 return session_->local_description();
1343}
1344
1345const SessionDescriptionInterface* PeerConnection::remote_description() const {
1346 return session_->remote_description();
1347}
1348
deadbeeffe4a8a42016-12-20 17:56:17 -08001349const SessionDescriptionInterface* PeerConnection::current_local_description()
1350 const {
1351 return session_->current_local_description();
1352}
1353
1354const SessionDescriptionInterface* PeerConnection::current_remote_description()
1355 const {
1356 return session_->current_remote_description();
1357}
1358
1359const SessionDescriptionInterface* PeerConnection::pending_local_description()
1360 const {
1361 return session_->pending_local_description();
1362}
1363
1364const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1365 const {
1366 return session_->pending_remote_description();
1367}
1368
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001370 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371 // Update stats here so that we have the most recent stats for tracks and
1372 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001373 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374
deadbeefd59daf82015-10-14 15:02:44 -07001375 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001376 network_thread()->Invoke<void>(
1377 RTC_FROM_HERE,
1378 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1379 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001380
1381 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
1382 [this] { call_.reset(); });
terelius33860252017-05-12 23:37:18 -07001383
1384 // The event log must outlive call (and any other object that uses it).
1385 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386}
1387
deadbeefd59daf82015-10-14 15:02:44 -07001388void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1389 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001391 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001393 break;
deadbeefd59daf82015-10-14 15:02:44 -07001394 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1396 break;
deadbeefd59daf82015-10-14 15:02:44 -07001397 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1399 break;
deadbeefd59daf82015-10-14 15:02:44 -07001400 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1402 break;
deadbeefd59daf82015-10-14 15:02:44 -07001403 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1405 break;
deadbeefd59daf82015-10-14 15:02:44 -07001406 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 ChangeSignalingState(PeerConnectionInterface::kStable);
1408 break;
deadbeefd59daf82015-10-14 15:02:44 -07001409 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410 ChangeSignalingState(PeerConnectionInterface::kClosed);
1411 break;
1412 default:
1413 break;
1414 }
1415}
1416
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001417void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001418 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001419 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1420 SetSessionDescriptionMsg* param =
1421 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1422 param->observer->OnSuccess();
1423 delete param;
1424 break;
1425 }
1426 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1427 SetSessionDescriptionMsg* param =
1428 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1429 param->observer->OnFailure(param->error);
1430 delete param;
1431 break;
1432 }
deadbeefab9b2d12015-10-14 11:33:11 -07001433 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1434 CreateSessionDescriptionMsg* param =
1435 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1436 param->observer->OnFailure(param->error);
1437 delete param;
1438 break;
1439 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 case MSG_GETSTATS: {
1441 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001442 StatsReports reports;
1443 stats_->GetStats(param->track, &reports);
1444 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445 delete param;
1446 break;
1447 }
deadbeefbd292462015-12-14 18:15:29 -08001448 case MSG_FREE_DATACHANNELS: {
1449 sctp_data_channels_to_free_.clear();
1450 break;
1451 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001453 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454 break;
1455 }
1456}
1457
deadbeefab9b2d12015-10-14 11:33:11 -07001458void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001459 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001460 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001461 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1462 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001463 signaling_thread(),
1464 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1465 stream->AddTrack(
1466 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001467 receivers_.push_back(receiver);
1468 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1469 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1470 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471}
1472
deadbeefab9b2d12015-10-14 11:33:11 -07001473void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001474 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001475 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001476 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1477 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001478 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001479 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1480 session_->video_channel()));
1481 stream->AddTrack(
1482 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001483 receivers_.push_back(receiver);
1484 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1485 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1486 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487}
1488
deadbeef70ab1a12015-09-28 16:53:55 -07001489// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1490// description.
perkjd61bf802016-03-24 03:16:19 -07001491void PeerConnection::DestroyReceiver(const std::string& track_id) {
1492 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001493 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001494 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001495 << " doesn't exist.";
1496 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001497 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001498 receivers_.erase(it);
1499 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001500}
1501
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001502void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1503 MediaStreamInterface* stream) {
1504 RTC_DCHECK(!IsClosed());
1505 auto sender = FindSenderForTrack(track);
1506 if (sender != senders_.end()) {
1507 // We already have a sender for this track, so just change the stream_id
1508 // so that it's correct in the next call to CreateOffer.
1509 (*sender)->internal()->set_stream_id(stream->label());
1510 return;
1511 }
1512
1513 // Normal case; we've never seen this track before.
1514 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1515 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1516 signaling_thread(),
1517 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1518 stats_.get()));
1519 senders_.push_back(new_sender);
1520 // If the sender has already been configured in SDP, we call SetSsrc,
1521 // which will connect the sender to the underlying transport. This can
1522 // occur if a local session description that contains the ID of the sender
1523 // is set before AddStream is called. It can also occur if the local
1524 // session description is not changed and RemoveStream is called, and
1525 // later AddStream is called again with the same stream.
1526 const TrackInfo* track_info =
1527 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1528 if (track_info) {
1529 new_sender->internal()->SetSsrc(track_info->ssrc);
1530 }
1531}
1532
1533// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1534// indefinitely, when we have unified plan SDP.
1535void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1536 MediaStreamInterface* stream) {
1537 RTC_DCHECK(!IsClosed());
1538 auto sender = FindSenderForTrack(track);
1539 if (sender == senders_.end()) {
1540 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1541 << " doesn't exist.";
1542 return;
1543 }
1544 (*sender)->internal()->Stop();
1545 senders_.erase(sender);
1546}
1547
1548void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1549 MediaStreamInterface* stream) {
1550 RTC_DCHECK(!IsClosed());
1551 auto sender = FindSenderForTrack(track);
1552 if (sender != senders_.end()) {
1553 // We already have a sender for this track, so just change the stream_id
1554 // so that it's correct in the next call to CreateOffer.
1555 (*sender)->internal()->set_stream_id(stream->label());
1556 return;
1557 }
1558
1559 // Normal case; we've never seen this track before.
1560 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1561 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1562 signaling_thread(), new VideoRtpSender(track, stream->label(),
1563 session_->video_channel()));
1564 senders_.push_back(new_sender);
1565 const TrackInfo* track_info =
1566 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1567 if (track_info) {
1568 new_sender->internal()->SetSsrc(track_info->ssrc);
1569 }
1570}
1571
1572void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1573 MediaStreamInterface* stream) {
1574 RTC_DCHECK(!IsClosed());
1575 auto sender = FindSenderForTrack(track);
1576 if (sender == senders_.end()) {
1577 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1578 << " doesn't exist.";
1579 return;
1580 }
1581 (*sender)->internal()->Stop();
1582 senders_.erase(sender);
1583}
1584
zstein6dfd53a2017-03-06 13:49:03 -08001585void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001587 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001588 // After transitioning to "closed", ignore any additional states from
1589 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001590 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001591 return;
1592 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001593 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001594 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001595}
1596
1597void PeerConnection::OnIceGatheringChange(
1598 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001599 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600 if (IsClosed()) {
1601 return;
1602 }
1603 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001604 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001605}
1606
jbauch81bf7b02017-03-25 08:31:12 -07001607void PeerConnection::OnIceCandidate(
1608 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001609 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001610 if (IsClosed()) {
1611 return;
1612 }
jbauch81bf7b02017-03-25 08:31:12 -07001613 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001614}
1615
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001616void PeerConnection::OnIceCandidatesRemoved(
1617 const std::vector<cricket::Candidate>& candidates) {
1618 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001619 if (IsClosed()) {
1620 return;
1621 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001622 observer_->OnIceCandidatesRemoved(candidates);
1623}
1624
Peter Thatcher54360512015-07-08 11:08:35 -07001625void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001626 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001627 if (IsClosed()) {
1628 return;
1629 }
Peter Thatcher54360512015-07-08 11:08:35 -07001630 observer_->OnIceConnectionReceivingChange(receiving);
1631}
1632
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001633void PeerConnection::ChangeSignalingState(
1634 PeerConnectionInterface::SignalingState signaling_state) {
1635 signaling_state_ = signaling_state;
1636 if (signaling_state == kClosed) {
1637 ice_connection_state_ = kIceConnectionClosed;
1638 observer_->OnIceConnectionChange(ice_connection_state_);
1639 if (ice_gathering_state_ != kIceGatheringComplete) {
1640 ice_gathering_state_ = kIceGatheringComplete;
1641 observer_->OnIceGatheringChange(ice_gathering_state_);
1642 }
1643 }
1644 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645}
1646
deadbeefeb459812015-12-15 19:24:43 -08001647void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1648 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001649 if (IsClosed()) {
1650 return;
1651 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001652 AddAudioTrack(track, stream);
1653 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001654}
1655
deadbeefeb459812015-12-15 19:24:43 -08001656void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1657 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001658 if (IsClosed()) {
1659 return;
1660 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001661 RemoveAudioTrack(track, stream);
1662 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001663}
1664
1665void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1666 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001667 if (IsClosed()) {
1668 return;
1669 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001670 AddVideoTrack(track, stream);
1671 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001672}
1673
1674void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1675 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001676 if (IsClosed()) {
1677 return;
1678 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001679 RemoveVideoTrack(track, stream);
1680 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001681}
1682
deadbeefab9b2d12015-10-14 11:33:11 -07001683void PeerConnection::PostSetSessionDescriptionFailure(
1684 SetSessionDescriptionObserver* observer,
1685 const std::string& error) {
1686 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1687 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001688 signaling_thread()->Post(RTC_FROM_HERE, this,
1689 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001690}
1691
1692void PeerConnection::PostCreateSessionDescriptionFailure(
1693 CreateSessionDescriptionObserver* observer,
1694 const std::string& error) {
1695 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1696 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001697 signaling_thread()->Post(RTC_FROM_HERE, this,
1698 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001699}
1700
olka3c747662017-08-17 06:50:32 -07001701bool PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001702 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1703 cricket::MediaSessionOptions* session_options) {
olka3c747662017-08-17 06:50:32 -07001704 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1705 // ContentInfos.
deadbeef0ed85b22016-02-23 17:24:52 -08001706 if (session_->local_description()) {
olka3c747662017-08-17 06:50:32 -07001707 for (const cricket::ContentInfo& content :
1708 session_->local_description()->description()->contents()) {
1709 session_options->transport_options[content.name] =
1710 cricket::TransportOptions();
1711 }
1712 }
1713 session_options->enable_ice_renomination =
1714 configuration_.enable_ice_renomination;
1715
1716 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
1717 return false;
deadbeefab9b2d12015-10-14 11:33:11 -07001718 }
1719
olka3c747662017-08-17 06:50:32 -07001720 AddSendStreams(session_options, senders_, rtp_data_channels_);
1721 // Offer to receive audio/video if the constraint is not set and there are
1722 // send streams, or we're currently receiving.
1723 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1724 session_options->recv_audio =
1725 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1726 !remote_audio_tracks_.empty();
deadbeefc80741f2015-10-22 13:14:45 -07001727 }
olka3c747662017-08-17 06:50:32 -07001728 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1729 session_options->recv_video =
1730 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1731 !remote_video_tracks_.empty();
deadbeefc80741f2015-10-22 13:14:45 -07001732 }
deadbeefc80741f2015-10-22 13:14:45 -07001733
zhihuang9763d562016-08-05 11:14:50 -07001734 // Intentionally unset the data channel type for RTP data channel with the
1735 // second condition. Otherwise the RTP data channels would be successfully
1736 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1737 // when building with chromium. We want to leave RTP data channels broken, so
1738 // people won't try to use them.
olka3c747662017-08-17 06:50:32 -07001739 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001740 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001741 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001742
olka3c747662017-08-17 06:50:32 -07001743 session_options->bundle_enabled =
1744 session_options->bundle_enabled &&
1745 (session_options->has_audio() || session_options->has_video() ||
1746 session_options->has_data());
1747
zhihuang8f65cdf2016-05-06 18:40:30 -07001748 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001749 session_options->crypto_options = factory_->options().crypto_options;
olka3c747662017-08-17 06:50:32 -07001750 return true;
deadbeefab9b2d12015-10-14 11:33:11 -07001751}
1752
olka3c747662017-08-17 06:50:32 -07001753void PeerConnection::InitializeOptionsForAnswer(
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001754 cricket::MediaSessionOptions* session_options) {
olka3c747662017-08-17 06:50:32 -07001755 session_options->recv_audio = false;
1756 session_options->recv_video = false;
1757 session_options->enable_ice_renomination =
1758 configuration_.enable_ice_renomination;
1759}
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001760
olka3c747662017-08-17 06:50:32 -07001761void PeerConnection::FinishOptionsForAnswer(
1762 cricket::MediaSessionOptions* session_options) {
1763 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1764 // ContentInfos.
1765 if (session_->remote_description()) {
1766 // Initialize the transport_options map.
1767 for (const cricket::ContentInfo& content :
1768 session_->remote_description()->description()->contents()) {
1769 session_options->transport_options[content.name] =
1770 cricket::TransportOptions();
1771 }
deadbeef0ed85b22016-02-23 17:24:52 -08001772 }
olka3c747662017-08-17 06:50:32 -07001773 AddSendStreams(session_options, senders_, rtp_data_channels_);
1774 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1775 // are not signaled in the SDP so does not go through that path and must be
1776 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001777 // Intentionally unset the data channel type for RTP data channel. Otherwise
1778 // the RTP data channels would be successfully negotiated by default and the
1779 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1780 // We want to leave RTP data channels broken, so people won't try to use them.
olka3c747662017-08-17 06:50:32 -07001781 if (session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001782 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001783 }
olka3c747662017-08-17 06:50:32 -07001784 session_options->bundle_enabled =
1785 session_options->bundle_enabled &&
1786 (session_options->has_audio() || session_options->has_video() ||
1787 session_options->has_data());
zhihuangaf388472016-11-02 16:49:48 -07001788
jbauchcb560652016-08-04 05:20:32 -07001789 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001790}
1791
olka3c747662017-08-17 06:50:32 -07001792bool PeerConnection::GetOptionsForAnswer(
1793 const MediaConstraintsInterface* constraints,
htaa2a49d92016-03-04 02:51:39 -08001794 cricket::MediaSessionOptions* session_options) {
olka3c747662017-08-17 06:50:32 -07001795 InitializeOptionsForAnswer(session_options);
1796 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1797 return false;
htaa2a49d92016-03-04 02:51:39 -08001798 }
olka3c747662017-08-17 06:50:32 -07001799 session_options->rtcp_cname = rtcp_cname_;
1800
1801 FinishOptionsForAnswer(session_options);
1802 return true;
1803}
1804
1805bool PeerConnection::GetOptionsForAnswer(
1806 const RTCOfferAnswerOptions& options,
1807 cricket::MediaSessionOptions* session_options) {
1808 InitializeOptionsForAnswer(session_options);
1809 if (!ExtractMediaSessionOptions(options, false, session_options)) {
1810 return false;
1811 }
1812 session_options->rtcp_cname = rtcp_cname_;
1813
1814 FinishOptionsForAnswer(session_options);
1815 return true;
deadbeefab9b2d12015-10-14 11:33:11 -07001816}
1817
deadbeeffaac4972015-11-12 15:33:07 -08001818void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1819 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001820 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1821 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001822}
1823
deadbeefab9b2d12015-10-14 11:33:11 -07001824void PeerConnection::UpdateRemoteStreamsList(
1825 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001826 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001827 cricket::MediaType media_type,
1828 StreamCollection* new_streams) {
1829 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1830
1831 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001832 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001833 auto track_it = current_tracks->begin();
1834 while (track_it != current_tracks->end()) {
1835 const TrackInfo& info = *track_it;
1836 const cricket::StreamParams* params =
1837 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001838 bool track_exists = params && params->id == info.track_id;
1839 // If this is a default track, and we still need it, don't remove it.
1840 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1841 track_exists) {
1842 ++track_it;
1843 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001844 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1845 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001846 }
1847 }
1848
1849 // Find new and active tracks.
1850 for (const cricket::StreamParams& params : streams) {
1851 // The sync_label is the MediaStream label and the |stream.id| is the
1852 // track id.
1853 const std::string& stream_label = params.sync_label;
1854 const std::string& track_id = params.id;
1855 uint32_t ssrc = params.first_ssrc();
1856
1857 rtc::scoped_refptr<MediaStreamInterface> stream =
1858 remote_streams_->find(stream_label);
1859 if (!stream) {
1860 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001861 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1862 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001863 remote_streams_->AddStream(stream);
1864 new_streams->AddStream(stream);
1865 }
1866
1867 const TrackInfo* track_info =
1868 FindTrackInfo(*current_tracks, stream_label, track_id);
1869 if (!track_info) {
1870 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1871 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1872 }
1873 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001874
1875 // Add default track if necessary.
1876 if (default_track_needed) {
1877 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1878 remote_streams_->find(kDefaultStreamLabel);
1879 if (!default_stream) {
1880 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001881 default_stream = MediaStreamProxy::Create(
1882 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001883 remote_streams_->AddStream(default_stream);
1884 new_streams->AddStream(default_stream);
1885 }
1886 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1887 ? kDefaultAudioTrackLabel
1888 : kDefaultVideoTrackLabel;
1889 const TrackInfo* default_track_info =
1890 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1891 if (!default_track_info) {
1892 current_tracks->push_back(
1893 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1894 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1895 }
1896 }
deadbeefab9b2d12015-10-14 11:33:11 -07001897}
1898
1899void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1900 const std::string& track_id,
1901 uint32_t ssrc,
1902 cricket::MediaType media_type) {
1903 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1904
1905 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001906 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001907 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001908 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001909 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001910 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001911 }
1912}
1913
1914void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1915 const std::string& track_id,
1916 cricket::MediaType media_type) {
1917 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1918
1919 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001920 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1921 // will be notified which will end the AudioRtpReceiver::track().
1922 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001923 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1924 stream->FindAudioTrack(track_id);
1925 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001926 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001927 }
1928 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001929 // Stopping or destroying a VideoRtpReceiver will end the
1930 // VideoRtpReceiver::track().
1931 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001932 rtc::scoped_refptr<VideoTrackInterface> video_track =
1933 stream->FindVideoTrack(track_id);
1934 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001935 // There's no guarantee the track is still available, e.g. the track may
1936 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001937 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001938 }
1939 } else {
nisseede5da42017-01-12 05:15:36 -08001940 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001941 }
1942}
1943
1944void PeerConnection::UpdateEndedRemoteMediaStreams() {
1945 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1946 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1947 MediaStreamInterface* stream = remote_streams_->at(i);
1948 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1949 streams_to_remove.push_back(stream);
1950 }
1951 }
1952
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001953 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001954 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001955 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001956 }
1957}
1958
deadbeefab9b2d12015-10-14 11:33:11 -07001959void PeerConnection::UpdateLocalTracks(
1960 const std::vector<cricket::StreamParams>& streams,
1961 cricket::MediaType media_type) {
1962 TrackInfos* current_tracks = GetLocalTracks(media_type);
1963
1964 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1965 // don't match the new StreamParam.
1966 TrackInfos::iterator track_it = current_tracks->begin();
1967 while (track_it != current_tracks->end()) {
1968 const TrackInfo& info = *track_it;
1969 const cricket::StreamParams* params =
1970 cricket::GetStreamBySsrc(streams, info.ssrc);
1971 if (!params || params->id != info.track_id ||
1972 params->sync_label != info.stream_label) {
1973 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1974 media_type);
1975 track_it = current_tracks->erase(track_it);
1976 } else {
1977 ++track_it;
1978 }
1979 }
1980
1981 // Find new and active tracks.
1982 for (const cricket::StreamParams& params : streams) {
1983 // The sync_label is the MediaStream label and the |stream.id| is the
1984 // track id.
1985 const std::string& stream_label = params.sync_label;
1986 const std::string& track_id = params.id;
1987 uint32_t ssrc = params.first_ssrc();
1988 const TrackInfo* track_info =
1989 FindTrackInfo(*current_tracks, stream_label, track_id);
1990 if (!track_info) {
1991 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1992 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1993 }
1994 }
1995}
1996
1997void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1998 const std::string& track_id,
1999 uint32_t ssrc,
2000 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002001 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002002 if (!sender) {
2003 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2004 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002005 return;
2006 }
2007
deadbeeffac06552015-11-25 11:26:01 -08002008 if (sender->media_type() != media_type) {
2009 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2010 << " description with an unexpected media type.";
2011 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002012 }
deadbeeffac06552015-11-25 11:26:01 -08002013
2014 sender->set_stream_id(stream_label);
2015 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002016}
2017
2018void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2019 const std::string& track_id,
2020 uint32_t ssrc,
2021 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002022 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002023 if (!sender) {
2024 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002025 // SessionDescriptions has been renegotiated.
2026 return;
2027 }
deadbeeffac06552015-11-25 11:26:01 -08002028
2029 // A sender has been removed from the SessionDescription but it's still
2030 // associated with the PeerConnection. This only occurs if the SDP doesn't
2031 // match with the calls to CreateSender, AddStream and RemoveStream.
2032 if (sender->media_type() != media_type) {
2033 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2034 << " description with an unexpected media type.";
2035 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002036 }
deadbeeffac06552015-11-25 11:26:01 -08002037
2038 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002039}
2040
2041void PeerConnection::UpdateLocalRtpDataChannels(
2042 const cricket::StreamParamsVec& streams) {
2043 std::vector<std::string> existing_channels;
2044
2045 // Find new and active data channels.
2046 for (const cricket::StreamParams& params : streams) {
2047 // |it->sync_label| is actually the data channel label. The reason is that
2048 // we use the same naming of data channels as we do for
2049 // MediaStreams and Tracks.
2050 // For MediaStreams, the sync_label is the MediaStream label and the
2051 // track label is the same as |streamid|.
2052 const std::string& channel_label = params.sync_label;
2053 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002054 if (data_channel_it == rtp_data_channels_.end()) {
2055 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002056 continue;
2057 }
2058 // Set the SSRC the data channel should use for sending.
2059 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2060 existing_channels.push_back(data_channel_it->first);
2061 }
2062
2063 UpdateClosingRtpDataChannels(existing_channels, true);
2064}
2065
2066void PeerConnection::UpdateRemoteRtpDataChannels(
2067 const cricket::StreamParamsVec& streams) {
2068 std::vector<std::string> existing_channels;
2069
2070 // Find new and active data channels.
2071 for (const cricket::StreamParams& params : streams) {
2072 // The data channel label is either the mslabel or the SSRC if the mslabel
2073 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2074 std::string label = params.sync_label.empty()
2075 ? rtc::ToString(params.first_ssrc())
2076 : params.sync_label;
2077 auto data_channel_it = rtp_data_channels_.find(label);
2078 if (data_channel_it == rtp_data_channels_.end()) {
2079 // This is a new data channel.
2080 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2081 } else {
2082 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2083 }
2084 existing_channels.push_back(label);
2085 }
2086
2087 UpdateClosingRtpDataChannels(existing_channels, false);
2088}
2089
2090void PeerConnection::UpdateClosingRtpDataChannels(
2091 const std::vector<std::string>& active_channels,
2092 bool is_local_update) {
2093 auto it = rtp_data_channels_.begin();
2094 while (it != rtp_data_channels_.end()) {
2095 DataChannel* data_channel = it->second;
2096 if (std::find(active_channels.begin(), active_channels.end(),
2097 data_channel->label()) != active_channels.end()) {
2098 ++it;
2099 continue;
2100 }
2101
2102 if (is_local_update) {
2103 data_channel->SetSendSsrc(0);
2104 } else {
2105 data_channel->RemotePeerRequestClose();
2106 }
2107
2108 if (data_channel->state() == DataChannel::kClosed) {
2109 rtp_data_channels_.erase(it);
2110 it = rtp_data_channels_.begin();
2111 } else {
2112 ++it;
2113 }
2114 }
2115}
2116
2117void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2118 uint32_t remote_ssrc) {
2119 rtc::scoped_refptr<DataChannel> channel(
2120 InternalCreateDataChannel(label, nullptr));
2121 if (!channel.get()) {
2122 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2123 << "CreateDataChannel failed.";
2124 return;
2125 }
2126 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002127 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2128 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002129 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002130}
2131
2132rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2133 const std::string& label,
2134 const InternalDataChannelInit* config) {
2135 if (IsClosed()) {
2136 return nullptr;
2137 }
2138 if (session_->data_channel_type() == cricket::DCT_NONE) {
2139 LOG(LS_ERROR)
2140 << "InternalCreateDataChannel: Data is not supported in this call.";
2141 return nullptr;
2142 }
2143 InternalDataChannelInit new_config =
2144 config ? (*config) : InternalDataChannelInit();
2145 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2146 if (new_config.id < 0) {
2147 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002148 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002149 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2150 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2151 return nullptr;
2152 }
2153 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2154 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2155 << "because the id is already in use or out of range.";
2156 return nullptr;
2157 }
2158 }
2159
2160 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2161 session_.get(), session_->data_channel_type(), label, new_config));
2162 if (!channel) {
2163 sid_allocator_.ReleaseSid(new_config.id);
2164 return nullptr;
2165 }
2166
2167 if (channel->data_channel_type() == cricket::DCT_RTP) {
2168 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2169 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2170 << " already exists.";
2171 return nullptr;
2172 }
2173 rtp_data_channels_[channel->label()] = channel;
2174 } else {
2175 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2176 sctp_data_channels_.push_back(channel);
2177 channel->SignalClosed.connect(this,
2178 &PeerConnection::OnSctpDataChannelClosed);
2179 }
2180
hbos82ebe022016-11-14 01:41:09 -08002181 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002182 return channel;
2183}
2184
2185bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002186#ifdef HAVE_QUIC
2187 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2188 (session_->quic_data_transport() &&
2189 session_->quic_data_transport()->HasDataChannels());
2190#else
deadbeefab9b2d12015-10-14 11:33:11 -07002191 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002192#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002193}
2194
2195void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2196 for (const auto& channel : sctp_data_channels_) {
2197 if (channel->id() < 0) {
2198 int sid;
2199 if (!sid_allocator_.AllocateSid(role, &sid)) {
2200 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2201 continue;
2202 }
2203 channel->SetSctpSid(sid);
2204 }
2205 }
2206}
2207
2208void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002209 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002210 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2211 ++it) {
2212 if (it->get() == channel) {
2213 if (channel->id() >= 0) {
2214 sid_allocator_.ReleaseSid(channel->id());
2215 }
deadbeefbd292462015-12-14 18:15:29 -08002216 // Since this method is triggered by a signal from the DataChannel,
2217 // we can't free it directly here; we need to free it asynchronously.
2218 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002219 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002220 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2221 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002222 return;
2223 }
2224 }
2225}
2226
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002227void PeerConnection::OnVoiceChannelCreated() {
2228 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2229 session_->voice_channel(), senders_, receivers_,
2230 cricket::MEDIA_TYPE_AUDIO);
2231}
2232
deadbeefab9b2d12015-10-14 11:33:11 -07002233void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002234 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2235 cricket::VoiceChannel>(
2236 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2237}
2238
2239void PeerConnection::OnVideoChannelCreated() {
2240 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2241 session_->video_channel(), senders_, receivers_,
2242 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002243}
2244
2245void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002246 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2247 cricket::VideoChannel>(
2248 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002249}
2250
2251void PeerConnection::OnDataChannelCreated() {
2252 for (const auto& channel : sctp_data_channels_) {
2253 channel->OnTransportChannelCreated();
2254 }
2255}
2256
2257void PeerConnection::OnDataChannelDestroyed() {
2258 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2259 // DataChannel may callback to us and try to modify the list.
2260 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2261 temp_rtp_dcs.swap(rtp_data_channels_);
2262 for (const auto& kv : temp_rtp_dcs) {
2263 kv.second->OnTransportChannelDestroyed();
2264 }
2265
2266 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2267 temp_sctp_dcs.swap(sctp_data_channels_);
2268 for (const auto& channel : temp_sctp_dcs) {
2269 channel->OnTransportChannelDestroyed();
2270 }
2271}
2272
2273void PeerConnection::OnDataChannelOpenMessage(
2274 const std::string& label,
2275 const InternalDataChannelInit& config) {
2276 rtc::scoped_refptr<DataChannel> channel(
2277 InternalCreateDataChannel(label, &config));
2278 if (!channel.get()) {
2279 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2280 return;
2281 }
2282
deadbeefa601f5c2016-06-06 14:27:39 -07002283 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2284 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002285 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002286}
2287
deadbeefa601f5c2016-06-06 14:27:39 -07002288RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2289 auto it = std::find_if(
2290 senders_.begin(), senders_.end(),
2291 [id](const rtc::scoped_refptr<
2292 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2293 return sender->id() == id;
2294 });
2295 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002296}
2297
deadbeefa601f5c2016-06-06 14:27:39 -07002298std::vector<
2299 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002300PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2301 return std::find_if(
2302 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002303 [track](const rtc::scoped_refptr<
2304 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002305 return sender->track() == track;
2306 });
2307}
2308
deadbeefa601f5c2016-06-06 14:27:39 -07002309std::vector<rtc::scoped_refptr<
2310 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002311PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002312 return std::find_if(
2313 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002314 [track_id](const rtc::scoped_refptr<
2315 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002316 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002317 });
2318}
2319
deadbeefab9b2d12015-10-14 11:33:11 -07002320PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2321 cricket::MediaType media_type) {
2322 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2323 media_type == cricket::MEDIA_TYPE_VIDEO);
2324 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2325 : &remote_video_tracks_;
2326}
2327
2328PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2329 cricket::MediaType media_type) {
2330 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2331 media_type == cricket::MEDIA_TYPE_VIDEO);
2332 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2333 : &local_video_tracks_;
2334}
2335
2336const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2337 const PeerConnection::TrackInfos& infos,
2338 const std::string& stream_label,
2339 const std::string track_id) const {
2340 for (const TrackInfo& track_info : infos) {
2341 if (track_info.stream_label == stream_label &&
2342 track_info.track_id == track_id) {
2343 return &track_info;
2344 }
2345 }
2346 return nullptr;
2347}
2348
2349DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2350 for (const auto& channel : sctp_data_channels_) {
2351 if (channel->id() == sid) {
2352 return channel;
2353 }
2354 }
2355 return nullptr;
2356}
2357
deadbeef91dd5672016-05-18 16:55:30 -07002358bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002359 const RTCConfiguration& configuration) {
2360 cricket::ServerAddresses stun_servers;
2361 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002362 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2363 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002364 return false;
2365 }
2366
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002367 port_allocator_->Initialize();
2368
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002369 // To handle both internal and externally created port allocator, we will
2370 // enable BUNDLE here.
2371 int portallocator_flags = port_allocator_->flags();
2372 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002373 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2374 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002375 // If the disable-IPv6 flag was specified, we'll not override it
2376 // by experiment.
2377 if (configuration.disable_ipv6) {
2378 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002379 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2380 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002381 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2382 }
2383
zhihuangb09b3f92017-03-07 14:40:51 -08002384 if (configuration.disable_ipv6_on_wifi) {
2385 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2386 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2387 }
2388
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002389 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2390 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2391 LOG(LS_INFO) << "TCP candidates are disabled.";
2392 }
2393
honghaiz60347052016-05-31 18:29:12 -07002394 if (configuration.candidate_network_policy ==
2395 kCandidateNetworkPolicyLowCost) {
2396 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2397 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2398 }
2399
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002400 port_allocator_->set_flags(portallocator_flags);
2401 // No step delay is used while allocating ports.
2402 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2403 port_allocator_->set_candidate_filter(
2404 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002405 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002406
2407 // Call this last since it may create pooled allocator sessions using the
2408 // properties set above.
2409 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002410 configuration.ice_candidate_pool_size,
2411 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002412 return true;
2413}
2414
deadbeef91dd5672016-05-18 16:55:30 -07002415bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002416 const cricket::ServerAddresses& stun_servers,
2417 const std::vector<cricket::RelayServerConfig>& turn_servers,
2418 IceTransportsType type,
2419 int candidate_pool_size,
2420 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002421 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002422 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002423 // Call this last since it may create pooled allocator sessions using the
2424 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002425 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002426 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002427}
2428
ivoc14d5dbe2016-07-04 07:06:55 -07002429bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2430 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002431 if (!event_log_) {
2432 return false;
2433 }
skvlad11a9cbf2016-10-07 11:53:05 -07002434 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002435}
2436
2437void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002438 if (event_log_) {
2439 event_log_->StopLogging();
2440 }
ivoc14d5dbe2016-07-04 07:06:55 -07002441}
nisseeaabdf62017-05-05 02:23:02 -07002442
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002443} // namespace webrtc