blob: f006b23cbda5197d9646f9e233ab15176f99b3af [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
Steve Anton038834f2017-07-14 15:59:59 -0700219bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
220 if (error_out) {
221 *error_out = std::move(error);
222 }
223 return error.ok();
224}
225
deadbeef0a6c4ca2015-10-06 11:38:28 -0700226} // namespace
227
228namespace webrtc {
229
deadbeef293e9262017-01-11 12:28:30 -0800230bool PeerConnectionInterface::RTCConfiguration::operator==(
231 const PeerConnectionInterface::RTCConfiguration& o) const {
232 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700233 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800234 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000235 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700236 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800237 BundlePolicy bundle_policy;
238 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700239 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
240 int ice_candidate_pool_size;
241 bool disable_ipv6;
242 bool disable_ipv6_on_wifi;
243 bool enable_rtp_data_channel;
244 rtc::Optional<int> screencast_min_bitrate;
245 rtc::Optional<bool> combined_audio_video_bwe;
246 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800247 TcpCandidatePolicy tcp_candidate_policy;
248 CandidateNetworkPolicy candidate_network_policy;
249 int audio_jitter_buffer_max_packets;
250 bool audio_jitter_buffer_fast_accelerate;
251 int ice_connection_receiving_timeout;
252 int ice_backup_candidate_pair_ping_interval;
253 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800254 bool prioritize_most_likely_ice_candidate_pairs;
255 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800256 bool enable_quic;
deadbeef293e9262017-01-11 12:28:30 -0800257 bool prune_turn_ports;
258 bool presume_writable_when_fully_relayed;
259 bool enable_ice_renomination;
260 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800261 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700262 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800263 };
264 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
265 "Did you add something to RTCConfiguration and forget to "
266 "update operator==?");
267 return type == o.type && servers == o.servers &&
268 bundle_policy == o.bundle_policy &&
269 rtcp_mux_policy == o.rtcp_mux_policy &&
270 tcp_candidate_policy == o.tcp_candidate_policy &&
271 candidate_network_policy == o.candidate_network_policy &&
272 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
273 audio_jitter_buffer_fast_accelerate ==
274 o.audio_jitter_buffer_fast_accelerate &&
275 ice_connection_receiving_timeout ==
276 o.ice_connection_receiving_timeout &&
277 ice_backup_candidate_pair_ping_interval ==
278 o.ice_backup_candidate_pair_ping_interval &&
279 continual_gathering_policy == o.continual_gathering_policy &&
280 certificates == o.certificates &&
281 prioritize_most_likely_ice_candidate_pairs ==
282 o.prioritize_most_likely_ice_candidate_pairs &&
283 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800284 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeef293e9262017-01-11 12:28:30 -0800285 enable_rtp_data_channel == o.enable_rtp_data_channel &&
286 enable_quic == o.enable_quic &&
287 screencast_min_bitrate == o.screencast_min_bitrate &&
288 combined_audio_video_bwe == o.combined_audio_video_bwe &&
289 enable_dtls_srtp == o.enable_dtls_srtp &&
290 ice_candidate_pool_size == o.ice_candidate_pool_size &&
291 prune_turn_ports == o.prune_turn_ports &&
292 presume_writable_when_fully_relayed ==
293 o.presume_writable_when_fully_relayed &&
294 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800295 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700296 ice_check_min_interval == o.ice_check_min_interval &&
297 ice_regather_interval_range == o.ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800298}
299
300bool PeerConnectionInterface::RTCConfiguration::operator!=(
301 const PeerConnectionInterface::RTCConfiguration& o) const {
302 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800303}
304
zhihuang8f65cdf2016-05-06 18:40:30 -0700305// Generate a RTCP CNAME when a PeerConnection is created.
306std::string GenerateRtcpCname() {
307 std::string cname;
308 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
309 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800310 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700311 }
312 return cname;
313}
314
htaa2a49d92016-03-04 02:51:39 -0800315bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700316 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800317 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700318 cricket::MediaSessionOptions* session_options) {
319 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
320 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
321 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
322 return false;
323 }
324
htaaac2dea2016-03-10 13:35:55 -0800325 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700326 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700327 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800328 } else {
329 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700330 }
htaaac2dea2016-03-10 13:35:55 -0800331 // For offers, we only offer video if we have it or it's forced by options.
332 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700333 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700334 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800335 } else if (is_offer) {
336 session_options->recv_video = false;
337 } else {
338 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700339 }
340
341 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700342 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800343 for (auto& kv : session_options->transport_options) {
344 kv.second.ice_restart = rtc_options.ice_restart;
345 }
deadbeefab9b2d12015-10-14 11:33:11 -0700346
347 return true;
348}
349
350bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
351 cricket::MediaSessionOptions* session_options) {
352 bool value = false;
353 size_t mandatory_constraints_satisfied = 0;
354
355 // kOfferToReceiveAudio defaults to true according to spec.
356 if (!FindConstraint(constraints,
357 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
358 &mandatory_constraints_satisfied) ||
359 value) {
360 session_options->recv_audio = true;
361 }
362
363 // kOfferToReceiveVideo defaults to false according to spec. But
364 // if it is an answer and video is offered, we should still accept video
365 // per default.
366 value = false;
367 if (!FindConstraint(constraints,
368 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
369 &mandatory_constraints_satisfied) ||
370 value) {
371 session_options->recv_video = true;
372 }
373
374 if (FindConstraint(constraints,
375 MediaConstraintsInterface::kVoiceActivityDetection, &value,
376 &mandatory_constraints_satisfied)) {
377 session_options->vad_enabled = value;
378 }
379
380 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
381 &mandatory_constraints_satisfied)) {
382 session_options->bundle_enabled = value;
383 } else {
384 // kUseRtpMux defaults to true according to spec.
385 session_options->bundle_enabled = true;
386 }
deadbeefab9b2d12015-10-14 11:33:11 -0700387
deadbeef0ed85b22016-02-23 17:24:52 -0800388 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700389 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
390 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700391 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800392 ice_restart = true;
393 }
394 for (auto& kv : session_options->transport_options) {
395 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700396 }
397
398 if (!constraints) {
399 return true;
400 }
401 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
402}
403
zhihuang38ede132017-06-15 12:52:32 -0700404PeerConnection::PeerConnection(PeerConnectionFactory* factory,
405 std::unique_ptr<RtcEventLog> event_log,
406 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000407 : factory_(factory),
408 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000409 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700410 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000411 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000412 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700413 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700414 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700415 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700416 remote_streams_(StreamCollection::Create()),
417 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000418
419PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100420 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700421 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700422 // Need to detach RTP senders/receivers from WebRtcSession,
423 // since it's about to be destroyed.
424 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700425 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700426 }
427 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700428 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700429 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700430 // Destroy stats_ because it depends on session_.
431 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800432 if (stats_collector_) {
433 stats_collector_->WaitForPendingRequest();
434 stats_collector_ = nullptr;
435 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700436 // Now destroy session_ before destroying other members,
437 // because its destruction fires signals (such as VoiceChannelDestroyed)
438 // which will trigger some final actions in PeerConnection...
439 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700440 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700441 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700442 [this] { port_allocator_.reset(); });
443 // call_ must be destroyed on the worker thread.
444 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
445 [this] { call_.reset(); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000446}
447
448bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000449 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700450 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200451 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800452 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100453 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700454
455 RTCError config_error = ValidateConfiguration(configuration);
456 if (!config_error.ok()) {
457 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
458 return false;
459 }
460
deadbeef293e9262017-01-11 12:28:30 -0800461 if (!allocator) {
462 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
463 << "This shouldn't happen if using PeerConnectionFactory.";
464 return false;
465 }
deadbeef653b8e02015-11-11 12:55:10 -0800466 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800467 // TODO(deadbeef): Why do we do this?
468 LOG(LS_ERROR) << "PeerConnection initialized without a "
469 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800470 return false;
471 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000472 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800473 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800474
deadbeef91dd5672016-05-18 16:55:30 -0700475 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700476 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700477 if (!network_thread()->Invoke<bool>(
478 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
479 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000480 return false;
481 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000482
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000483
zhihuang29ff8442016-07-27 11:07:25 -0700484 session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700485 call_.get(), factory_->channel_manager(), configuration.media_config,
486 event_log_.get(),
487 factory_->network_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700488 factory_->worker_thread(), factory_->signaling_thread(),
489 port_allocator_.get(),
490 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700491 factory_->CreateTransportController(
492 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800493 configuration.redetermine_role_on_ice_restart)),
494#ifdef HAVE_SCTP
495 std::unique_ptr<cricket::SctpTransportInternalFactory>(
496 new cricket::SctpTransportFactory(factory_->network_thread()))
497#else
498 nullptr
499#endif
500 ));
zhihuang29ff8442016-07-27 11:07:25 -0700501
deadbeefab9b2d12015-10-14 11:33:11 -0700502 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700503 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000504
505 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200506 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800507 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000508 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700509 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000510
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000511 // Register PeerConnection as receiver of local ice candidates.
512 // All the callbacks will be posted to the application from PeerConnection.
513 session_->RegisterIceObserver(this);
514 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700515 session_->SignalVoiceChannelCreated.connect(
516 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700517 session_->SignalVoiceChannelDestroyed.connect(
518 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700519 session_->SignalVideoChannelCreated.connect(
520 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700521 session_->SignalVideoChannelDestroyed.connect(
522 this, &PeerConnection::OnVideoChannelDestroyed);
523 session_->SignalDataChannelCreated.connect(
524 this, &PeerConnection::OnDataChannelCreated);
525 session_->SignalDataChannelDestroyed.connect(
526 this, &PeerConnection::OnDataChannelDestroyed);
527 session_->SignalDataChannelOpenMessage.connect(
528 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800529
530 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531 return true;
532}
533
Steve Anton038834f2017-07-14 15:59:59 -0700534RTCError PeerConnection::ValidateConfiguration(
535 const RTCConfiguration& config) const {
536 if (config.ice_regather_interval_range &&
537 config.continual_gathering_policy == GATHER_ONCE) {
538 return RTCError(RTCErrorType::INVALID_PARAMETER,
539 "ice_regather_interval_range specified but continual "
540 "gathering policy is GATHER_ONCE");
541 }
542 return RTCError::OK();
543}
544
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000545rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000546PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700547 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000548}
549
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000550rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000551PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700552 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000553}
554
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000555bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100556 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000557 if (IsClosed()) {
558 return false;
559 }
deadbeefab9b2d12015-10-14 11:33:11 -0700560 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000561 return false;
562 }
deadbeefab9b2d12015-10-14 11:33:11 -0700563
564 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800565 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
566 observer->SignalAudioTrackAdded.connect(this,
567 &PeerConnection::OnAudioTrackAdded);
568 observer->SignalAudioTrackRemoved.connect(
569 this, &PeerConnection::OnAudioTrackRemoved);
570 observer->SignalVideoTrackAdded.connect(this,
571 &PeerConnection::OnVideoTrackAdded);
572 observer->SignalVideoTrackRemoved.connect(
573 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700574 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700575
deadbeefab9b2d12015-10-14 11:33:11 -0700576 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700577 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700578 }
579 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700580 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700581 }
582
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000583 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000584 observer_->OnRenegotiationNeeded();
585 return true;
586}
587
588void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100589 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700590 if (!IsClosed()) {
591 for (const auto& track : local_stream->GetAudioTracks()) {
592 RemoveAudioTrack(track.get(), local_stream);
593 }
594 for (const auto& track : local_stream->GetVideoTracks()) {
595 RemoveVideoTrack(track.get(), local_stream);
596 }
deadbeefab9b2d12015-10-14 11:33:11 -0700597 }
deadbeefab9b2d12015-10-14 11:33:11 -0700598 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800599 stream_observers_.erase(
600 std::remove_if(
601 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700602 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800603 return observer->stream()->label().compare(local_stream->label()) ==
604 0;
605 }),
606 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700607
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608 if (IsClosed()) {
609 return;
610 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000611 observer_->OnRenegotiationNeeded();
612}
613
deadbeefe1f9d832016-01-14 15:35:42 -0800614rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
615 MediaStreamTrackInterface* track,
616 std::vector<MediaStreamInterface*> streams) {
617 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
618 if (IsClosed()) {
619 return nullptr;
620 }
621 if (streams.size() >= 2) {
622 LOG(LS_ERROR)
623 << "Adding a track with two streams is not currently supported.";
624 return nullptr;
625 }
626 // TODO(deadbeef): Support adding a track to two different senders.
627 if (FindSenderForTrack(track) != senders_.end()) {
628 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
629 return nullptr;
630 }
631
632 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700633 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800634 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700635 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800636 signaling_thread(),
637 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700638 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800639 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700640 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800641 }
642 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700643 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800644 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700645 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800646 }
647 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700648 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800649 signaling_thread(),
650 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700651 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800652 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700653 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800654 }
655 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700656 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800657 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700658 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800659 }
660 } else {
661 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
662 return rtc::scoped_refptr<RtpSenderInterface>();
663 }
664
665 senders_.push_back(new_sender);
666 observer_->OnRenegotiationNeeded();
667 return new_sender;
668}
669
670bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
671 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
672 if (IsClosed()) {
673 return false;
674 }
675
676 auto it = std::find(senders_.begin(), senders_.end(), sender);
677 if (it == senders_.end()) {
678 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
679 return false;
680 }
deadbeefa601f5c2016-06-06 14:27:39 -0700681 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800682 senders_.erase(it);
683
684 observer_->OnRenegotiationNeeded();
685 return true;
686}
687
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000688rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100690 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700691 if (IsClosed()) {
692 return nullptr;
693 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000694 if (!track) {
695 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800696 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000697 }
deadbeef20cb0c12017-02-01 20:27:00 -0800698 auto it = FindSenderForTrack(track);
699 if (it == senders_.end()) {
700 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
701 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702 }
703
deadbeef20cb0c12017-02-01 20:27:00 -0800704 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705}
706
deadbeeffac06552015-11-25 11:26:01 -0800707rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800708 const std::string& kind,
709 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100710 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700711 if (IsClosed()) {
712 return nullptr;
713 }
deadbeefa601f5c2016-06-06 14:27:39 -0700714 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800715 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700716 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700717 signaling_thread(),
718 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800719 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700720 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700721 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800722 } else {
723 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800724 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800725 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800726 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700727 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800728 }
deadbeeffac06552015-11-25 11:26:01 -0800729 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800730 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800731}
732
deadbeef70ab1a12015-09-28 16:53:55 -0700733std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
734 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700735 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
736 for (const auto& sender : senders_) {
737 ret.push_back(sender.get());
738 }
739 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700740}
741
742std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
743PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700744 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
745 for (const auto& receiver : receivers_) {
746 ret.push_back(receiver.get());
747 }
748 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700749}
750
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000751bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000752 MediaStreamTrackInterface* track,
753 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100754 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700755 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800756 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000757 LOG(LS_ERROR) << "GetStats - observer is NULL.";
758 return false;
759 }
760
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000761 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700762 // The StatsCollector is used to tell if a track is valid because it may
763 // remember tracks that the PeerConnection previously removed.
764 if (track && !stats_->IsValidTrack(track->id())) {
765 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
766 << track->id();
767 return false;
768 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700769 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000770 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771 return true;
772}
773
hbos74e1a4f2016-09-15 23:33:01 -0700774void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
775 RTC_DCHECK(stats_collector_);
776 stats_collector_->GetStatsReport(callback);
777}
778
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
780 return signaling_state_;
781}
782
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783PeerConnectionInterface::IceConnectionState
784PeerConnection::ice_connection_state() {
785 return ice_connection_state_;
786}
787
788PeerConnectionInterface::IceGatheringState
789PeerConnection::ice_gathering_state() {
790 return ice_gathering_state_;
791}
792
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000793rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794PeerConnection::CreateDataChannel(
795 const std::string& label,
796 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100797 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700798#ifdef HAVE_QUIC
799 if (session_->data_channel_type() == cricket::DCT_QUIC) {
800 // TODO(zhihuang): Handle case when config is NULL.
801 if (!config) {
802 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
803 return nullptr;
804 }
805 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
806 if (!config->reliable || config->ordered) {
807 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
808 "ordered delivery.";
809 return nullptr;
810 }
811 return session_->quic_data_transport()->CreateDataChannel(label, config);
812 }
813#endif // HAVE_QUIC
814
deadbeefab9b2d12015-10-14 11:33:11 -0700815 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000816
kwibergd1fe2812016-04-27 06:47:29 -0700817 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000818 if (config) {
819 internal_config.reset(new InternalDataChannelInit(*config));
820 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000821 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700822 InternalCreateDataChannel(label, internal_config.get()));
823 if (!channel.get()) {
824 return nullptr;
825 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000827 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
828 // the first SCTP DataChannel.
829 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
830 observer_->OnRenegotiationNeeded();
831 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000832
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 return DataChannelProxy::Create(signaling_thread(), channel.get());
834}
835
836void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
837 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100838 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800839 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
841 return;
842 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000843 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000844
845 bool value;
846 size_t mandatory_constraints = 0;
847
848 if (FindConstraint(constraints,
849 MediaConstraintsInterface::kOfferToReceiveAudio,
850 &value,
851 &mandatory_constraints)) {
852 options.offer_to_receive_audio =
853 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
854 }
855
856 if (FindConstraint(constraints,
857 MediaConstraintsInterface::kOfferToReceiveVideo,
858 &value,
859 &mandatory_constraints)) {
860 options.offer_to_receive_video =
861 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
862 }
863
864 if (FindConstraint(constraints,
865 MediaConstraintsInterface::kVoiceActivityDetection,
866 &value,
867 &mandatory_constraints)) {
868 options.voice_activity_detection = value;
869 }
870
871 if (FindConstraint(constraints,
872 MediaConstraintsInterface::kIceRestart,
873 &value,
874 &mandatory_constraints)) {
875 options.ice_restart = value;
876 }
877
878 if (FindConstraint(constraints,
879 MediaConstraintsInterface::kUseRtpMux,
880 &value,
881 &mandatory_constraints)) {
882 options.use_rtp_mux = value;
883 }
884
885 CreateOffer(observer, options);
886}
887
888void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
889 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100890 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800891 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000892 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
893 return;
894 }
deadbeefab9b2d12015-10-14 11:33:11 -0700895
896 cricket::MediaSessionOptions session_options;
897 if (!GetOptionsForOffer(options, &session_options)) {
898 std::string error = "CreateOffer called with invalid options.";
899 LOG(LS_ERROR) << error;
900 PostCreateSessionDescriptionFailure(observer, error);
901 return;
902 }
903
904 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905}
906
907void PeerConnection::CreateAnswer(
908 CreateSessionDescriptionObserver* observer,
909 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100910 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800911 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000912 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
913 return;
914 }
deadbeefab9b2d12015-10-14 11:33:11 -0700915
916 cricket::MediaSessionOptions session_options;
917 if (!GetOptionsForAnswer(constraints, &session_options)) {
918 std::string error = "CreateAnswer called with invalid constraints.";
919 LOG(LS_ERROR) << error;
920 PostCreateSessionDescriptionFailure(observer, error);
921 return;
922 }
923
htaa2a49d92016-03-04 02:51:39 -0800924 session_->CreateAnswer(observer, session_options);
925}
926
927void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
928 const RTCOfferAnswerOptions& options) {
929 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800930 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800931 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
932 return;
933 }
934
935 cricket::MediaSessionOptions session_options;
936 if (!GetOptionsForAnswer(options, &session_options)) {
937 std::string error = "CreateAnswer called with invalid options.";
938 LOG(LS_ERROR) << error;
939 PostCreateSessionDescriptionFailure(observer, error);
940 return;
941 }
942
943 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944}
945
946void PeerConnection::SetLocalDescription(
947 SetSessionDescriptionObserver* observer,
948 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100949 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700950 if (IsClosed()) {
951 return;
952 }
nisse7ce109a2017-01-31 00:57:56 -0800953 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
955 return;
956 }
957 if (!desc) {
958 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
959 return;
960 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961 // Update stats here so that we have the most recent stats for tracks and
962 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000963 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000964 std::string error;
965 if (!session_->SetLocalDescription(desc, &error)) {
966 PostSetSessionDescriptionFailure(observer, error);
967 return;
968 }
deadbeefab9b2d12015-10-14 11:33:11 -0700969
970 // If setting the description decided our SSL role, allocate any necessary
971 // SCTP sids.
972 rtc::SSLRole role;
973 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800974 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700975 AllocateSctpSids(role);
976 }
977
978 // Update state and SSRC of local MediaStreams and DataChannels based on the
979 // local session description.
980 const cricket::ContentInfo* audio_content =
981 GetFirstAudioContent(desc->description());
982 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800983 if (audio_content->rejected) {
984 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
985 } else {
986 const cricket::AudioContentDescription* audio_desc =
987 static_cast<const cricket::AudioContentDescription*>(
988 audio_content->description);
989 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
990 }
deadbeefab9b2d12015-10-14 11:33:11 -0700991 }
992
993 const cricket::ContentInfo* video_content =
994 GetFirstVideoContent(desc->description());
995 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800996 if (video_content->rejected) {
997 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
998 } else {
999 const cricket::VideoContentDescription* video_desc =
1000 static_cast<const cricket::VideoContentDescription*>(
1001 video_content->description);
1002 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1003 }
deadbeefab9b2d12015-10-14 11:33:11 -07001004 }
1005
1006 const cricket::ContentInfo* data_content =
1007 GetFirstDataContent(desc->description());
1008 if (data_content) {
1009 const cricket::DataContentDescription* data_desc =
1010 static_cast<const cricket::DataContentDescription*>(
1011 data_content->description);
1012 if (rtc::starts_with(data_desc->protocol().data(),
1013 cricket::kMediaProtocolRtpPrefix)) {
1014 UpdateLocalRtpDataChannels(data_desc->streams());
1015 }
1016 }
1017
1018 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001019 signaling_thread()->Post(RTC_FROM_HERE, this,
1020 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001021
deadbeef42a42632017-03-10 15:18:00 -08001022 // According to JSEP, after setLocalDescription, changing the candidate pool
1023 // size is not allowed, and changing the set of ICE servers will not result
1024 // in new candidates being gathered.
1025 port_allocator_->FreezeCandidatePool();
1026
deadbeefcbecd352015-09-23 11:50:27 -07001027 // MaybeStartGathering needs to be called after posting
1028 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1029 // before signaling that SetLocalDescription completed.
1030 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001031
1032 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1033 // TODO(deadbeef): We already had to hop to the network thread for
1034 // MaybeStartGathering...
1035 network_thread()->Invoke<void>(
1036 RTC_FROM_HERE,
1037 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1038 port_allocator_.get()));
1039 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001040}
1041
1042void PeerConnection::SetRemoteDescription(
1043 SetSessionDescriptionObserver* observer,
1044 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001045 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001046 if (IsClosed()) {
1047 return;
1048 }
nisse7ce109a2017-01-31 00:57:56 -08001049 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1051 return;
1052 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053 if (!desc) {
1054 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1055 return;
1056 }
1057 // Update stats here so that we have the most recent stats for tracks and
1058 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001059 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060 std::string error;
1061 if (!session_->SetRemoteDescription(desc, &error)) {
1062 PostSetSessionDescriptionFailure(observer, error);
1063 return;
1064 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065
deadbeefab9b2d12015-10-14 11:33:11 -07001066 // If setting the description decided our SSL role, allocate any necessary
1067 // SCTP sids.
1068 rtc::SSLRole role;
1069 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001070 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001071 AllocateSctpSids(role);
1072 }
1073
1074 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001075 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1076 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1077 const cricket::AudioContentDescription* audio_desc =
1078 GetFirstAudioContentDescription(remote_desc);
1079 const cricket::VideoContentDescription* video_desc =
1080 GetFirstVideoContentDescription(remote_desc);
1081 const cricket::DataContentDescription* data_desc =
1082 GetFirstDataContentDescription(remote_desc);
1083
1084 // Check if the descriptions include streams, just in case the peer supports
1085 // MSID, but doesn't indicate so with "a=msid-semantic".
1086 if (remote_desc->msid_supported() ||
1087 (audio_desc && !audio_desc->streams().empty()) ||
1088 (video_desc && !video_desc->streams().empty())) {
1089 remote_peer_supports_msid_ = true;
1090 }
deadbeefab9b2d12015-10-14 11:33:11 -07001091
1092 // We wait to signal new streams until we finish processing the description,
1093 // since only at that point will new streams have all their tracks.
1094 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1095
1096 // Find all audio rtp streams and create corresponding remote AudioTracks
1097 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001098 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001099 if (audio_content->rejected) {
1100 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1101 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001102 bool default_audio_track_needed =
1103 !remote_peer_supports_msid_ &&
1104 MediaContentDirectionHasSend(audio_desc->direction());
1105 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1106 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001107 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 }
1110
1111 // Find all video rtp streams and create corresponding remote VideoTracks
1112 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001113 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001114 if (video_content->rejected) {
1115 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1116 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001117 bool default_video_track_needed =
1118 !remote_peer_supports_msid_ &&
1119 MediaContentDirectionHasSend(video_desc->direction());
1120 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1121 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001122 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001123 }
deadbeefab9b2d12015-10-14 11:33:11 -07001124 }
1125
1126 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001127 if (data_desc) {
1128 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001129 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001130 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001131 }
1132 }
1133
1134 // Iterate new_streams and notify the observer about new MediaStreams.
1135 for (size_t i = 0; i < new_streams->count(); ++i) {
1136 MediaStreamInterface* new_stream = new_streams->at(i);
1137 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001138 observer_->OnAddStream(
1139 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001140 }
1141
deadbeefbda7e0b2015-12-08 17:13:40 -08001142 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001143
1144 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001145 signaling_thread()->Post(RTC_FROM_HERE, this,
1146 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001147
1148 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1149 // TODO(deadbeef): We already had to hop to the network thread for
1150 // MaybeStartGathering...
1151 network_thread()->Invoke<void>(
1152 RTC_FROM_HERE,
1153 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1154 port_allocator_.get()));
1155 }
deadbeeffc648b62015-10-13 16:42:33 -07001156}
1157
deadbeef46c73892016-11-16 19:42:04 -08001158PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1159 return configuration_;
1160}
1161
deadbeef293e9262017-01-11 12:28:30 -08001162bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1163 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001164 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001165
1166 if (session_->local_description() &&
1167 configuration.ice_candidate_pool_size !=
1168 configuration_.ice_candidate_pool_size) {
1169 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1170 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001171 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001172 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001173
deadbeef293e9262017-01-11 12:28:30 -08001174 // The simplest (and most future-compatible) way to tell if the config was
1175 // modified in an invalid way is to copy each property we do support
1176 // modifying, then use operator==. There are far more properties we don't
1177 // support modifying than those we do, and more could be added.
1178 RTCConfiguration modified_config = configuration_;
1179 modified_config.servers = configuration.servers;
1180 modified_config.type = configuration.type;
1181 modified_config.ice_candidate_pool_size =
1182 configuration.ice_candidate_pool_size;
1183 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001184 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001185 if (configuration != modified_config) {
1186 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1187 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1188 }
1189
Steve Anton038834f2017-07-14 15:59:59 -07001190 // Validate the modified configuration.
1191 RTCError validate_error = ValidateConfiguration(modified_config);
1192 if (!validate_error.ok()) {
1193 return SafeSetError(std::move(validate_error), error);
1194 }
1195
deadbeef293e9262017-01-11 12:28:30 -08001196 // Note that this isn't possible through chromium, since it's an unsigned
1197 // short in WebIDL.
1198 if (configuration.ice_candidate_pool_size < 0 ||
1199 configuration.ice_candidate_pool_size > UINT16_MAX) {
1200 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1201 }
1202
1203 // Parse ICE servers before hopping to network thread.
1204 cricket::ServerAddresses stun_servers;
1205 std::vector<cricket::RelayServerConfig> turn_servers;
1206 RTCErrorType parse_error =
1207 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1208 if (parse_error != RTCErrorType::NONE) {
1209 return SafeSetError(parse_error, error);
1210 }
1211
1212 // In theory this shouldn't fail.
1213 if (!network_thread()->Invoke<bool>(
1214 RTC_FROM_HERE,
1215 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1216 stun_servers, turn_servers, modified_config.type,
1217 modified_config.ice_candidate_pool_size,
1218 modified_config.prune_turn_ports))) {
1219 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1220 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1221 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001222
deadbeefd1a38b52016-12-10 13:15:33 -08001223 // As described in JSEP, calling setConfiguration with new ICE servers or
1224 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1225 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001226 if (modified_config.servers != configuration_.servers ||
1227 modified_config.type != configuration_.type ||
1228 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001229 session_->SetNeedsIceRestartFlag();
1230 }
skvladd1f5fda2017-02-03 16:54:05 -08001231
1232 if (modified_config.ice_check_min_interval !=
1233 configuration_.ice_check_min_interval) {
1234 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1235 }
1236
deadbeef293e9262017-01-11 12:28:30 -08001237 configuration_ = modified_config;
1238 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001239}
1240
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241bool PeerConnection::AddIceCandidate(
1242 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001243 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001244 if (IsClosed()) {
1245 return false;
1246 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247 return session_->ProcessIceMessage(ice_candidate);
1248}
1249
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001250bool PeerConnection::RemoveIceCandidates(
1251 const std::vector<cricket::Candidate>& candidates) {
1252 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1253 return session_->RemoveRemoteIceCandidates(candidates);
1254}
1255
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001256void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001257 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001258 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001259
1260 if (session_) {
1261 session_->set_metrics_observer(uma_observer_);
1262 }
1263
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001264 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001265 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001266 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001267 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001268 uma_observer_->IncrementEnumCounter(
1269 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1270 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001271 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001272 uma_observer_->IncrementEnumCounter(
1273 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1274 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001275 }
1276 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001277}
1278
zstein4b979802017-06-02 14:37:37 -07001279RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
1280 rtc::Thread* worker_thread = factory_->worker_thread();
1281 if (!worker_thread->IsCurrent()) {
1282 return worker_thread->Invoke<RTCError>(
1283 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1284 }
1285
1286 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1287 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1288 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1289 if (has_min && *bitrate.min_bitrate_bps < 0) {
1290 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1291 "min_bitrate_bps <= 0");
1292 }
1293 if (has_current) {
1294 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1295 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1296 "current_bitrate_bps < min_bitrate_bps");
1297 } else if (*bitrate.current_bitrate_bps < 0) {
1298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1299 "curent_bitrate_bps < 0");
1300 }
1301 }
1302 if (has_max) {
1303 if (has_current &&
1304 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1306 "max_bitrate_bps < current_bitrate_bps");
1307 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1308 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1309 "max_bitrate_bps < min_bitrate_bps");
1310 } else if (*bitrate.max_bitrate_bps < 0) {
1311 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1312 "max_bitrate_bps < 0");
1313 }
1314 }
1315
1316 Call::Config::BitrateConfigMask mask;
1317 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1318 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1319 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1320
1321 RTC_DCHECK(call_.get());
1322 call_->SetBitrateConfigMask(mask);
1323
1324 return RTCError::OK();
1325}
1326
ivoc14d5dbe2016-07-04 07:06:55 -07001327bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1328 int64_t max_size_bytes) {
1329 return factory_->worker_thread()->Invoke<bool>(
1330 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1331 max_size_bytes));
1332}
1333
1334void PeerConnection::StopRtcEventLog() {
1335 factory_->worker_thread()->Invoke<void>(
1336 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1337}
1338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339const SessionDescriptionInterface* PeerConnection::local_description() const {
1340 return session_->local_description();
1341}
1342
1343const SessionDescriptionInterface* PeerConnection::remote_description() const {
1344 return session_->remote_description();
1345}
1346
deadbeeffe4a8a42016-12-20 17:56:17 -08001347const SessionDescriptionInterface* PeerConnection::current_local_description()
1348 const {
1349 return session_->current_local_description();
1350}
1351
1352const SessionDescriptionInterface* PeerConnection::current_remote_description()
1353 const {
1354 return session_->current_remote_description();
1355}
1356
1357const SessionDescriptionInterface* PeerConnection::pending_local_description()
1358 const {
1359 return session_->pending_local_description();
1360}
1361
1362const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1363 const {
1364 return session_->pending_remote_description();
1365}
1366
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001368 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 // Update stats here so that we have the most recent stats for tracks and
1370 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001371 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372
deadbeefd59daf82015-10-14 15:02:44 -07001373 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001374 network_thread()->Invoke<void>(
1375 RTC_FROM_HERE,
1376 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1377 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001378
1379 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
1380 [this] { call_.reset(); });
terelius33860252017-05-12 23:37:18 -07001381
1382 // The event log must outlive call (and any other object that uses it).
1383 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384}
1385
deadbeefd59daf82015-10-14 15:02:44 -07001386void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1387 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001389 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001391 break;
deadbeefd59daf82015-10-14 15:02:44 -07001392 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1394 break;
deadbeefd59daf82015-10-14 15:02:44 -07001395 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1397 break;
deadbeefd59daf82015-10-14 15:02:44 -07001398 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001399 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1400 break;
deadbeefd59daf82015-10-14 15:02:44 -07001401 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1403 break;
deadbeefd59daf82015-10-14 15:02:44 -07001404 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405 ChangeSignalingState(PeerConnectionInterface::kStable);
1406 break;
deadbeefd59daf82015-10-14 15:02:44 -07001407 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 ChangeSignalingState(PeerConnectionInterface::kClosed);
1409 break;
1410 default:
1411 break;
1412 }
1413}
1414
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001415void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001417 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1418 SetSessionDescriptionMsg* param =
1419 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1420 param->observer->OnSuccess();
1421 delete param;
1422 break;
1423 }
1424 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1425 SetSessionDescriptionMsg* param =
1426 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1427 param->observer->OnFailure(param->error);
1428 delete param;
1429 break;
1430 }
deadbeefab9b2d12015-10-14 11:33:11 -07001431 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1432 CreateSessionDescriptionMsg* param =
1433 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1434 param->observer->OnFailure(param->error);
1435 delete param;
1436 break;
1437 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001438 case MSG_GETSTATS: {
1439 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001440 StatsReports reports;
1441 stats_->GetStats(param->track, &reports);
1442 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443 delete param;
1444 break;
1445 }
deadbeefbd292462015-12-14 18:15:29 -08001446 case MSG_FREE_DATACHANNELS: {
1447 sctp_data_channels_to_free_.clear();
1448 break;
1449 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001451 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452 break;
1453 }
1454}
1455
deadbeefab9b2d12015-10-14 11:33:11 -07001456void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001457 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001458 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001459 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1460 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001461 signaling_thread(),
1462 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1463 stream->AddTrack(
1464 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001465 receivers_.push_back(receiver);
1466 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1467 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1468 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469}
1470
deadbeefab9b2d12015-10-14 11:33:11 -07001471void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001472 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001473 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001474 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1475 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001476 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001477 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1478 session_->video_channel()));
1479 stream->AddTrack(
1480 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001481 receivers_.push_back(receiver);
1482 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1483 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1484 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485}
1486
deadbeef70ab1a12015-09-28 16:53:55 -07001487// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1488// description.
perkjd61bf802016-03-24 03:16:19 -07001489void PeerConnection::DestroyReceiver(const std::string& track_id) {
1490 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001491 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001492 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001493 << " doesn't exist.";
1494 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001495 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001496 receivers_.erase(it);
1497 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001498}
1499
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001500void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1501 MediaStreamInterface* stream) {
1502 RTC_DCHECK(!IsClosed());
1503 auto sender = FindSenderForTrack(track);
1504 if (sender != senders_.end()) {
1505 // We already have a sender for this track, so just change the stream_id
1506 // so that it's correct in the next call to CreateOffer.
1507 (*sender)->internal()->set_stream_id(stream->label());
1508 return;
1509 }
1510
1511 // Normal case; we've never seen this track before.
1512 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1513 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1514 signaling_thread(),
1515 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1516 stats_.get()));
1517 senders_.push_back(new_sender);
1518 // If the sender has already been configured in SDP, we call SetSsrc,
1519 // which will connect the sender to the underlying transport. This can
1520 // occur if a local session description that contains the ID of the sender
1521 // is set before AddStream is called. It can also occur if the local
1522 // session description is not changed and RemoveStream is called, and
1523 // later AddStream is called again with the same stream.
1524 const TrackInfo* track_info =
1525 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1526 if (track_info) {
1527 new_sender->internal()->SetSsrc(track_info->ssrc);
1528 }
1529}
1530
1531// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1532// indefinitely, when we have unified plan SDP.
1533void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1534 MediaStreamInterface* stream) {
1535 RTC_DCHECK(!IsClosed());
1536 auto sender = FindSenderForTrack(track);
1537 if (sender == senders_.end()) {
1538 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1539 << " doesn't exist.";
1540 return;
1541 }
1542 (*sender)->internal()->Stop();
1543 senders_.erase(sender);
1544}
1545
1546void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1547 MediaStreamInterface* stream) {
1548 RTC_DCHECK(!IsClosed());
1549 auto sender = FindSenderForTrack(track);
1550 if (sender != senders_.end()) {
1551 // We already have a sender for this track, so just change the stream_id
1552 // so that it's correct in the next call to CreateOffer.
1553 (*sender)->internal()->set_stream_id(stream->label());
1554 return;
1555 }
1556
1557 // Normal case; we've never seen this track before.
1558 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1559 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1560 signaling_thread(), new VideoRtpSender(track, stream->label(),
1561 session_->video_channel()));
1562 senders_.push_back(new_sender);
1563 const TrackInfo* track_info =
1564 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1565 if (track_info) {
1566 new_sender->internal()->SetSsrc(track_info->ssrc);
1567 }
1568}
1569
1570void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1571 MediaStreamInterface* stream) {
1572 RTC_DCHECK(!IsClosed());
1573 auto sender = FindSenderForTrack(track);
1574 if (sender == senders_.end()) {
1575 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1576 << " doesn't exist.";
1577 return;
1578 }
1579 (*sender)->internal()->Stop();
1580 senders_.erase(sender);
1581}
1582
zstein6dfd53a2017-03-06 13:49:03 -08001583void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001585 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001586 // After transitioning to "closed", ignore any additional states from
1587 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001588 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001589 return;
1590 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001592 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001593}
1594
1595void PeerConnection::OnIceGatheringChange(
1596 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001597 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001598 if (IsClosed()) {
1599 return;
1600 }
1601 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001602 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603}
1604
jbauch81bf7b02017-03-25 08:31:12 -07001605void PeerConnection::OnIceCandidate(
1606 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001607 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001608 if (IsClosed()) {
1609 return;
1610 }
jbauch81bf7b02017-03-25 08:31:12 -07001611 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612}
1613
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001614void PeerConnection::OnIceCandidatesRemoved(
1615 const std::vector<cricket::Candidate>& candidates) {
1616 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001617 if (IsClosed()) {
1618 return;
1619 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001620 observer_->OnIceCandidatesRemoved(candidates);
1621}
1622
Peter Thatcher54360512015-07-08 11:08:35 -07001623void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001624 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001625 if (IsClosed()) {
1626 return;
1627 }
Peter Thatcher54360512015-07-08 11:08:35 -07001628 observer_->OnIceConnectionReceivingChange(receiving);
1629}
1630
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001631void PeerConnection::ChangeSignalingState(
1632 PeerConnectionInterface::SignalingState signaling_state) {
1633 signaling_state_ = signaling_state;
1634 if (signaling_state == kClosed) {
1635 ice_connection_state_ = kIceConnectionClosed;
1636 observer_->OnIceConnectionChange(ice_connection_state_);
1637 if (ice_gathering_state_ != kIceGatheringComplete) {
1638 ice_gathering_state_ = kIceGatheringComplete;
1639 observer_->OnIceGatheringChange(ice_gathering_state_);
1640 }
1641 }
1642 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001643}
1644
deadbeefeb459812015-12-15 19:24:43 -08001645void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1646 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001647 if (IsClosed()) {
1648 return;
1649 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001650 AddAudioTrack(track, stream);
1651 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001652}
1653
deadbeefeb459812015-12-15 19:24:43 -08001654void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1655 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001656 if (IsClosed()) {
1657 return;
1658 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001659 RemoveAudioTrack(track, stream);
1660 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001661}
1662
1663void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1664 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001665 if (IsClosed()) {
1666 return;
1667 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001668 AddVideoTrack(track, stream);
1669 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001670}
1671
1672void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1673 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001674 if (IsClosed()) {
1675 return;
1676 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001677 RemoveVideoTrack(track, stream);
1678 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001679}
1680
deadbeefab9b2d12015-10-14 11:33:11 -07001681void PeerConnection::PostSetSessionDescriptionFailure(
1682 SetSessionDescriptionObserver* observer,
1683 const std::string& error) {
1684 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1685 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001686 signaling_thread()->Post(RTC_FROM_HERE, this,
1687 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001688}
1689
1690void PeerConnection::PostCreateSessionDescriptionFailure(
1691 CreateSessionDescriptionObserver* observer,
1692 const std::string& error) {
1693 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1694 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001695 signaling_thread()->Post(RTC_FROM_HERE, this,
1696 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001697}
1698
1699bool PeerConnection::GetOptionsForOffer(
1700 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1701 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001702 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1703 // ContentInfos.
1704 if (session_->local_description()) {
1705 for (const cricket::ContentInfo& content :
1706 session_->local_description()->description()->contents()) {
1707 session_options->transport_options[content.name] =
1708 cricket::TransportOptions();
1709 }
1710 }
deadbeef46c73892016-11-16 19:42:04 -08001711 session_options->enable_ice_renomination =
1712 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001713
htaaac2dea2016-03-10 13:35:55 -08001714 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001715 return false;
1716 }
1717
deadbeeffac06552015-11-25 11:26:01 -08001718 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001719 // Offer to receive audio/video if the constraint is not set and there are
1720 // send streams, or we're currently receiving.
1721 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1722 session_options->recv_audio =
1723 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1724 !remote_audio_tracks_.empty();
1725 }
1726 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1727 session_options->recv_video =
1728 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1729 !remote_video_tracks_.empty();
1730 }
deadbeefc80741f2015-10-22 13:14:45 -07001731
zhihuang9763d562016-08-05 11:14:50 -07001732 // Intentionally unset the data channel type for RTP data channel with the
1733 // second condition. Otherwise the RTP data channels would be successfully
1734 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1735 // when building with chromium. We want to leave RTP data channels broken, so
1736 // people won't try to use them.
1737 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1738 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001739 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001740
zhihuangaf388472016-11-02 16:49:48 -07001741 session_options->bundle_enabled =
1742 session_options->bundle_enabled &&
1743 (session_options->has_audio() || session_options->has_video() ||
1744 session_options->has_data());
1745
zhihuang8f65cdf2016-05-06 18:40:30 -07001746 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001747 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001748 return true;
1749}
1750
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001751void PeerConnection::InitializeOptionsForAnswer(
1752 cricket::MediaSessionOptions* session_options) {
1753 session_options->recv_audio = false;
1754 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001755 session_options->enable_ice_renomination =
1756 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001757}
1758
htaa2a49d92016-03-04 02:51:39 -08001759void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001760 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001761 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1762 // ContentInfos.
1763 if (session_->remote_description()) {
1764 // Initialize the transport_options map.
1765 for (const cricket::ContentInfo& content :
1766 session_->remote_description()->description()->contents()) {
1767 session_options->transport_options[content.name] =
1768 cricket::TransportOptions();
1769 }
1770 }
deadbeeffac06552015-11-25 11:26:01 -08001771 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001772 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1773 // are not signaled in the SDP so does not go through that path and must be
1774 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001775 // Intentionally unset the data channel type for RTP data channel. Otherwise
1776 // the RTP data channels would be successfully negotiated by default and the
1777 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1778 // We want to leave RTP data channels broken, so people won't try to use them.
1779 if (session_->data_channel_type() != cricket::DCT_RTP) {
1780 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001781 }
zhihuangaf388472016-11-02 16:49:48 -07001782 session_options->bundle_enabled =
1783 session_options->bundle_enabled &&
1784 (session_options->has_audio() || session_options->has_video() ||
1785 session_options->has_data());
1786
jbauchcb560652016-08-04 05:20:32 -07001787 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001788}
1789
1790bool PeerConnection::GetOptionsForAnswer(
1791 const MediaConstraintsInterface* constraints,
1792 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001793 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001794 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1795 return false;
1796 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001797 session_options->rtcp_cname = rtcp_cname_;
1798
htaa2a49d92016-03-04 02:51:39 -08001799 FinishOptionsForAnswer(session_options);
1800 return true;
1801}
1802
1803bool PeerConnection::GetOptionsForAnswer(
1804 const RTCOfferAnswerOptions& options,
1805 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001806 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001807 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001808 return false;
1809 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001810 session_options->rtcp_cname = rtcp_cname_;
1811
htaa2a49d92016-03-04 02:51:39 -08001812 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001813 return true;
1814}
1815
deadbeeffaac4972015-11-12 15:33:07 -08001816void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1817 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001818 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1819 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001820}
1821
deadbeefab9b2d12015-10-14 11:33:11 -07001822void PeerConnection::UpdateRemoteStreamsList(
1823 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001824 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001825 cricket::MediaType media_type,
1826 StreamCollection* new_streams) {
1827 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1828
1829 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001830 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001831 auto track_it = current_tracks->begin();
1832 while (track_it != current_tracks->end()) {
1833 const TrackInfo& info = *track_it;
1834 const cricket::StreamParams* params =
1835 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001836 bool track_exists = params && params->id == info.track_id;
1837 // If this is a default track, and we still need it, don't remove it.
1838 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1839 track_exists) {
1840 ++track_it;
1841 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001842 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1843 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001844 }
1845 }
1846
1847 // Find new and active tracks.
1848 for (const cricket::StreamParams& params : streams) {
1849 // The sync_label is the MediaStream label and the |stream.id| is the
1850 // track id.
1851 const std::string& stream_label = params.sync_label;
1852 const std::string& track_id = params.id;
1853 uint32_t ssrc = params.first_ssrc();
1854
1855 rtc::scoped_refptr<MediaStreamInterface> stream =
1856 remote_streams_->find(stream_label);
1857 if (!stream) {
1858 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001859 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1860 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001861 remote_streams_->AddStream(stream);
1862 new_streams->AddStream(stream);
1863 }
1864
1865 const TrackInfo* track_info =
1866 FindTrackInfo(*current_tracks, stream_label, track_id);
1867 if (!track_info) {
1868 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1869 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1870 }
1871 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001872
1873 // Add default track if necessary.
1874 if (default_track_needed) {
1875 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1876 remote_streams_->find(kDefaultStreamLabel);
1877 if (!default_stream) {
1878 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001879 default_stream = MediaStreamProxy::Create(
1880 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001881 remote_streams_->AddStream(default_stream);
1882 new_streams->AddStream(default_stream);
1883 }
1884 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1885 ? kDefaultAudioTrackLabel
1886 : kDefaultVideoTrackLabel;
1887 const TrackInfo* default_track_info =
1888 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1889 if (!default_track_info) {
1890 current_tracks->push_back(
1891 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1892 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1893 }
1894 }
deadbeefab9b2d12015-10-14 11:33:11 -07001895}
1896
1897void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1898 const std::string& track_id,
1899 uint32_t ssrc,
1900 cricket::MediaType media_type) {
1901 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1902
1903 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001904 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001905 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001906 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001907 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001908 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001909 }
1910}
1911
1912void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1913 const std::string& track_id,
1914 cricket::MediaType media_type) {
1915 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1916
1917 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001918 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1919 // will be notified which will end the AudioRtpReceiver::track().
1920 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001921 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1922 stream->FindAudioTrack(track_id);
1923 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001924 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001925 }
1926 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001927 // Stopping or destroying a VideoRtpReceiver will end the
1928 // VideoRtpReceiver::track().
1929 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001930 rtc::scoped_refptr<VideoTrackInterface> video_track =
1931 stream->FindVideoTrack(track_id);
1932 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001933 // There's no guarantee the track is still available, e.g. the track may
1934 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001935 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001936 }
1937 } else {
nisseede5da42017-01-12 05:15:36 -08001938 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001939 }
1940}
1941
1942void PeerConnection::UpdateEndedRemoteMediaStreams() {
1943 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1944 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1945 MediaStreamInterface* stream = remote_streams_->at(i);
1946 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1947 streams_to_remove.push_back(stream);
1948 }
1949 }
1950
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001951 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001952 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001953 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001954 }
1955}
1956
deadbeefab9b2d12015-10-14 11:33:11 -07001957void PeerConnection::UpdateLocalTracks(
1958 const std::vector<cricket::StreamParams>& streams,
1959 cricket::MediaType media_type) {
1960 TrackInfos* current_tracks = GetLocalTracks(media_type);
1961
1962 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1963 // don't match the new StreamParam.
1964 TrackInfos::iterator track_it = current_tracks->begin();
1965 while (track_it != current_tracks->end()) {
1966 const TrackInfo& info = *track_it;
1967 const cricket::StreamParams* params =
1968 cricket::GetStreamBySsrc(streams, info.ssrc);
1969 if (!params || params->id != info.track_id ||
1970 params->sync_label != info.stream_label) {
1971 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1972 media_type);
1973 track_it = current_tracks->erase(track_it);
1974 } else {
1975 ++track_it;
1976 }
1977 }
1978
1979 // Find new and active tracks.
1980 for (const cricket::StreamParams& params : streams) {
1981 // The sync_label is the MediaStream label and the |stream.id| is the
1982 // track id.
1983 const std::string& stream_label = params.sync_label;
1984 const std::string& track_id = params.id;
1985 uint32_t ssrc = params.first_ssrc();
1986 const TrackInfo* track_info =
1987 FindTrackInfo(*current_tracks, stream_label, track_id);
1988 if (!track_info) {
1989 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1990 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1991 }
1992 }
1993}
1994
1995void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1996 const std::string& track_id,
1997 uint32_t ssrc,
1998 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001999 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002000 if (!sender) {
2001 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2002 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002003 return;
2004 }
2005
deadbeeffac06552015-11-25 11:26:01 -08002006 if (sender->media_type() != media_type) {
2007 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2008 << " description with an unexpected media type.";
2009 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002010 }
deadbeeffac06552015-11-25 11:26:01 -08002011
2012 sender->set_stream_id(stream_label);
2013 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002014}
2015
2016void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2017 const std::string& track_id,
2018 uint32_t ssrc,
2019 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002020 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002021 if (!sender) {
2022 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002023 // SessionDescriptions has been renegotiated.
2024 return;
2025 }
deadbeeffac06552015-11-25 11:26:01 -08002026
2027 // A sender has been removed from the SessionDescription but it's still
2028 // associated with the PeerConnection. This only occurs if the SDP doesn't
2029 // match with the calls to CreateSender, AddStream and RemoveStream.
2030 if (sender->media_type() != media_type) {
2031 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2032 << " description with an unexpected media type.";
2033 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002034 }
deadbeeffac06552015-11-25 11:26:01 -08002035
2036 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002037}
2038
2039void PeerConnection::UpdateLocalRtpDataChannels(
2040 const cricket::StreamParamsVec& streams) {
2041 std::vector<std::string> existing_channels;
2042
2043 // Find new and active data channels.
2044 for (const cricket::StreamParams& params : streams) {
2045 // |it->sync_label| is actually the data channel label. The reason is that
2046 // we use the same naming of data channels as we do for
2047 // MediaStreams and Tracks.
2048 // For MediaStreams, the sync_label is the MediaStream label and the
2049 // track label is the same as |streamid|.
2050 const std::string& channel_label = params.sync_label;
2051 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002052 if (data_channel_it == rtp_data_channels_.end()) {
2053 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002054 continue;
2055 }
2056 // Set the SSRC the data channel should use for sending.
2057 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2058 existing_channels.push_back(data_channel_it->first);
2059 }
2060
2061 UpdateClosingRtpDataChannels(existing_channels, true);
2062}
2063
2064void PeerConnection::UpdateRemoteRtpDataChannels(
2065 const cricket::StreamParamsVec& streams) {
2066 std::vector<std::string> existing_channels;
2067
2068 // Find new and active data channels.
2069 for (const cricket::StreamParams& params : streams) {
2070 // The data channel label is either the mslabel or the SSRC if the mslabel
2071 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2072 std::string label = params.sync_label.empty()
2073 ? rtc::ToString(params.first_ssrc())
2074 : params.sync_label;
2075 auto data_channel_it = rtp_data_channels_.find(label);
2076 if (data_channel_it == rtp_data_channels_.end()) {
2077 // This is a new data channel.
2078 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2079 } else {
2080 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2081 }
2082 existing_channels.push_back(label);
2083 }
2084
2085 UpdateClosingRtpDataChannels(existing_channels, false);
2086}
2087
2088void PeerConnection::UpdateClosingRtpDataChannels(
2089 const std::vector<std::string>& active_channels,
2090 bool is_local_update) {
2091 auto it = rtp_data_channels_.begin();
2092 while (it != rtp_data_channels_.end()) {
2093 DataChannel* data_channel = it->second;
2094 if (std::find(active_channels.begin(), active_channels.end(),
2095 data_channel->label()) != active_channels.end()) {
2096 ++it;
2097 continue;
2098 }
2099
2100 if (is_local_update) {
2101 data_channel->SetSendSsrc(0);
2102 } else {
2103 data_channel->RemotePeerRequestClose();
2104 }
2105
2106 if (data_channel->state() == DataChannel::kClosed) {
2107 rtp_data_channels_.erase(it);
2108 it = rtp_data_channels_.begin();
2109 } else {
2110 ++it;
2111 }
2112 }
2113}
2114
2115void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2116 uint32_t remote_ssrc) {
2117 rtc::scoped_refptr<DataChannel> channel(
2118 InternalCreateDataChannel(label, nullptr));
2119 if (!channel.get()) {
2120 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2121 << "CreateDataChannel failed.";
2122 return;
2123 }
2124 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002125 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2126 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002127 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002128}
2129
2130rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2131 const std::string& label,
2132 const InternalDataChannelInit* config) {
2133 if (IsClosed()) {
2134 return nullptr;
2135 }
2136 if (session_->data_channel_type() == cricket::DCT_NONE) {
2137 LOG(LS_ERROR)
2138 << "InternalCreateDataChannel: Data is not supported in this call.";
2139 return nullptr;
2140 }
2141 InternalDataChannelInit new_config =
2142 config ? (*config) : InternalDataChannelInit();
2143 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2144 if (new_config.id < 0) {
2145 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002146 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002147 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2148 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2149 return nullptr;
2150 }
2151 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2152 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2153 << "because the id is already in use or out of range.";
2154 return nullptr;
2155 }
2156 }
2157
2158 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2159 session_.get(), session_->data_channel_type(), label, new_config));
2160 if (!channel) {
2161 sid_allocator_.ReleaseSid(new_config.id);
2162 return nullptr;
2163 }
2164
2165 if (channel->data_channel_type() == cricket::DCT_RTP) {
2166 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2167 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2168 << " already exists.";
2169 return nullptr;
2170 }
2171 rtp_data_channels_[channel->label()] = channel;
2172 } else {
2173 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2174 sctp_data_channels_.push_back(channel);
2175 channel->SignalClosed.connect(this,
2176 &PeerConnection::OnSctpDataChannelClosed);
2177 }
2178
hbos82ebe022016-11-14 01:41:09 -08002179 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002180 return channel;
2181}
2182
2183bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002184#ifdef HAVE_QUIC
2185 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2186 (session_->quic_data_transport() &&
2187 session_->quic_data_transport()->HasDataChannels());
2188#else
deadbeefab9b2d12015-10-14 11:33:11 -07002189 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002190#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002191}
2192
2193void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2194 for (const auto& channel : sctp_data_channels_) {
2195 if (channel->id() < 0) {
2196 int sid;
2197 if (!sid_allocator_.AllocateSid(role, &sid)) {
2198 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2199 continue;
2200 }
2201 channel->SetSctpSid(sid);
2202 }
2203 }
2204}
2205
2206void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002207 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002208 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2209 ++it) {
2210 if (it->get() == channel) {
2211 if (channel->id() >= 0) {
2212 sid_allocator_.ReleaseSid(channel->id());
2213 }
deadbeefbd292462015-12-14 18:15:29 -08002214 // Since this method is triggered by a signal from the DataChannel,
2215 // we can't free it directly here; we need to free it asynchronously.
2216 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002217 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002218 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2219 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002220 return;
2221 }
2222 }
2223}
2224
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002225void PeerConnection::OnVoiceChannelCreated() {
2226 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2227 session_->voice_channel(), senders_, receivers_,
2228 cricket::MEDIA_TYPE_AUDIO);
2229}
2230
deadbeefab9b2d12015-10-14 11:33:11 -07002231void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002232 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2233 cricket::VoiceChannel>(
2234 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2235}
2236
2237void PeerConnection::OnVideoChannelCreated() {
2238 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2239 session_->video_channel(), senders_, receivers_,
2240 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002241}
2242
2243void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002244 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2245 cricket::VideoChannel>(
2246 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002247}
2248
2249void PeerConnection::OnDataChannelCreated() {
2250 for (const auto& channel : sctp_data_channels_) {
2251 channel->OnTransportChannelCreated();
2252 }
2253}
2254
2255void PeerConnection::OnDataChannelDestroyed() {
2256 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2257 // DataChannel may callback to us and try to modify the list.
2258 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2259 temp_rtp_dcs.swap(rtp_data_channels_);
2260 for (const auto& kv : temp_rtp_dcs) {
2261 kv.second->OnTransportChannelDestroyed();
2262 }
2263
2264 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2265 temp_sctp_dcs.swap(sctp_data_channels_);
2266 for (const auto& channel : temp_sctp_dcs) {
2267 channel->OnTransportChannelDestroyed();
2268 }
2269}
2270
2271void PeerConnection::OnDataChannelOpenMessage(
2272 const std::string& label,
2273 const InternalDataChannelInit& config) {
2274 rtc::scoped_refptr<DataChannel> channel(
2275 InternalCreateDataChannel(label, &config));
2276 if (!channel.get()) {
2277 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2278 return;
2279 }
2280
deadbeefa601f5c2016-06-06 14:27:39 -07002281 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2282 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002283 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002284}
2285
deadbeefa601f5c2016-06-06 14:27:39 -07002286RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2287 auto it = std::find_if(
2288 senders_.begin(), senders_.end(),
2289 [id](const rtc::scoped_refptr<
2290 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2291 return sender->id() == id;
2292 });
2293 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002294}
2295
deadbeefa601f5c2016-06-06 14:27:39 -07002296std::vector<
2297 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002298PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2299 return std::find_if(
2300 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002301 [track](const rtc::scoped_refptr<
2302 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002303 return sender->track() == track;
2304 });
2305}
2306
deadbeefa601f5c2016-06-06 14:27:39 -07002307std::vector<rtc::scoped_refptr<
2308 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002309PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002310 return std::find_if(
2311 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002312 [track_id](const rtc::scoped_refptr<
2313 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002314 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002315 });
2316}
2317
deadbeefab9b2d12015-10-14 11:33:11 -07002318PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2319 cricket::MediaType media_type) {
2320 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2321 media_type == cricket::MEDIA_TYPE_VIDEO);
2322 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2323 : &remote_video_tracks_;
2324}
2325
2326PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2327 cricket::MediaType media_type) {
2328 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2329 media_type == cricket::MEDIA_TYPE_VIDEO);
2330 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2331 : &local_video_tracks_;
2332}
2333
2334const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2335 const PeerConnection::TrackInfos& infos,
2336 const std::string& stream_label,
2337 const std::string track_id) const {
2338 for (const TrackInfo& track_info : infos) {
2339 if (track_info.stream_label == stream_label &&
2340 track_info.track_id == track_id) {
2341 return &track_info;
2342 }
2343 }
2344 return nullptr;
2345}
2346
2347DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2348 for (const auto& channel : sctp_data_channels_) {
2349 if (channel->id() == sid) {
2350 return channel;
2351 }
2352 }
2353 return nullptr;
2354}
2355
deadbeef91dd5672016-05-18 16:55:30 -07002356bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002357 const RTCConfiguration& configuration) {
2358 cricket::ServerAddresses stun_servers;
2359 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002360 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2361 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002362 return false;
2363 }
2364
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002365 port_allocator_->Initialize();
2366
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002367 // To handle both internal and externally created port allocator, we will
2368 // enable BUNDLE here.
2369 int portallocator_flags = port_allocator_->flags();
2370 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002371 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2372 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002373 // If the disable-IPv6 flag was specified, we'll not override it
2374 // by experiment.
2375 if (configuration.disable_ipv6) {
2376 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002377 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2378 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002379 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2380 }
2381
zhihuangb09b3f92017-03-07 14:40:51 -08002382 if (configuration.disable_ipv6_on_wifi) {
2383 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2384 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2385 }
2386
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002387 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2388 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2389 LOG(LS_INFO) << "TCP candidates are disabled.";
2390 }
2391
honghaiz60347052016-05-31 18:29:12 -07002392 if (configuration.candidate_network_policy ==
2393 kCandidateNetworkPolicyLowCost) {
2394 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2395 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2396 }
2397
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002398 port_allocator_->set_flags(portallocator_flags);
2399 // No step delay is used while allocating ports.
2400 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2401 port_allocator_->set_candidate_filter(
2402 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2403
2404 // Call this last since it may create pooled allocator sessions using the
2405 // properties set above.
2406 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002407 configuration.ice_candidate_pool_size,
2408 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002409 return true;
2410}
2411
deadbeef91dd5672016-05-18 16:55:30 -07002412bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002413 const cricket::ServerAddresses& stun_servers,
2414 const std::vector<cricket::RelayServerConfig>& turn_servers,
2415 IceTransportsType type,
2416 int candidate_pool_size,
2417 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002418 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002419 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002420 // Call this last since it may create pooled allocator sessions using the
2421 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002422 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002423 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002424}
2425
ivoc14d5dbe2016-07-04 07:06:55 -07002426bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2427 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002428 if (!event_log_) {
2429 return false;
2430 }
skvlad11a9cbf2016-10-07 11:53:05 -07002431 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002432}
2433
2434void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002435 if (event_log_) {
2436 event_log_->StopLogging();
2437 }
ivoc14d5dbe2016-07-04 07:06:55 -07002438}
nisseeaabdf62017-05-05 02:23:02 -07002439
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440} // namespace webrtc