blob: a947c301a18461c8135106d2c85a5a8a7e582f79 [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
136// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800137void AddSendStreams(
138 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700139 const std::vector<rtc::scoped_refptr<
140 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800141 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
142 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700143 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800144 for (const auto& sender : senders) {
145 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700146 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700147 }
148
149 // 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) {
154 // |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);
162 }
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
deadbeef0a6c4ca2015-10-06 11:38:28 -0700219} // namespace
220
221namespace webrtc {
222
deadbeef293e9262017-01-11 12:28:30 -0800223bool PeerConnectionInterface::RTCConfiguration::operator==(
224 const PeerConnectionInterface::RTCConfiguration& o) const {
225 // This static_assert prevents us from accidentally breaking operator==.
226 struct stuff_being_tested_for_equality {
Steve Antonaa41f0c2017-07-11 14:38:29 -0700227 IceTransportsType type;
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000228 IceServers servers;
deadbeef293e9262017-01-11 12:28:30 -0800229 BundlePolicy bundle_policy;
230 RtcpMuxPolicy rtcp_mux_policy;
231 TcpCandidatePolicy tcp_candidate_policy;
232 CandidateNetworkPolicy candidate_network_policy;
233 int audio_jitter_buffer_max_packets;
234 bool audio_jitter_buffer_fast_accelerate;
235 int ice_connection_receiving_timeout;
236 int ice_backup_candidate_pair_ping_interval;
237 ContinualGatheringPolicy continual_gathering_policy;
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000238 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
deadbeef293e9262017-01-11 12:28:30 -0800239 bool prioritize_most_likely_ice_candidate_pairs;
240 struct cricket::MediaConfig media_config;
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000241 bool disable_ipv6;
242 bool disable_ipv6_on_wifi;
243 bool enable_rtp_data_channel;
deadbeef293e9262017-01-11 12:28:30 -0800244 bool enable_quic;
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000245 rtc::Optional<int> screencast_min_bitrate;
246 rtc::Optional<bool> combined_audio_video_bwe;
247 rtc::Optional<bool> enable_dtls_srtp;
248 int ice_candidate_pool_size;
deadbeef293e9262017-01-11 12:28:30 -0800249 bool prune_turn_ports;
250 bool presume_writable_when_fully_relayed;
251 bool enable_ice_renomination;
252 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800253 rtc::Optional<int> ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800254 };
255 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
256 "Did you add something to RTCConfiguration and forget to "
257 "update operator==?");
258 return type == o.type && servers == o.servers &&
259 bundle_policy == o.bundle_policy &&
260 rtcp_mux_policy == o.rtcp_mux_policy &&
261 tcp_candidate_policy == o.tcp_candidate_policy &&
262 candidate_network_policy == o.candidate_network_policy &&
263 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
264 audio_jitter_buffer_fast_accelerate ==
265 o.audio_jitter_buffer_fast_accelerate &&
266 ice_connection_receiving_timeout ==
267 o.ice_connection_receiving_timeout &&
268 ice_backup_candidate_pair_ping_interval ==
269 o.ice_backup_candidate_pair_ping_interval &&
270 continual_gathering_policy == o.continual_gathering_policy &&
271 certificates == o.certificates &&
272 prioritize_most_likely_ice_candidate_pairs ==
273 o.prioritize_most_likely_ice_candidate_pairs &&
274 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800275 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeef293e9262017-01-11 12:28:30 -0800276 enable_rtp_data_channel == o.enable_rtp_data_channel &&
277 enable_quic == o.enable_quic &&
278 screencast_min_bitrate == o.screencast_min_bitrate &&
279 combined_audio_video_bwe == o.combined_audio_video_bwe &&
280 enable_dtls_srtp == o.enable_dtls_srtp &&
281 ice_candidate_pool_size == o.ice_candidate_pool_size &&
282 prune_turn_ports == o.prune_turn_ports &&
283 presume_writable_when_fully_relayed ==
284 o.presume_writable_when_fully_relayed &&
285 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800286 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000287 ice_check_min_interval == o.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800288}
289
290bool PeerConnectionInterface::RTCConfiguration::operator!=(
291 const PeerConnectionInterface::RTCConfiguration& o) const {
292 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800293}
294
zhihuang8f65cdf2016-05-06 18:40:30 -0700295// Generate a RTCP CNAME when a PeerConnection is created.
296std::string GenerateRtcpCname() {
297 std::string cname;
298 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
299 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800300 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700301 }
302 return cname;
303}
304
htaa2a49d92016-03-04 02:51:39 -0800305bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700306 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800307 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700308 cricket::MediaSessionOptions* session_options) {
309 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
310 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
311 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
312 return false;
313 }
314
htaaac2dea2016-03-10 13:35:55 -0800315 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700316 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700317 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800318 } else {
319 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700320 }
htaaac2dea2016-03-10 13:35:55 -0800321 // For offers, we only offer video if we have it or it's forced by options.
322 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700323 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700324 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800325 } else if (is_offer) {
326 session_options->recv_video = false;
327 } else {
328 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700329 }
330
331 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700332 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800333 for (auto& kv : session_options->transport_options) {
334 kv.second.ice_restart = rtc_options.ice_restart;
335 }
deadbeefab9b2d12015-10-14 11:33:11 -0700336
337 return true;
338}
339
340bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
341 cricket::MediaSessionOptions* session_options) {
342 bool value = false;
343 size_t mandatory_constraints_satisfied = 0;
344
345 // kOfferToReceiveAudio defaults to true according to spec.
346 if (!FindConstraint(constraints,
347 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
348 &mandatory_constraints_satisfied) ||
349 value) {
350 session_options->recv_audio = true;
351 }
352
353 // kOfferToReceiveVideo defaults to false according to spec. But
354 // if it is an answer and video is offered, we should still accept video
355 // per default.
356 value = false;
357 if (!FindConstraint(constraints,
358 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
359 &mandatory_constraints_satisfied) ||
360 value) {
361 session_options->recv_video = true;
362 }
363
364 if (FindConstraint(constraints,
365 MediaConstraintsInterface::kVoiceActivityDetection, &value,
366 &mandatory_constraints_satisfied)) {
367 session_options->vad_enabled = value;
368 }
369
370 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
371 &mandatory_constraints_satisfied)) {
372 session_options->bundle_enabled = value;
373 } else {
374 // kUseRtpMux defaults to true according to spec.
375 session_options->bundle_enabled = true;
376 }
deadbeefab9b2d12015-10-14 11:33:11 -0700377
deadbeef0ed85b22016-02-23 17:24:52 -0800378 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700379 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
380 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700381 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800382 ice_restart = true;
383 }
384 for (auto& kv : session_options->transport_options) {
385 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700386 }
387
388 if (!constraints) {
389 return true;
390 }
391 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
392}
393
zhihuang38ede132017-06-15 12:52:32 -0700394PeerConnection::PeerConnection(PeerConnectionFactory* factory,
395 std::unique_ptr<RtcEventLog> event_log,
396 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397 : factory_(factory),
398 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000399 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700400 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000401 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000402 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700403 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700404 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700405 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700406 remote_streams_(StreamCollection::Create()),
407 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000408
409PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100410 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700411 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700412 // Need to detach RTP senders/receivers from WebRtcSession,
413 // since it's about to be destroyed.
414 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700415 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700416 }
417 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700418 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700419 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700420 // Destroy stats_ because it depends on session_.
421 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800422 if (stats_collector_) {
423 stats_collector_->WaitForPendingRequest();
424 stats_collector_ = nullptr;
425 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700426 // Now destroy session_ before destroying other members,
427 // because its destruction fires signals (such as VoiceChannelDestroyed)
428 // which will trigger some final actions in PeerConnection...
429 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700430 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700431 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700432 [this] { port_allocator_.reset(); });
433 // call_ must be destroyed on the worker thread.
434 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
435 [this] { call_.reset(); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000436}
437
438bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000439 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700440 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200441 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800442 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100443 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800444 if (!allocator) {
445 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
446 << "This shouldn't happen if using PeerConnectionFactory.";
447 return false;
448 }
deadbeef653b8e02015-11-11 12:55:10 -0800449 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800450 // TODO(deadbeef): Why do we do this?
451 LOG(LS_ERROR) << "PeerConnection initialized without a "
452 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800453 return false;
454 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000455 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800456 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800457
deadbeef91dd5672016-05-18 16:55:30 -0700458 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700459 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700460 if (!network_thread()->Invoke<bool>(
461 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
462 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000463 return false;
464 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000466
zhihuang29ff8442016-07-27 11:07:25 -0700467 session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700468 call_.get(), factory_->channel_manager(), configuration.media_config,
469 event_log_.get(),
470 factory_->network_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700471 factory_->worker_thread(), factory_->signaling_thread(),
472 port_allocator_.get(),
473 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700474 factory_->CreateTransportController(
475 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800476 configuration.redetermine_role_on_ice_restart)),
477#ifdef HAVE_SCTP
478 std::unique_ptr<cricket::SctpTransportInternalFactory>(
479 new cricket::SctpTransportFactory(factory_->network_thread()))
480#else
481 nullptr
482#endif
483 ));
zhihuang29ff8442016-07-27 11:07:25 -0700484
deadbeefab9b2d12015-10-14 11:33:11 -0700485 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700486 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000487
488 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200489 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800490 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000491 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700492 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000494 // Register PeerConnection as receiver of local ice candidates.
495 // All the callbacks will be posted to the application from PeerConnection.
496 session_->RegisterIceObserver(this);
497 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700498 session_->SignalVoiceChannelCreated.connect(
499 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700500 session_->SignalVoiceChannelDestroyed.connect(
501 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700502 session_->SignalVideoChannelCreated.connect(
503 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700504 session_->SignalVideoChannelDestroyed.connect(
505 this, &PeerConnection::OnVideoChannelDestroyed);
506 session_->SignalDataChannelCreated.connect(
507 this, &PeerConnection::OnDataChannelCreated);
508 session_->SignalDataChannelDestroyed.connect(
509 this, &PeerConnection::OnDataChannelDestroyed);
510 session_->SignalDataChannelOpenMessage.connect(
511 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800512
513 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514 return true;
515}
516
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000517rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000518PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700519 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000520}
521
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000522rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000523PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700524 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525}
526
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000527bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100528 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000529 if (IsClosed()) {
530 return false;
531 }
deadbeefab9b2d12015-10-14 11:33:11 -0700532 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533 return false;
534 }
deadbeefab9b2d12015-10-14 11:33:11 -0700535
536 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800537 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
538 observer->SignalAudioTrackAdded.connect(this,
539 &PeerConnection::OnAudioTrackAdded);
540 observer->SignalAudioTrackRemoved.connect(
541 this, &PeerConnection::OnAudioTrackRemoved);
542 observer->SignalVideoTrackAdded.connect(this,
543 &PeerConnection::OnVideoTrackAdded);
544 observer->SignalVideoTrackRemoved.connect(
545 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700546 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700547
deadbeefab9b2d12015-10-14 11:33:11 -0700548 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800549 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700550 }
551 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800552 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700553 }
554
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000555 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000556 observer_->OnRenegotiationNeeded();
557 return true;
558}
559
560void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100561 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700562 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800563 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700564 }
565 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800566 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700567 }
568
569 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800570 stream_observers_.erase(
571 std::remove_if(
572 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700573 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800574 return observer->stream()->label().compare(local_stream->label()) ==
575 0;
576 }),
577 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700578
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579 if (IsClosed()) {
580 return;
581 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000582 observer_->OnRenegotiationNeeded();
583}
584
deadbeefe1f9d832016-01-14 15:35:42 -0800585rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
586 MediaStreamTrackInterface* track,
587 std::vector<MediaStreamInterface*> streams) {
588 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
589 if (IsClosed()) {
590 return nullptr;
591 }
592 if (streams.size() >= 2) {
593 LOG(LS_ERROR)
594 << "Adding a track with two streams is not currently supported.";
595 return nullptr;
596 }
597 // TODO(deadbeef): Support adding a track to two different senders.
598 if (FindSenderForTrack(track) != senders_.end()) {
599 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
600 return nullptr;
601 }
602
603 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700604 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800605 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700606 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800607 signaling_thread(),
608 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700609 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800610 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700611 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800612 }
613 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700614 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800615 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700616 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800617 }
618 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700619 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800620 signaling_thread(),
621 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700622 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800623 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700624 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800625 }
626 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700627 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800628 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700629 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800630 }
631 } else {
632 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
633 return rtc::scoped_refptr<RtpSenderInterface>();
634 }
635
636 senders_.push_back(new_sender);
637 observer_->OnRenegotiationNeeded();
638 return new_sender;
639}
640
641bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
642 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
643 if (IsClosed()) {
644 return false;
645 }
646
647 auto it = std::find(senders_.begin(), senders_.end(), sender);
648 if (it == senders_.end()) {
649 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
650 return false;
651 }
deadbeefa601f5c2016-06-06 14:27:39 -0700652 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800653 senders_.erase(it);
654
655 observer_->OnRenegotiationNeeded();
656 return true;
657}
658
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000659rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000660 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100661 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700662 if (IsClosed()) {
663 return nullptr;
664 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000665 if (!track) {
666 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800667 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668 }
deadbeef20cb0c12017-02-01 20:27:00 -0800669 auto it = FindSenderForTrack(track);
670 if (it == senders_.end()) {
671 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
672 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 }
674
deadbeef20cb0c12017-02-01 20:27:00 -0800675 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676}
677
deadbeeffac06552015-11-25 11:26:01 -0800678rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800679 const std::string& kind,
680 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100681 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700682 if (IsClosed()) {
683 return nullptr;
684 }
deadbeefa601f5c2016-06-06 14:27:39 -0700685 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800686 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700687 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700688 signaling_thread(),
689 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800690 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700691 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700692 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800693 } else {
694 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800695 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800696 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800697 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700698 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800699 }
deadbeeffac06552015-11-25 11:26:01 -0800700 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800701 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800702}
703
deadbeef70ab1a12015-09-28 16:53:55 -0700704std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
705 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700706 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
707 for (const auto& sender : senders_) {
708 ret.push_back(sender.get());
709 }
710 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700711}
712
713std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
714PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700715 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
716 for (const auto& receiver : receivers_) {
717 ret.push_back(receiver.get());
718 }
719 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700720}
721
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000723 MediaStreamTrackInterface* track,
724 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100725 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700726 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800727 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 LOG(LS_ERROR) << "GetStats - observer is NULL.";
729 return false;
730 }
731
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000732 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700733 // The StatsCollector is used to tell if a track is valid because it may
734 // remember tracks that the PeerConnection previously removed.
735 if (track && !stats_->IsValidTrack(track->id())) {
736 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
737 << track->id();
738 return false;
739 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700740 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000741 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742 return true;
743}
744
hbos74e1a4f2016-09-15 23:33:01 -0700745void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
746 RTC_DCHECK(stats_collector_);
747 stats_collector_->GetStatsReport(callback);
748}
749
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
751 return signaling_state_;
752}
753
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754PeerConnectionInterface::IceConnectionState
755PeerConnection::ice_connection_state() {
756 return ice_connection_state_;
757}
758
759PeerConnectionInterface::IceGatheringState
760PeerConnection::ice_gathering_state() {
761 return ice_gathering_state_;
762}
763
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000764rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765PeerConnection::CreateDataChannel(
766 const std::string& label,
767 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100768 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700769#ifdef HAVE_QUIC
770 if (session_->data_channel_type() == cricket::DCT_QUIC) {
771 // TODO(zhihuang): Handle case when config is NULL.
772 if (!config) {
773 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
774 return nullptr;
775 }
776 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
777 if (!config->reliable || config->ordered) {
778 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
779 "ordered delivery.";
780 return nullptr;
781 }
782 return session_->quic_data_transport()->CreateDataChannel(label, config);
783 }
784#endif // HAVE_QUIC
785
deadbeefab9b2d12015-10-14 11:33:11 -0700786 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000787
kwibergd1fe2812016-04-27 06:47:29 -0700788 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000789 if (config) {
790 internal_config.reset(new InternalDataChannelInit(*config));
791 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000792 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700793 InternalCreateDataChannel(label, internal_config.get()));
794 if (!channel.get()) {
795 return nullptr;
796 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000798 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
799 // the first SCTP DataChannel.
800 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
801 observer_->OnRenegotiationNeeded();
802 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000803
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 return DataChannelProxy::Create(signaling_thread(), channel.get());
805}
806
807void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
808 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100809 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800810 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
812 return;
813 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000814 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000815
816 bool value;
817 size_t mandatory_constraints = 0;
818
819 if (FindConstraint(constraints,
820 MediaConstraintsInterface::kOfferToReceiveAudio,
821 &value,
822 &mandatory_constraints)) {
823 options.offer_to_receive_audio =
824 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
825 }
826
827 if (FindConstraint(constraints,
828 MediaConstraintsInterface::kOfferToReceiveVideo,
829 &value,
830 &mandatory_constraints)) {
831 options.offer_to_receive_video =
832 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
833 }
834
835 if (FindConstraint(constraints,
836 MediaConstraintsInterface::kVoiceActivityDetection,
837 &value,
838 &mandatory_constraints)) {
839 options.voice_activity_detection = value;
840 }
841
842 if (FindConstraint(constraints,
843 MediaConstraintsInterface::kIceRestart,
844 &value,
845 &mandatory_constraints)) {
846 options.ice_restart = value;
847 }
848
849 if (FindConstraint(constraints,
850 MediaConstraintsInterface::kUseRtpMux,
851 &value,
852 &mandatory_constraints)) {
853 options.use_rtp_mux = value;
854 }
855
856 CreateOffer(observer, options);
857}
858
859void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
860 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100861 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800862 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000863 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
864 return;
865 }
deadbeefab9b2d12015-10-14 11:33:11 -0700866
867 cricket::MediaSessionOptions session_options;
868 if (!GetOptionsForOffer(options, &session_options)) {
869 std::string error = "CreateOffer called with invalid options.";
870 LOG(LS_ERROR) << error;
871 PostCreateSessionDescriptionFailure(observer, error);
872 return;
873 }
874
875 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876}
877
878void PeerConnection::CreateAnswer(
879 CreateSessionDescriptionObserver* observer,
880 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100881 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800882 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
884 return;
885 }
deadbeefab9b2d12015-10-14 11:33:11 -0700886
887 cricket::MediaSessionOptions session_options;
888 if (!GetOptionsForAnswer(constraints, &session_options)) {
889 std::string error = "CreateAnswer called with invalid constraints.";
890 LOG(LS_ERROR) << error;
891 PostCreateSessionDescriptionFailure(observer, error);
892 return;
893 }
894
htaa2a49d92016-03-04 02:51:39 -0800895 session_->CreateAnswer(observer, session_options);
896}
897
898void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
899 const RTCOfferAnswerOptions& options) {
900 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800901 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800902 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
903 return;
904 }
905
906 cricket::MediaSessionOptions session_options;
907 if (!GetOptionsForAnswer(options, &session_options)) {
908 std::string error = "CreateAnswer called with invalid options.";
909 LOG(LS_ERROR) << error;
910 PostCreateSessionDescriptionFailure(observer, error);
911 return;
912 }
913
914 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915}
916
917void PeerConnection::SetLocalDescription(
918 SetSessionDescriptionObserver* observer,
919 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100920 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700921 if (IsClosed()) {
922 return;
923 }
nisse7ce109a2017-01-31 00:57:56 -0800924 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
926 return;
927 }
928 if (!desc) {
929 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
930 return;
931 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932 // Update stats here so that we have the most recent stats for tracks and
933 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000934 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 std::string error;
936 if (!session_->SetLocalDescription(desc, &error)) {
937 PostSetSessionDescriptionFailure(observer, error);
938 return;
939 }
deadbeefab9b2d12015-10-14 11:33:11 -0700940
941 // If setting the description decided our SSL role, allocate any necessary
942 // SCTP sids.
943 rtc::SSLRole role;
944 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800945 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700946 AllocateSctpSids(role);
947 }
948
949 // Update state and SSRC of local MediaStreams and DataChannels based on the
950 // local session description.
951 const cricket::ContentInfo* audio_content =
952 GetFirstAudioContent(desc->description());
953 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800954 if (audio_content->rejected) {
955 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
956 } else {
957 const cricket::AudioContentDescription* audio_desc =
958 static_cast<const cricket::AudioContentDescription*>(
959 audio_content->description);
960 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
961 }
deadbeefab9b2d12015-10-14 11:33:11 -0700962 }
963
964 const cricket::ContentInfo* video_content =
965 GetFirstVideoContent(desc->description());
966 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800967 if (video_content->rejected) {
968 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
969 } else {
970 const cricket::VideoContentDescription* video_desc =
971 static_cast<const cricket::VideoContentDescription*>(
972 video_content->description);
973 UpdateLocalTracks(video_desc->streams(), video_desc->type());
974 }
deadbeefab9b2d12015-10-14 11:33:11 -0700975 }
976
977 const cricket::ContentInfo* data_content =
978 GetFirstDataContent(desc->description());
979 if (data_content) {
980 const cricket::DataContentDescription* data_desc =
981 static_cast<const cricket::DataContentDescription*>(
982 data_content->description);
983 if (rtc::starts_with(data_desc->protocol().data(),
984 cricket::kMediaProtocolRtpPrefix)) {
985 UpdateLocalRtpDataChannels(data_desc->streams());
986 }
987 }
988
989 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700990 signaling_thread()->Post(RTC_FROM_HERE, this,
991 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700992
deadbeef42a42632017-03-10 15:18:00 -0800993 // According to JSEP, after setLocalDescription, changing the candidate pool
994 // size is not allowed, and changing the set of ICE servers will not result
995 // in new candidates being gathered.
996 port_allocator_->FreezeCandidatePool();
997
deadbeefcbecd352015-09-23 11:50:27 -0700998 // MaybeStartGathering needs to be called after posting
999 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1000 // before signaling that SetLocalDescription completed.
1001 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001002
1003 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1004 // TODO(deadbeef): We already had to hop to the network thread for
1005 // MaybeStartGathering...
1006 network_thread()->Invoke<void>(
1007 RTC_FROM_HERE,
1008 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1009 port_allocator_.get()));
1010 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011}
1012
1013void PeerConnection::SetRemoteDescription(
1014 SetSessionDescriptionObserver* observer,
1015 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001016 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001017 if (IsClosed()) {
1018 return;
1019 }
nisse7ce109a2017-01-31 00:57:56 -08001020 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1022 return;
1023 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024 if (!desc) {
1025 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1026 return;
1027 }
1028 // Update stats here so that we have the most recent stats for tracks and
1029 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001030 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031 std::string error;
1032 if (!session_->SetRemoteDescription(desc, &error)) {
1033 PostSetSessionDescriptionFailure(observer, error);
1034 return;
1035 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036
deadbeefab9b2d12015-10-14 11:33:11 -07001037 // If setting the description decided our SSL role, allocate any necessary
1038 // SCTP sids.
1039 rtc::SSLRole role;
1040 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001041 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001042 AllocateSctpSids(role);
1043 }
1044
1045 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001046 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1047 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1048 const cricket::AudioContentDescription* audio_desc =
1049 GetFirstAudioContentDescription(remote_desc);
1050 const cricket::VideoContentDescription* video_desc =
1051 GetFirstVideoContentDescription(remote_desc);
1052 const cricket::DataContentDescription* data_desc =
1053 GetFirstDataContentDescription(remote_desc);
1054
1055 // Check if the descriptions include streams, just in case the peer supports
1056 // MSID, but doesn't indicate so with "a=msid-semantic".
1057 if (remote_desc->msid_supported() ||
1058 (audio_desc && !audio_desc->streams().empty()) ||
1059 (video_desc && !video_desc->streams().empty())) {
1060 remote_peer_supports_msid_ = true;
1061 }
deadbeefab9b2d12015-10-14 11:33:11 -07001062
1063 // We wait to signal new streams until we finish processing the description,
1064 // since only at that point will new streams have all their tracks.
1065 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1066
1067 // Find all audio rtp streams and create corresponding remote AudioTracks
1068 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001069 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001070 if (audio_content->rejected) {
1071 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1072 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001073 bool default_audio_track_needed =
1074 !remote_peer_supports_msid_ &&
1075 MediaContentDirectionHasSend(audio_desc->direction());
1076 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1077 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001078 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080 }
1081
1082 // Find all video rtp streams and create corresponding remote VideoTracks
1083 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001084 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001085 if (video_content->rejected) {
1086 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1087 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001088 bool default_video_track_needed =
1089 !remote_peer_supports_msid_ &&
1090 MediaContentDirectionHasSend(video_desc->direction());
1091 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1092 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001093 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001094 }
deadbeefab9b2d12015-10-14 11:33:11 -07001095 }
1096
1097 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001098 if (data_desc) {
1099 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001100 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001101 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001102 }
1103 }
1104
1105 // Iterate new_streams and notify the observer about new MediaStreams.
1106 for (size_t i = 0; i < new_streams->count(); ++i) {
1107 MediaStreamInterface* new_stream = new_streams->at(i);
1108 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001109 observer_->OnAddStream(
1110 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001111 }
1112
deadbeefbda7e0b2015-12-08 17:13:40 -08001113 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001114
1115 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001116 signaling_thread()->Post(RTC_FROM_HERE, this,
1117 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001118
1119 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1120 // TODO(deadbeef): We already had to hop to the network thread for
1121 // MaybeStartGathering...
1122 network_thread()->Invoke<void>(
1123 RTC_FROM_HERE,
1124 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1125 port_allocator_.get()));
1126 }
deadbeeffc648b62015-10-13 16:42:33 -07001127}
1128
deadbeef46c73892016-11-16 19:42:04 -08001129PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1130 return configuration_;
1131}
1132
deadbeef293e9262017-01-11 12:28:30 -08001133bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1134 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001135 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001136
1137 if (session_->local_description() &&
1138 configuration.ice_candidate_pool_size !=
1139 configuration_.ice_candidate_pool_size) {
1140 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1141 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001142 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001143 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001144
deadbeef293e9262017-01-11 12:28:30 -08001145 // The simplest (and most future-compatible) way to tell if the config was
1146 // modified in an invalid way is to copy each property we do support
1147 // modifying, then use operator==. There are far more properties we don't
1148 // support modifying than those we do, and more could be added.
1149 RTCConfiguration modified_config = configuration_;
1150 modified_config.servers = configuration.servers;
1151 modified_config.type = configuration.type;
1152 modified_config.ice_candidate_pool_size =
1153 configuration.ice_candidate_pool_size;
1154 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001155 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001156 if (configuration != modified_config) {
1157 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1158 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1159 }
1160
1161 // Note that this isn't possible through chromium, since it's an unsigned
1162 // short in WebIDL.
1163 if (configuration.ice_candidate_pool_size < 0 ||
1164 configuration.ice_candidate_pool_size > UINT16_MAX) {
1165 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1166 }
1167
1168 // Parse ICE servers before hopping to network thread.
1169 cricket::ServerAddresses stun_servers;
1170 std::vector<cricket::RelayServerConfig> turn_servers;
1171 RTCErrorType parse_error =
1172 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1173 if (parse_error != RTCErrorType::NONE) {
1174 return SafeSetError(parse_error, error);
1175 }
1176
1177 // In theory this shouldn't fail.
1178 if (!network_thread()->Invoke<bool>(
1179 RTC_FROM_HERE,
1180 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1181 stun_servers, turn_servers, modified_config.type,
1182 modified_config.ice_candidate_pool_size,
1183 modified_config.prune_turn_ports))) {
1184 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1185 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1186 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001187
deadbeefd1a38b52016-12-10 13:15:33 -08001188 // As described in JSEP, calling setConfiguration with new ICE servers or
1189 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1190 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001191 if (modified_config.servers != configuration_.servers ||
1192 modified_config.type != configuration_.type ||
1193 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001194 session_->SetNeedsIceRestartFlag();
1195 }
skvladd1f5fda2017-02-03 16:54:05 -08001196
1197 if (modified_config.ice_check_min_interval !=
1198 configuration_.ice_check_min_interval) {
1199 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1200 }
1201
deadbeef293e9262017-01-11 12:28:30 -08001202 configuration_ = modified_config;
1203 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001204}
1205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206bool PeerConnection::AddIceCandidate(
1207 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001208 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001209 if (IsClosed()) {
1210 return false;
1211 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212 return session_->ProcessIceMessage(ice_candidate);
1213}
1214
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001215bool PeerConnection::RemoveIceCandidates(
1216 const std::vector<cricket::Candidate>& candidates) {
1217 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1218 return session_->RemoveRemoteIceCandidates(candidates);
1219}
1220
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001221void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001222 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001223 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001224
1225 if (session_) {
1226 session_->set_metrics_observer(uma_observer_);
1227 }
1228
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001229 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001230 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001231 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001232 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001233 uma_observer_->IncrementEnumCounter(
1234 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1235 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001236 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001237 uma_observer_->IncrementEnumCounter(
1238 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1239 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001240 }
1241 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001242}
1243
zstein4b979802017-06-02 14:37:37 -07001244RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
1245 rtc::Thread* worker_thread = factory_->worker_thread();
1246 if (!worker_thread->IsCurrent()) {
1247 return worker_thread->Invoke<RTCError>(
1248 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1249 }
1250
1251 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1252 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1253 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1254 if (has_min && *bitrate.min_bitrate_bps < 0) {
1255 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1256 "min_bitrate_bps <= 0");
1257 }
1258 if (has_current) {
1259 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1260 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1261 "current_bitrate_bps < min_bitrate_bps");
1262 } else if (*bitrate.current_bitrate_bps < 0) {
1263 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1264 "curent_bitrate_bps < 0");
1265 }
1266 }
1267 if (has_max) {
1268 if (has_current &&
1269 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1270 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1271 "max_bitrate_bps < current_bitrate_bps");
1272 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1274 "max_bitrate_bps < min_bitrate_bps");
1275 } else if (*bitrate.max_bitrate_bps < 0) {
1276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1277 "max_bitrate_bps < 0");
1278 }
1279 }
1280
1281 Call::Config::BitrateConfigMask mask;
1282 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1283 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1284 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1285
1286 RTC_DCHECK(call_.get());
1287 call_->SetBitrateConfigMask(mask);
1288
1289 return RTCError::OK();
1290}
1291
ivoc14d5dbe2016-07-04 07:06:55 -07001292bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1293 int64_t max_size_bytes) {
1294 return factory_->worker_thread()->Invoke<bool>(
1295 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1296 max_size_bytes));
1297}
1298
1299void PeerConnection::StopRtcEventLog() {
1300 factory_->worker_thread()->Invoke<void>(
1301 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1302}
1303
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304const SessionDescriptionInterface* PeerConnection::local_description() const {
1305 return session_->local_description();
1306}
1307
1308const SessionDescriptionInterface* PeerConnection::remote_description() const {
1309 return session_->remote_description();
1310}
1311
deadbeeffe4a8a42016-12-20 17:56:17 -08001312const SessionDescriptionInterface* PeerConnection::current_local_description()
1313 const {
1314 return session_->current_local_description();
1315}
1316
1317const SessionDescriptionInterface* PeerConnection::current_remote_description()
1318 const {
1319 return session_->current_remote_description();
1320}
1321
1322const SessionDescriptionInterface* PeerConnection::pending_local_description()
1323 const {
1324 return session_->pending_local_description();
1325}
1326
1327const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1328 const {
1329 return session_->pending_remote_description();
1330}
1331
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001333 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 // Update stats here so that we have the most recent stats for tracks and
1335 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001336 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337
deadbeefd59daf82015-10-14 15:02:44 -07001338 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001339 network_thread()->Invoke<void>(
1340 RTC_FROM_HERE,
1341 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1342 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001343
1344 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
1345 [this] { call_.reset(); });
terelius33860252017-05-12 23:37:18 -07001346
1347 // The event log must outlive call (and any other object that uses it).
1348 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349}
1350
deadbeefd59daf82015-10-14 15:02:44 -07001351void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1352 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001354 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001355 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001356 break;
deadbeefd59daf82015-10-14 15:02:44 -07001357 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1359 break;
deadbeefd59daf82015-10-14 15:02:44 -07001360 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1362 break;
deadbeefd59daf82015-10-14 15:02:44 -07001363 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1365 break;
deadbeefd59daf82015-10-14 15:02:44 -07001366 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1368 break;
deadbeefd59daf82015-10-14 15:02:44 -07001369 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 ChangeSignalingState(PeerConnectionInterface::kStable);
1371 break;
deadbeefd59daf82015-10-14 15:02:44 -07001372 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373 ChangeSignalingState(PeerConnectionInterface::kClosed);
1374 break;
1375 default:
1376 break;
1377 }
1378}
1379
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001380void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001382 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1383 SetSessionDescriptionMsg* param =
1384 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1385 param->observer->OnSuccess();
1386 delete param;
1387 break;
1388 }
1389 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1390 SetSessionDescriptionMsg* param =
1391 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1392 param->observer->OnFailure(param->error);
1393 delete param;
1394 break;
1395 }
deadbeefab9b2d12015-10-14 11:33:11 -07001396 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1397 CreateSessionDescriptionMsg* param =
1398 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1399 param->observer->OnFailure(param->error);
1400 delete param;
1401 break;
1402 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403 case MSG_GETSTATS: {
1404 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001405 StatsReports reports;
1406 stats_->GetStats(param->track, &reports);
1407 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 delete param;
1409 break;
1410 }
deadbeefbd292462015-12-14 18:15:29 -08001411 case MSG_FREE_DATACHANNELS: {
1412 sctp_data_channels_to_free_.clear();
1413 break;
1414 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001416 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001417 break;
1418 }
1419}
1420
deadbeefab9b2d12015-10-14 11:33:11 -07001421void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001422 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001423 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1425 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001426 signaling_thread(),
1427 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1428 stream->AddTrack(
1429 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001430 receivers_.push_back(receiver);
1431 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1432 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1433 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001434}
1435
deadbeefab9b2d12015-10-14 11:33:11 -07001436void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001437 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001438 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001439 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1440 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001441 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001442 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1443 session_->video_channel()));
1444 stream->AddTrack(
1445 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001446 receivers_.push_back(receiver);
1447 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1448 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1449 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450}
1451
deadbeef70ab1a12015-09-28 16:53:55 -07001452// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1453// description.
perkjd61bf802016-03-24 03:16:19 -07001454void PeerConnection::DestroyReceiver(const std::string& track_id) {
1455 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001456 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001457 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001458 << " doesn't exist.";
1459 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001460 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001461 receivers_.erase(it);
1462 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463}
1464
zstein6dfd53a2017-03-06 13:49:03 -08001465void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001467 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001468 // After transitioning to "closed", ignore any additional states from
1469 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001470 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001471 return;
1472 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001474 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475}
1476
1477void PeerConnection::OnIceGatheringChange(
1478 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001479 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 if (IsClosed()) {
1481 return;
1482 }
1483 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001484 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485}
1486
jbauch81bf7b02017-03-25 08:31:12 -07001487void PeerConnection::OnIceCandidate(
1488 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001489 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001490 if (IsClosed()) {
1491 return;
1492 }
jbauch81bf7b02017-03-25 08:31:12 -07001493 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494}
1495
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001496void PeerConnection::OnIceCandidatesRemoved(
1497 const std::vector<cricket::Candidate>& candidates) {
1498 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001499 if (IsClosed()) {
1500 return;
1501 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001502 observer_->OnIceCandidatesRemoved(candidates);
1503}
1504
Peter Thatcher54360512015-07-08 11:08:35 -07001505void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001506 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001507 if (IsClosed()) {
1508 return;
1509 }
Peter Thatcher54360512015-07-08 11:08:35 -07001510 observer_->OnIceConnectionReceivingChange(receiving);
1511}
1512
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001513void PeerConnection::ChangeSignalingState(
1514 PeerConnectionInterface::SignalingState signaling_state) {
1515 signaling_state_ = signaling_state;
1516 if (signaling_state == kClosed) {
1517 ice_connection_state_ = kIceConnectionClosed;
1518 observer_->OnIceConnectionChange(ice_connection_state_);
1519 if (ice_gathering_state_ != kIceGatheringComplete) {
1520 ice_gathering_state_ = kIceGatheringComplete;
1521 observer_->OnIceGatheringChange(ice_gathering_state_);
1522 }
1523 }
1524 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001525}
1526
deadbeefeb459812015-12-15 19:24:43 -08001527void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1528 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001529 if (IsClosed()) {
1530 return;
1531 }
deadbeefeb459812015-12-15 19:24:43 -08001532 auto sender = FindSenderForTrack(track);
1533 if (sender != senders_.end()) {
1534 // We already have a sender for this track, so just change the stream_id
1535 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001536 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001537 return;
1538 }
1539
1540 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001541 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1542 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001543 signaling_thread(),
1544 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1545 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001546 senders_.push_back(new_sender);
1547 // If the sender has already been configured in SDP, we call SetSsrc,
1548 // which will connect the sender to the underlying transport. This can
1549 // occur if a local session description that contains the ID of the sender
1550 // is set before AddStream is called. It can also occur if the local
1551 // session description is not changed and RemoveStream is called, and
1552 // later AddStream is called again with the same stream.
1553 const TrackInfo* track_info =
1554 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1555 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001556 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001557 }
1558}
1559
1560// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1561// indefinitely, when we have unified plan SDP.
1562void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1563 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001564 if (IsClosed()) {
1565 return;
1566 }
deadbeefeb459812015-12-15 19:24:43 -08001567 auto sender = FindSenderForTrack(track);
1568 if (sender == senders_.end()) {
1569 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1570 << " doesn't exist.";
1571 return;
1572 }
deadbeefa601f5c2016-06-06 14:27:39 -07001573 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001574 senders_.erase(sender);
1575}
1576
1577void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1578 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001579 if (IsClosed()) {
1580 return;
1581 }
deadbeefeb459812015-12-15 19:24:43 -08001582 auto sender = FindSenderForTrack(track);
1583 if (sender != senders_.end()) {
1584 // We already have a sender for this track, so just change the stream_id
1585 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001586 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001587 return;
1588 }
1589
1590 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001591 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1592 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001593 signaling_thread(), new VideoRtpSender(track, stream->label(),
1594 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001595 senders_.push_back(new_sender);
1596 const TrackInfo* track_info =
1597 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1598 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001599 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001600 }
1601}
1602
1603void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1604 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001605 if (IsClosed()) {
1606 return;
1607 }
deadbeefeb459812015-12-15 19:24:43 -08001608 auto sender = FindSenderForTrack(track);
1609 if (sender == senders_.end()) {
1610 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1611 << " doesn't exist.";
1612 return;
1613 }
deadbeefa601f5c2016-06-06 14:27:39 -07001614 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001615 senders_.erase(sender);
1616}
1617
deadbeefab9b2d12015-10-14 11:33:11 -07001618void PeerConnection::PostSetSessionDescriptionFailure(
1619 SetSessionDescriptionObserver* observer,
1620 const std::string& error) {
1621 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1622 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001623 signaling_thread()->Post(RTC_FROM_HERE, this,
1624 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001625}
1626
1627void PeerConnection::PostCreateSessionDescriptionFailure(
1628 CreateSessionDescriptionObserver* observer,
1629 const std::string& error) {
1630 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1631 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001632 signaling_thread()->Post(RTC_FROM_HERE, this,
1633 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001634}
1635
1636bool PeerConnection::GetOptionsForOffer(
1637 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1638 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001639 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1640 // ContentInfos.
1641 if (session_->local_description()) {
1642 for (const cricket::ContentInfo& content :
1643 session_->local_description()->description()->contents()) {
1644 session_options->transport_options[content.name] =
1645 cricket::TransportOptions();
1646 }
1647 }
deadbeef46c73892016-11-16 19:42:04 -08001648 session_options->enable_ice_renomination =
1649 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001650
htaaac2dea2016-03-10 13:35:55 -08001651 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001652 return false;
1653 }
1654
deadbeeffac06552015-11-25 11:26:01 -08001655 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001656 // Offer to receive audio/video if the constraint is not set and there are
1657 // send streams, or we're currently receiving.
1658 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1659 session_options->recv_audio =
1660 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1661 !remote_audio_tracks_.empty();
1662 }
1663 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1664 session_options->recv_video =
1665 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1666 !remote_video_tracks_.empty();
1667 }
deadbeefc80741f2015-10-22 13:14:45 -07001668
zhihuang9763d562016-08-05 11:14:50 -07001669 // Intentionally unset the data channel type for RTP data channel with the
1670 // second condition. Otherwise the RTP data channels would be successfully
1671 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1672 // when building with chromium. We want to leave RTP data channels broken, so
1673 // people won't try to use them.
1674 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1675 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001676 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001677
zhihuangaf388472016-11-02 16:49:48 -07001678 session_options->bundle_enabled =
1679 session_options->bundle_enabled &&
1680 (session_options->has_audio() || session_options->has_video() ||
1681 session_options->has_data());
1682
zhihuang8f65cdf2016-05-06 18:40:30 -07001683 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001684 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001685 return true;
1686}
1687
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001688void PeerConnection::InitializeOptionsForAnswer(
1689 cricket::MediaSessionOptions* session_options) {
1690 session_options->recv_audio = false;
1691 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001692 session_options->enable_ice_renomination =
1693 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001694}
1695
htaa2a49d92016-03-04 02:51:39 -08001696void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001697 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001698 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1699 // ContentInfos.
1700 if (session_->remote_description()) {
1701 // Initialize the transport_options map.
1702 for (const cricket::ContentInfo& content :
1703 session_->remote_description()->description()->contents()) {
1704 session_options->transport_options[content.name] =
1705 cricket::TransportOptions();
1706 }
1707 }
deadbeeffac06552015-11-25 11:26:01 -08001708 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001709 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1710 // are not signaled in the SDP so does not go through that path and must be
1711 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001712 // Intentionally unset the data channel type for RTP data channel. Otherwise
1713 // the RTP data channels would be successfully negotiated by default and the
1714 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1715 // We want to leave RTP data channels broken, so people won't try to use them.
1716 if (session_->data_channel_type() != cricket::DCT_RTP) {
1717 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001718 }
zhihuangaf388472016-11-02 16:49:48 -07001719 session_options->bundle_enabled =
1720 session_options->bundle_enabled &&
1721 (session_options->has_audio() || session_options->has_video() ||
1722 session_options->has_data());
1723
jbauchcb560652016-08-04 05:20:32 -07001724 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001725}
1726
1727bool PeerConnection::GetOptionsForAnswer(
1728 const MediaConstraintsInterface* constraints,
1729 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001730 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001731 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1732 return false;
1733 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001734 session_options->rtcp_cname = rtcp_cname_;
1735
htaa2a49d92016-03-04 02:51:39 -08001736 FinishOptionsForAnswer(session_options);
1737 return true;
1738}
1739
1740bool PeerConnection::GetOptionsForAnswer(
1741 const RTCOfferAnswerOptions& options,
1742 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001743 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001744 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001745 return false;
1746 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001747 session_options->rtcp_cname = rtcp_cname_;
1748
htaa2a49d92016-03-04 02:51:39 -08001749 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001750 return true;
1751}
1752
deadbeeffaac4972015-11-12 15:33:07 -08001753void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1754 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001755 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1756 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001757}
1758
deadbeefab9b2d12015-10-14 11:33:11 -07001759void PeerConnection::UpdateRemoteStreamsList(
1760 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001761 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001762 cricket::MediaType media_type,
1763 StreamCollection* new_streams) {
1764 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1765
1766 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001767 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001768 auto track_it = current_tracks->begin();
1769 while (track_it != current_tracks->end()) {
1770 const TrackInfo& info = *track_it;
1771 const cricket::StreamParams* params =
1772 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001773 bool track_exists = params && params->id == info.track_id;
1774 // If this is a default track, and we still need it, don't remove it.
1775 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1776 track_exists) {
1777 ++track_it;
1778 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001779 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1780 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001781 }
1782 }
1783
1784 // Find new and active tracks.
1785 for (const cricket::StreamParams& params : streams) {
1786 // The sync_label is the MediaStream label and the |stream.id| is the
1787 // track id.
1788 const std::string& stream_label = params.sync_label;
1789 const std::string& track_id = params.id;
1790 uint32_t ssrc = params.first_ssrc();
1791
1792 rtc::scoped_refptr<MediaStreamInterface> stream =
1793 remote_streams_->find(stream_label);
1794 if (!stream) {
1795 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001796 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1797 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001798 remote_streams_->AddStream(stream);
1799 new_streams->AddStream(stream);
1800 }
1801
1802 const TrackInfo* track_info =
1803 FindTrackInfo(*current_tracks, stream_label, track_id);
1804 if (!track_info) {
1805 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1806 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1807 }
1808 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001809
1810 // Add default track if necessary.
1811 if (default_track_needed) {
1812 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1813 remote_streams_->find(kDefaultStreamLabel);
1814 if (!default_stream) {
1815 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001816 default_stream = MediaStreamProxy::Create(
1817 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001818 remote_streams_->AddStream(default_stream);
1819 new_streams->AddStream(default_stream);
1820 }
1821 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1822 ? kDefaultAudioTrackLabel
1823 : kDefaultVideoTrackLabel;
1824 const TrackInfo* default_track_info =
1825 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1826 if (!default_track_info) {
1827 current_tracks->push_back(
1828 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1829 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1830 }
1831 }
deadbeefab9b2d12015-10-14 11:33:11 -07001832}
1833
1834void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1835 const std::string& track_id,
1836 uint32_t ssrc,
1837 cricket::MediaType media_type) {
1838 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1839
1840 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001841 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001842 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001843 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001844 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001845 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001846 }
1847}
1848
1849void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1850 const std::string& track_id,
1851 cricket::MediaType media_type) {
1852 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1853
1854 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001855 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1856 // will be notified which will end the AudioRtpReceiver::track().
1857 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001858 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1859 stream->FindAudioTrack(track_id);
1860 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001861 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001862 }
1863 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001864 // Stopping or destroying a VideoRtpReceiver will end the
1865 // VideoRtpReceiver::track().
1866 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001867 rtc::scoped_refptr<VideoTrackInterface> video_track =
1868 stream->FindVideoTrack(track_id);
1869 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001870 // There's no guarantee the track is still available, e.g. the track may
1871 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001872 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001873 }
1874 } else {
nisseede5da42017-01-12 05:15:36 -08001875 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001876 }
1877}
1878
1879void PeerConnection::UpdateEndedRemoteMediaStreams() {
1880 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1881 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1882 MediaStreamInterface* stream = remote_streams_->at(i);
1883 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1884 streams_to_remove.push_back(stream);
1885 }
1886 }
1887
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001888 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001889 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001890 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001891 }
1892}
1893
deadbeefab9b2d12015-10-14 11:33:11 -07001894void PeerConnection::UpdateLocalTracks(
1895 const std::vector<cricket::StreamParams>& streams,
1896 cricket::MediaType media_type) {
1897 TrackInfos* current_tracks = GetLocalTracks(media_type);
1898
1899 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1900 // don't match the new StreamParam.
1901 TrackInfos::iterator track_it = current_tracks->begin();
1902 while (track_it != current_tracks->end()) {
1903 const TrackInfo& info = *track_it;
1904 const cricket::StreamParams* params =
1905 cricket::GetStreamBySsrc(streams, info.ssrc);
1906 if (!params || params->id != info.track_id ||
1907 params->sync_label != info.stream_label) {
1908 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1909 media_type);
1910 track_it = current_tracks->erase(track_it);
1911 } else {
1912 ++track_it;
1913 }
1914 }
1915
1916 // Find new and active tracks.
1917 for (const cricket::StreamParams& params : streams) {
1918 // The sync_label is the MediaStream label and the |stream.id| is the
1919 // track id.
1920 const std::string& stream_label = params.sync_label;
1921 const std::string& track_id = params.id;
1922 uint32_t ssrc = params.first_ssrc();
1923 const TrackInfo* track_info =
1924 FindTrackInfo(*current_tracks, stream_label, track_id);
1925 if (!track_info) {
1926 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1927 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1928 }
1929 }
1930}
1931
1932void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1933 const std::string& track_id,
1934 uint32_t ssrc,
1935 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001936 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001937 if (!sender) {
1938 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1939 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001940 return;
1941 }
1942
deadbeeffac06552015-11-25 11:26:01 -08001943 if (sender->media_type() != media_type) {
1944 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1945 << " description with an unexpected media type.";
1946 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001947 }
deadbeeffac06552015-11-25 11:26:01 -08001948
1949 sender->set_stream_id(stream_label);
1950 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001951}
1952
1953void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1954 const std::string& track_id,
1955 uint32_t ssrc,
1956 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001957 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001958 if (!sender) {
1959 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001960 // SessionDescriptions has been renegotiated.
1961 return;
1962 }
deadbeeffac06552015-11-25 11:26:01 -08001963
1964 // A sender has been removed from the SessionDescription but it's still
1965 // associated with the PeerConnection. This only occurs if the SDP doesn't
1966 // match with the calls to CreateSender, AddStream and RemoveStream.
1967 if (sender->media_type() != media_type) {
1968 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1969 << " description with an unexpected media type.";
1970 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001971 }
deadbeeffac06552015-11-25 11:26:01 -08001972
1973 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001974}
1975
1976void PeerConnection::UpdateLocalRtpDataChannels(
1977 const cricket::StreamParamsVec& streams) {
1978 std::vector<std::string> existing_channels;
1979
1980 // Find new and active data channels.
1981 for (const cricket::StreamParams& params : streams) {
1982 // |it->sync_label| is actually the data channel label. The reason is that
1983 // we use the same naming of data channels as we do for
1984 // MediaStreams and Tracks.
1985 // For MediaStreams, the sync_label is the MediaStream label and the
1986 // track label is the same as |streamid|.
1987 const std::string& channel_label = params.sync_label;
1988 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08001989 if (data_channel_it == rtp_data_channels_.end()) {
1990 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07001991 continue;
1992 }
1993 // Set the SSRC the data channel should use for sending.
1994 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1995 existing_channels.push_back(data_channel_it->first);
1996 }
1997
1998 UpdateClosingRtpDataChannels(existing_channels, true);
1999}
2000
2001void PeerConnection::UpdateRemoteRtpDataChannels(
2002 const cricket::StreamParamsVec& streams) {
2003 std::vector<std::string> existing_channels;
2004
2005 // Find new and active data channels.
2006 for (const cricket::StreamParams& params : streams) {
2007 // The data channel label is either the mslabel or the SSRC if the mslabel
2008 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2009 std::string label = params.sync_label.empty()
2010 ? rtc::ToString(params.first_ssrc())
2011 : params.sync_label;
2012 auto data_channel_it = rtp_data_channels_.find(label);
2013 if (data_channel_it == rtp_data_channels_.end()) {
2014 // This is a new data channel.
2015 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2016 } else {
2017 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2018 }
2019 existing_channels.push_back(label);
2020 }
2021
2022 UpdateClosingRtpDataChannels(existing_channels, false);
2023}
2024
2025void PeerConnection::UpdateClosingRtpDataChannels(
2026 const std::vector<std::string>& active_channels,
2027 bool is_local_update) {
2028 auto it = rtp_data_channels_.begin();
2029 while (it != rtp_data_channels_.end()) {
2030 DataChannel* data_channel = it->second;
2031 if (std::find(active_channels.begin(), active_channels.end(),
2032 data_channel->label()) != active_channels.end()) {
2033 ++it;
2034 continue;
2035 }
2036
2037 if (is_local_update) {
2038 data_channel->SetSendSsrc(0);
2039 } else {
2040 data_channel->RemotePeerRequestClose();
2041 }
2042
2043 if (data_channel->state() == DataChannel::kClosed) {
2044 rtp_data_channels_.erase(it);
2045 it = rtp_data_channels_.begin();
2046 } else {
2047 ++it;
2048 }
2049 }
2050}
2051
2052void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2053 uint32_t remote_ssrc) {
2054 rtc::scoped_refptr<DataChannel> channel(
2055 InternalCreateDataChannel(label, nullptr));
2056 if (!channel.get()) {
2057 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2058 << "CreateDataChannel failed.";
2059 return;
2060 }
2061 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002062 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2063 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002064 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002065}
2066
2067rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2068 const std::string& label,
2069 const InternalDataChannelInit* config) {
2070 if (IsClosed()) {
2071 return nullptr;
2072 }
2073 if (session_->data_channel_type() == cricket::DCT_NONE) {
2074 LOG(LS_ERROR)
2075 << "InternalCreateDataChannel: Data is not supported in this call.";
2076 return nullptr;
2077 }
2078 InternalDataChannelInit new_config =
2079 config ? (*config) : InternalDataChannelInit();
2080 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2081 if (new_config.id < 0) {
2082 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002083 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002084 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2085 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2086 return nullptr;
2087 }
2088 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2089 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2090 << "because the id is already in use or out of range.";
2091 return nullptr;
2092 }
2093 }
2094
2095 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2096 session_.get(), session_->data_channel_type(), label, new_config));
2097 if (!channel) {
2098 sid_allocator_.ReleaseSid(new_config.id);
2099 return nullptr;
2100 }
2101
2102 if (channel->data_channel_type() == cricket::DCT_RTP) {
2103 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2104 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2105 << " already exists.";
2106 return nullptr;
2107 }
2108 rtp_data_channels_[channel->label()] = channel;
2109 } else {
2110 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2111 sctp_data_channels_.push_back(channel);
2112 channel->SignalClosed.connect(this,
2113 &PeerConnection::OnSctpDataChannelClosed);
2114 }
2115
hbos82ebe022016-11-14 01:41:09 -08002116 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002117 return channel;
2118}
2119
2120bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002121#ifdef HAVE_QUIC
2122 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2123 (session_->quic_data_transport() &&
2124 session_->quic_data_transport()->HasDataChannels());
2125#else
deadbeefab9b2d12015-10-14 11:33:11 -07002126 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002127#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002128}
2129
2130void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2131 for (const auto& channel : sctp_data_channels_) {
2132 if (channel->id() < 0) {
2133 int sid;
2134 if (!sid_allocator_.AllocateSid(role, &sid)) {
2135 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2136 continue;
2137 }
2138 channel->SetSctpSid(sid);
2139 }
2140 }
2141}
2142
2143void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002144 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002145 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2146 ++it) {
2147 if (it->get() == channel) {
2148 if (channel->id() >= 0) {
2149 sid_allocator_.ReleaseSid(channel->id());
2150 }
deadbeefbd292462015-12-14 18:15:29 -08002151 // Since this method is triggered by a signal from the DataChannel,
2152 // we can't free it directly here; we need to free it asynchronously.
2153 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002154 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002155 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2156 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002157 return;
2158 }
2159 }
2160}
2161
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002162void PeerConnection::OnVoiceChannelCreated() {
2163 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2164 session_->voice_channel(), senders_, receivers_,
2165 cricket::MEDIA_TYPE_AUDIO);
2166}
2167
deadbeefab9b2d12015-10-14 11:33:11 -07002168void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002169 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2170 cricket::VoiceChannel>(
2171 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2172}
2173
2174void PeerConnection::OnVideoChannelCreated() {
2175 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2176 session_->video_channel(), senders_, receivers_,
2177 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002178}
2179
2180void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002181 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2182 cricket::VideoChannel>(
2183 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002184}
2185
2186void PeerConnection::OnDataChannelCreated() {
2187 for (const auto& channel : sctp_data_channels_) {
2188 channel->OnTransportChannelCreated();
2189 }
2190}
2191
2192void PeerConnection::OnDataChannelDestroyed() {
2193 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2194 // DataChannel may callback to us and try to modify the list.
2195 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2196 temp_rtp_dcs.swap(rtp_data_channels_);
2197 for (const auto& kv : temp_rtp_dcs) {
2198 kv.second->OnTransportChannelDestroyed();
2199 }
2200
2201 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2202 temp_sctp_dcs.swap(sctp_data_channels_);
2203 for (const auto& channel : temp_sctp_dcs) {
2204 channel->OnTransportChannelDestroyed();
2205 }
2206}
2207
2208void PeerConnection::OnDataChannelOpenMessage(
2209 const std::string& label,
2210 const InternalDataChannelInit& config) {
2211 rtc::scoped_refptr<DataChannel> channel(
2212 InternalCreateDataChannel(label, &config));
2213 if (!channel.get()) {
2214 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2215 return;
2216 }
2217
deadbeefa601f5c2016-06-06 14:27:39 -07002218 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2219 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002220 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002221}
2222
deadbeefa601f5c2016-06-06 14:27:39 -07002223RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2224 auto it = std::find_if(
2225 senders_.begin(), senders_.end(),
2226 [id](const rtc::scoped_refptr<
2227 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2228 return sender->id() == id;
2229 });
2230 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002231}
2232
deadbeefa601f5c2016-06-06 14:27:39 -07002233std::vector<
2234 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002235PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2236 return std::find_if(
2237 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002238 [track](const rtc::scoped_refptr<
2239 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002240 return sender->track() == track;
2241 });
2242}
2243
deadbeefa601f5c2016-06-06 14:27:39 -07002244std::vector<rtc::scoped_refptr<
2245 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002246PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002247 return std::find_if(
2248 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002249 [track_id](const rtc::scoped_refptr<
2250 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002251 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002252 });
2253}
2254
deadbeefab9b2d12015-10-14 11:33:11 -07002255PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2256 cricket::MediaType media_type) {
2257 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2258 media_type == cricket::MEDIA_TYPE_VIDEO);
2259 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2260 : &remote_video_tracks_;
2261}
2262
2263PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2264 cricket::MediaType media_type) {
2265 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2266 media_type == cricket::MEDIA_TYPE_VIDEO);
2267 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2268 : &local_video_tracks_;
2269}
2270
2271const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2272 const PeerConnection::TrackInfos& infos,
2273 const std::string& stream_label,
2274 const std::string track_id) const {
2275 for (const TrackInfo& track_info : infos) {
2276 if (track_info.stream_label == stream_label &&
2277 track_info.track_id == track_id) {
2278 return &track_info;
2279 }
2280 }
2281 return nullptr;
2282}
2283
2284DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2285 for (const auto& channel : sctp_data_channels_) {
2286 if (channel->id() == sid) {
2287 return channel;
2288 }
2289 }
2290 return nullptr;
2291}
2292
deadbeef91dd5672016-05-18 16:55:30 -07002293bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002294 const RTCConfiguration& configuration) {
2295 cricket::ServerAddresses stun_servers;
2296 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002297 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2298 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002299 return false;
2300 }
2301
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002302 port_allocator_->Initialize();
2303
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002304 // To handle both internal and externally created port allocator, we will
2305 // enable BUNDLE here.
2306 int portallocator_flags = port_allocator_->flags();
2307 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002308 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2309 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002310 // If the disable-IPv6 flag was specified, we'll not override it
2311 // by experiment.
2312 if (configuration.disable_ipv6) {
2313 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002314 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2315 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002316 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2317 }
2318
zhihuangb09b3f92017-03-07 14:40:51 -08002319 if (configuration.disable_ipv6_on_wifi) {
2320 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2321 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2322 }
2323
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002324 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2325 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2326 LOG(LS_INFO) << "TCP candidates are disabled.";
2327 }
2328
honghaiz60347052016-05-31 18:29:12 -07002329 if (configuration.candidate_network_policy ==
2330 kCandidateNetworkPolicyLowCost) {
2331 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2332 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2333 }
2334
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002335 port_allocator_->set_flags(portallocator_flags);
2336 // No step delay is used while allocating ports.
2337 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2338 port_allocator_->set_candidate_filter(
2339 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2340
2341 // Call this last since it may create pooled allocator sessions using the
2342 // properties set above.
2343 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002344 configuration.ice_candidate_pool_size,
2345 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002346 return true;
2347}
2348
deadbeef91dd5672016-05-18 16:55:30 -07002349bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002350 const cricket::ServerAddresses& stun_servers,
2351 const std::vector<cricket::RelayServerConfig>& turn_servers,
2352 IceTransportsType type,
2353 int candidate_pool_size,
2354 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002355 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002356 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002357 // Call this last since it may create pooled allocator sessions using the
2358 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002359 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002360 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002361}
2362
ivoc14d5dbe2016-07-04 07:06:55 -07002363bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2364 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002365 if (!event_log_) {
2366 return false;
2367 }
skvlad11a9cbf2016-10-07 11:53:05 -07002368 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002369}
2370
2371void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002372 if (event_log_) {
2373 event_log_->StopLogging();
2374 }
ivoc14d5dbe2016-07-04 07:06:55 -07002375}
nisseeaabdf62017-05-05 02:23:02 -07002376
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377} // namespace webrtc