blob: 1a5fd6c5a9da0d5d289a3e532d7b33e104ac9db9 [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()) {
deadbeefeb459812015-12-15 19:24:43 -0800577 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700578 }
579 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800580 OnVideoTrackAdded(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");
deadbeefab9b2d12015-10-14 11:33:11 -0700590 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800591 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700592 }
593 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800594 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700595 }
596
597 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800598 stream_observers_.erase(
599 std::remove_if(
600 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700601 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800602 return observer->stream()->label().compare(local_stream->label()) ==
603 0;
604 }),
605 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700606
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 if (IsClosed()) {
608 return;
609 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 observer_->OnRenegotiationNeeded();
611}
612
deadbeefe1f9d832016-01-14 15:35:42 -0800613rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
614 MediaStreamTrackInterface* track,
615 std::vector<MediaStreamInterface*> streams) {
616 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
617 if (IsClosed()) {
618 return nullptr;
619 }
620 if (streams.size() >= 2) {
621 LOG(LS_ERROR)
622 << "Adding a track with two streams is not currently supported.";
623 return nullptr;
624 }
625 // TODO(deadbeef): Support adding a track to two different senders.
626 if (FindSenderForTrack(track) != senders_.end()) {
627 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
628 return nullptr;
629 }
630
631 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700632 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800633 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700634 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800635 signaling_thread(),
636 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700637 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800638 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700639 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800640 }
641 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700642 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800643 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700644 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800645 }
646 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700647 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800648 signaling_thread(),
649 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700650 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800651 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700652 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800653 }
654 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700655 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800656 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700657 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800658 }
659 } else {
660 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
661 return rtc::scoped_refptr<RtpSenderInterface>();
662 }
663
664 senders_.push_back(new_sender);
665 observer_->OnRenegotiationNeeded();
666 return new_sender;
667}
668
669bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
670 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
671 if (IsClosed()) {
672 return false;
673 }
674
675 auto it = std::find(senders_.begin(), senders_.end(), sender);
676 if (it == senders_.end()) {
677 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
678 return false;
679 }
deadbeefa601f5c2016-06-06 14:27:39 -0700680 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800681 senders_.erase(it);
682
683 observer_->OnRenegotiationNeeded();
684 return true;
685}
686
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000687rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100689 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700690 if (IsClosed()) {
691 return nullptr;
692 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693 if (!track) {
694 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800695 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696 }
deadbeef20cb0c12017-02-01 20:27:00 -0800697 auto it = FindSenderForTrack(track);
698 if (it == senders_.end()) {
699 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
700 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701 }
702
deadbeef20cb0c12017-02-01 20:27:00 -0800703 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704}
705
deadbeeffac06552015-11-25 11:26:01 -0800706rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800707 const std::string& kind,
708 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100709 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700710 if (IsClosed()) {
711 return nullptr;
712 }
deadbeefa601f5c2016-06-06 14:27:39 -0700713 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800714 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700715 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700716 signaling_thread(),
717 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800718 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700719 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700720 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800721 } else {
722 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800723 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800724 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800725 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700726 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800727 }
deadbeeffac06552015-11-25 11:26:01 -0800728 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800729 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800730}
731
deadbeef70ab1a12015-09-28 16:53:55 -0700732std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
733 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700734 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
735 for (const auto& sender : senders_) {
736 ret.push_back(sender.get());
737 }
738 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700739}
740
741std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
742PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700743 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
744 for (const auto& receiver : receivers_) {
745 ret.push_back(receiver.get());
746 }
747 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700748}
749
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000751 MediaStreamTrackInterface* track,
752 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100753 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700754 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800755 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756 LOG(LS_ERROR) << "GetStats - observer is NULL.";
757 return false;
758 }
759
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000760 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700761 // The StatsCollector is used to tell if a track is valid because it may
762 // remember tracks that the PeerConnection previously removed.
763 if (track && !stats_->IsValidTrack(track->id())) {
764 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
765 << track->id();
766 return false;
767 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700768 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000769 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770 return true;
771}
772
hbos74e1a4f2016-09-15 23:33:01 -0700773void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
774 RTC_DCHECK(stats_collector_);
775 stats_collector_->GetStatsReport(callback);
776}
777
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
779 return signaling_state_;
780}
781
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000782PeerConnectionInterface::IceConnectionState
783PeerConnection::ice_connection_state() {
784 return ice_connection_state_;
785}
786
787PeerConnectionInterface::IceGatheringState
788PeerConnection::ice_gathering_state() {
789 return ice_gathering_state_;
790}
791
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000792rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793PeerConnection::CreateDataChannel(
794 const std::string& label,
795 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100796 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700797#ifdef HAVE_QUIC
798 if (session_->data_channel_type() == cricket::DCT_QUIC) {
799 // TODO(zhihuang): Handle case when config is NULL.
800 if (!config) {
801 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
802 return nullptr;
803 }
804 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
805 if (!config->reliable || config->ordered) {
806 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
807 "ordered delivery.";
808 return nullptr;
809 }
810 return session_->quic_data_transport()->CreateDataChannel(label, config);
811 }
812#endif // HAVE_QUIC
813
deadbeefab9b2d12015-10-14 11:33:11 -0700814 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000815
kwibergd1fe2812016-04-27 06:47:29 -0700816 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000817 if (config) {
818 internal_config.reset(new InternalDataChannelInit(*config));
819 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000820 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700821 InternalCreateDataChannel(label, internal_config.get()));
822 if (!channel.get()) {
823 return nullptr;
824 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000826 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
827 // the first SCTP DataChannel.
828 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
829 observer_->OnRenegotiationNeeded();
830 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000831
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 return DataChannelProxy::Create(signaling_thread(), channel.get());
833}
834
835void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
836 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100837 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800838 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
840 return;
841 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000842 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000843
844 bool value;
845 size_t mandatory_constraints = 0;
846
847 if (FindConstraint(constraints,
848 MediaConstraintsInterface::kOfferToReceiveAudio,
849 &value,
850 &mandatory_constraints)) {
851 options.offer_to_receive_audio =
852 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
853 }
854
855 if (FindConstraint(constraints,
856 MediaConstraintsInterface::kOfferToReceiveVideo,
857 &value,
858 &mandatory_constraints)) {
859 options.offer_to_receive_video =
860 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
861 }
862
863 if (FindConstraint(constraints,
864 MediaConstraintsInterface::kVoiceActivityDetection,
865 &value,
866 &mandatory_constraints)) {
867 options.voice_activity_detection = value;
868 }
869
870 if (FindConstraint(constraints,
871 MediaConstraintsInterface::kIceRestart,
872 &value,
873 &mandatory_constraints)) {
874 options.ice_restart = value;
875 }
876
877 if (FindConstraint(constraints,
878 MediaConstraintsInterface::kUseRtpMux,
879 &value,
880 &mandatory_constraints)) {
881 options.use_rtp_mux = value;
882 }
883
884 CreateOffer(observer, options);
885}
886
887void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
888 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100889 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800890 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000891 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
892 return;
893 }
deadbeefab9b2d12015-10-14 11:33:11 -0700894
895 cricket::MediaSessionOptions session_options;
896 if (!GetOptionsForOffer(options, &session_options)) {
897 std::string error = "CreateOffer called with invalid options.";
898 LOG(LS_ERROR) << error;
899 PostCreateSessionDescriptionFailure(observer, error);
900 return;
901 }
902
903 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904}
905
906void PeerConnection::CreateAnswer(
907 CreateSessionDescriptionObserver* observer,
908 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100909 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800910 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000911 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
912 return;
913 }
deadbeefab9b2d12015-10-14 11:33:11 -0700914
915 cricket::MediaSessionOptions session_options;
916 if (!GetOptionsForAnswer(constraints, &session_options)) {
917 std::string error = "CreateAnswer called with invalid constraints.";
918 LOG(LS_ERROR) << error;
919 PostCreateSessionDescriptionFailure(observer, error);
920 return;
921 }
922
htaa2a49d92016-03-04 02:51:39 -0800923 session_->CreateAnswer(observer, session_options);
924}
925
926void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
927 const RTCOfferAnswerOptions& options) {
928 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800929 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800930 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
931 return;
932 }
933
934 cricket::MediaSessionOptions session_options;
935 if (!GetOptionsForAnswer(options, &session_options)) {
936 std::string error = "CreateAnswer called with invalid options.";
937 LOG(LS_ERROR) << error;
938 PostCreateSessionDescriptionFailure(observer, error);
939 return;
940 }
941
942 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943}
944
945void PeerConnection::SetLocalDescription(
946 SetSessionDescriptionObserver* observer,
947 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100948 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700949 if (IsClosed()) {
950 return;
951 }
nisse7ce109a2017-01-31 00:57:56 -0800952 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
954 return;
955 }
956 if (!desc) {
957 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
958 return;
959 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 // Update stats here so that we have the most recent stats for tracks and
961 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000962 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 std::string error;
964 if (!session_->SetLocalDescription(desc, &error)) {
965 PostSetSessionDescriptionFailure(observer, error);
966 return;
967 }
deadbeefab9b2d12015-10-14 11:33:11 -0700968
969 // If setting the description decided our SSL role, allocate any necessary
970 // SCTP sids.
971 rtc::SSLRole role;
972 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800973 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700974 AllocateSctpSids(role);
975 }
976
977 // Update state and SSRC of local MediaStreams and DataChannels based on the
978 // local session description.
979 const cricket::ContentInfo* audio_content =
980 GetFirstAudioContent(desc->description());
981 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800982 if (audio_content->rejected) {
983 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
984 } else {
985 const cricket::AudioContentDescription* audio_desc =
986 static_cast<const cricket::AudioContentDescription*>(
987 audio_content->description);
988 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
989 }
deadbeefab9b2d12015-10-14 11:33:11 -0700990 }
991
992 const cricket::ContentInfo* video_content =
993 GetFirstVideoContent(desc->description());
994 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800995 if (video_content->rejected) {
996 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
997 } else {
998 const cricket::VideoContentDescription* video_desc =
999 static_cast<const cricket::VideoContentDescription*>(
1000 video_content->description);
1001 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1002 }
deadbeefab9b2d12015-10-14 11:33:11 -07001003 }
1004
1005 const cricket::ContentInfo* data_content =
1006 GetFirstDataContent(desc->description());
1007 if (data_content) {
1008 const cricket::DataContentDescription* data_desc =
1009 static_cast<const cricket::DataContentDescription*>(
1010 data_content->description);
1011 if (rtc::starts_with(data_desc->protocol().data(),
1012 cricket::kMediaProtocolRtpPrefix)) {
1013 UpdateLocalRtpDataChannels(data_desc->streams());
1014 }
1015 }
1016
1017 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001018 signaling_thread()->Post(RTC_FROM_HERE, this,
1019 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001020
deadbeef42a42632017-03-10 15:18:00 -08001021 // According to JSEP, after setLocalDescription, changing the candidate pool
1022 // size is not allowed, and changing the set of ICE servers will not result
1023 // in new candidates being gathered.
1024 port_allocator_->FreezeCandidatePool();
1025
deadbeefcbecd352015-09-23 11:50:27 -07001026 // MaybeStartGathering needs to be called after posting
1027 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1028 // before signaling that SetLocalDescription completed.
1029 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001030
1031 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1032 // TODO(deadbeef): We already had to hop to the network thread for
1033 // MaybeStartGathering...
1034 network_thread()->Invoke<void>(
1035 RTC_FROM_HERE,
1036 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1037 port_allocator_.get()));
1038 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039}
1040
1041void PeerConnection::SetRemoteDescription(
1042 SetSessionDescriptionObserver* observer,
1043 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001044 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001045 if (IsClosed()) {
1046 return;
1047 }
nisse7ce109a2017-01-31 00:57:56 -08001048 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1050 return;
1051 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 if (!desc) {
1053 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1054 return;
1055 }
1056 // Update stats here so that we have the most recent stats for tracks and
1057 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001058 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059 std::string error;
1060 if (!session_->SetRemoteDescription(desc, &error)) {
1061 PostSetSessionDescriptionFailure(observer, error);
1062 return;
1063 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064
deadbeefab9b2d12015-10-14 11:33:11 -07001065 // If setting the description decided our SSL role, allocate any necessary
1066 // SCTP sids.
1067 rtc::SSLRole role;
1068 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001069 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001070 AllocateSctpSids(role);
1071 }
1072
1073 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001074 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1075 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1076 const cricket::AudioContentDescription* audio_desc =
1077 GetFirstAudioContentDescription(remote_desc);
1078 const cricket::VideoContentDescription* video_desc =
1079 GetFirstVideoContentDescription(remote_desc);
1080 const cricket::DataContentDescription* data_desc =
1081 GetFirstDataContentDescription(remote_desc);
1082
1083 // Check if the descriptions include streams, just in case the peer supports
1084 // MSID, but doesn't indicate so with "a=msid-semantic".
1085 if (remote_desc->msid_supported() ||
1086 (audio_desc && !audio_desc->streams().empty()) ||
1087 (video_desc && !video_desc->streams().empty())) {
1088 remote_peer_supports_msid_ = true;
1089 }
deadbeefab9b2d12015-10-14 11:33:11 -07001090
1091 // We wait to signal new streams until we finish processing the description,
1092 // since only at that point will new streams have all their tracks.
1093 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1094
1095 // Find all audio rtp streams and create corresponding remote AudioTracks
1096 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001097 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001098 if (audio_content->rejected) {
1099 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1100 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001101 bool default_audio_track_needed =
1102 !remote_peer_supports_msid_ &&
1103 MediaContentDirectionHasSend(audio_desc->direction());
1104 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1105 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001106 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001107 }
deadbeefab9b2d12015-10-14 11:33:11 -07001108 }
1109
1110 // Find all video rtp streams and create corresponding remote VideoTracks
1111 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001112 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001113 if (video_content->rejected) {
1114 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1115 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001116 bool default_video_track_needed =
1117 !remote_peer_supports_msid_ &&
1118 MediaContentDirectionHasSend(video_desc->direction());
1119 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1120 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001121 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001122 }
deadbeefab9b2d12015-10-14 11:33:11 -07001123 }
1124
1125 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001126 if (data_desc) {
1127 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001128 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001129 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001130 }
1131 }
1132
1133 // Iterate new_streams and notify the observer about new MediaStreams.
1134 for (size_t i = 0; i < new_streams->count(); ++i) {
1135 MediaStreamInterface* new_stream = new_streams->at(i);
1136 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001137 observer_->OnAddStream(
1138 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001139 }
1140
deadbeefbda7e0b2015-12-08 17:13:40 -08001141 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001142
1143 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001144 signaling_thread()->Post(RTC_FROM_HERE, this,
1145 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001146
1147 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1148 // TODO(deadbeef): We already had to hop to the network thread for
1149 // MaybeStartGathering...
1150 network_thread()->Invoke<void>(
1151 RTC_FROM_HERE,
1152 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1153 port_allocator_.get()));
1154 }
deadbeeffc648b62015-10-13 16:42:33 -07001155}
1156
deadbeef46c73892016-11-16 19:42:04 -08001157PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1158 return configuration_;
1159}
1160
deadbeef293e9262017-01-11 12:28:30 -08001161bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1162 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001163 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001164
1165 if (session_->local_description() &&
1166 configuration.ice_candidate_pool_size !=
1167 configuration_.ice_candidate_pool_size) {
1168 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1169 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001170 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001171 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001172
deadbeef293e9262017-01-11 12:28:30 -08001173 // The simplest (and most future-compatible) way to tell if the config was
1174 // modified in an invalid way is to copy each property we do support
1175 // modifying, then use operator==. There are far more properties we don't
1176 // support modifying than those we do, and more could be added.
1177 RTCConfiguration modified_config = configuration_;
1178 modified_config.servers = configuration.servers;
1179 modified_config.type = configuration.type;
1180 modified_config.ice_candidate_pool_size =
1181 configuration.ice_candidate_pool_size;
1182 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001183 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001184 if (configuration != modified_config) {
1185 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1186 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1187 }
1188
Steve Anton038834f2017-07-14 15:59:59 -07001189 // Validate the modified configuration.
1190 RTCError validate_error = ValidateConfiguration(modified_config);
1191 if (!validate_error.ok()) {
1192 return SafeSetError(std::move(validate_error), error);
1193 }
1194
deadbeef293e9262017-01-11 12:28:30 -08001195 // Note that this isn't possible through chromium, since it's an unsigned
1196 // short in WebIDL.
1197 if (configuration.ice_candidate_pool_size < 0 ||
1198 configuration.ice_candidate_pool_size > UINT16_MAX) {
1199 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1200 }
1201
1202 // Parse ICE servers before hopping to network thread.
1203 cricket::ServerAddresses stun_servers;
1204 std::vector<cricket::RelayServerConfig> turn_servers;
1205 RTCErrorType parse_error =
1206 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1207 if (parse_error != RTCErrorType::NONE) {
1208 return SafeSetError(parse_error, error);
1209 }
1210
1211 // In theory this shouldn't fail.
1212 if (!network_thread()->Invoke<bool>(
1213 RTC_FROM_HERE,
1214 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1215 stun_servers, turn_servers, modified_config.type,
1216 modified_config.ice_candidate_pool_size,
1217 modified_config.prune_turn_ports))) {
1218 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1219 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1220 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001221
deadbeefd1a38b52016-12-10 13:15:33 -08001222 // As described in JSEP, calling setConfiguration with new ICE servers or
1223 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1224 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001225 if (modified_config.servers != configuration_.servers ||
1226 modified_config.type != configuration_.type ||
1227 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001228 session_->SetNeedsIceRestartFlag();
1229 }
skvladd1f5fda2017-02-03 16:54:05 -08001230
1231 if (modified_config.ice_check_min_interval !=
1232 configuration_.ice_check_min_interval) {
1233 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1234 }
1235
deadbeef293e9262017-01-11 12:28:30 -08001236 configuration_ = modified_config;
1237 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001238}
1239
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001240bool PeerConnection::AddIceCandidate(
1241 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001242 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001243 if (IsClosed()) {
1244 return false;
1245 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 return session_->ProcessIceMessage(ice_candidate);
1247}
1248
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001249bool PeerConnection::RemoveIceCandidates(
1250 const std::vector<cricket::Candidate>& candidates) {
1251 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1252 return session_->RemoveRemoteIceCandidates(candidates);
1253}
1254
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001255void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001256 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001257 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001258
1259 if (session_) {
1260 session_->set_metrics_observer(uma_observer_);
1261 }
1262
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001263 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001264 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001265 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001266 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001267 uma_observer_->IncrementEnumCounter(
1268 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1269 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001270 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001271 uma_observer_->IncrementEnumCounter(
1272 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1273 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001274 }
1275 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001276}
1277
zstein4b979802017-06-02 14:37:37 -07001278RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
1279 rtc::Thread* worker_thread = factory_->worker_thread();
1280 if (!worker_thread->IsCurrent()) {
1281 return worker_thread->Invoke<RTCError>(
1282 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1283 }
1284
1285 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1286 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1287 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1288 if (has_min && *bitrate.min_bitrate_bps < 0) {
1289 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1290 "min_bitrate_bps <= 0");
1291 }
1292 if (has_current) {
1293 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1294 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1295 "current_bitrate_bps < min_bitrate_bps");
1296 } else if (*bitrate.current_bitrate_bps < 0) {
1297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1298 "curent_bitrate_bps < 0");
1299 }
1300 }
1301 if (has_max) {
1302 if (has_current &&
1303 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1305 "max_bitrate_bps < current_bitrate_bps");
1306 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1308 "max_bitrate_bps < min_bitrate_bps");
1309 } else if (*bitrate.max_bitrate_bps < 0) {
1310 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1311 "max_bitrate_bps < 0");
1312 }
1313 }
1314
1315 Call::Config::BitrateConfigMask mask;
1316 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1317 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1318 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1319
1320 RTC_DCHECK(call_.get());
1321 call_->SetBitrateConfigMask(mask);
1322
1323 return RTCError::OK();
1324}
1325
ivoc14d5dbe2016-07-04 07:06:55 -07001326bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1327 int64_t max_size_bytes) {
1328 return factory_->worker_thread()->Invoke<bool>(
1329 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1330 max_size_bytes));
1331}
1332
1333void PeerConnection::StopRtcEventLog() {
1334 factory_->worker_thread()->Invoke<void>(
1335 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1336}
1337
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338const SessionDescriptionInterface* PeerConnection::local_description() const {
1339 return session_->local_description();
1340}
1341
1342const SessionDescriptionInterface* PeerConnection::remote_description() const {
1343 return session_->remote_description();
1344}
1345
deadbeeffe4a8a42016-12-20 17:56:17 -08001346const SessionDescriptionInterface* PeerConnection::current_local_description()
1347 const {
1348 return session_->current_local_description();
1349}
1350
1351const SessionDescriptionInterface* PeerConnection::current_remote_description()
1352 const {
1353 return session_->current_remote_description();
1354}
1355
1356const SessionDescriptionInterface* PeerConnection::pending_local_description()
1357 const {
1358 return session_->pending_local_description();
1359}
1360
1361const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1362 const {
1363 return session_->pending_remote_description();
1364}
1365
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001367 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 // Update stats here so that we have the most recent stats for tracks and
1369 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001370 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371
deadbeefd59daf82015-10-14 15:02:44 -07001372 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001373 network_thread()->Invoke<void>(
1374 RTC_FROM_HERE,
1375 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1376 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001377
1378 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
1379 [this] { call_.reset(); });
terelius33860252017-05-12 23:37:18 -07001380
1381 // The event log must outlive call (and any other object that uses it).
1382 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383}
1384
deadbeefd59daf82015-10-14 15:02:44 -07001385void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1386 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001388 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001390 break;
deadbeefd59daf82015-10-14 15:02:44 -07001391 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1393 break;
deadbeefd59daf82015-10-14 15:02:44 -07001394 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1396 break;
deadbeefd59daf82015-10-14 15:02:44 -07001397 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1399 break;
deadbeefd59daf82015-10-14 15:02:44 -07001400 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1402 break;
deadbeefd59daf82015-10-14 15:02:44 -07001403 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 ChangeSignalingState(PeerConnectionInterface::kStable);
1405 break;
deadbeefd59daf82015-10-14 15:02:44 -07001406 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 ChangeSignalingState(PeerConnectionInterface::kClosed);
1408 break;
1409 default:
1410 break;
1411 }
1412}
1413
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001414void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1417 SetSessionDescriptionMsg* param =
1418 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1419 param->observer->OnSuccess();
1420 delete param;
1421 break;
1422 }
1423 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1424 SetSessionDescriptionMsg* param =
1425 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1426 param->observer->OnFailure(param->error);
1427 delete param;
1428 break;
1429 }
deadbeefab9b2d12015-10-14 11:33:11 -07001430 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1431 CreateSessionDescriptionMsg* param =
1432 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1433 param->observer->OnFailure(param->error);
1434 delete param;
1435 break;
1436 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437 case MSG_GETSTATS: {
1438 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001439 StatsReports reports;
1440 stats_->GetStats(param->track, &reports);
1441 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442 delete param;
1443 break;
1444 }
deadbeefbd292462015-12-14 18:15:29 -08001445 case MSG_FREE_DATACHANNELS: {
1446 sctp_data_channels_to_free_.clear();
1447 break;
1448 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001450 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451 break;
1452 }
1453}
1454
deadbeefab9b2d12015-10-14 11:33:11 -07001455void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001456 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001457 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001458 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1459 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001460 signaling_thread(),
1461 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1462 stream->AddTrack(
1463 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001464 receivers_.push_back(receiver);
1465 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1466 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1467 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468}
1469
deadbeefab9b2d12015-10-14 11:33:11 -07001470void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001471 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001472 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001473 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1474 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001475 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001476 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1477 session_->video_channel()));
1478 stream->AddTrack(
1479 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001480 receivers_.push_back(receiver);
1481 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1482 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1483 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001484}
1485
deadbeef70ab1a12015-09-28 16:53:55 -07001486// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1487// description.
perkjd61bf802016-03-24 03:16:19 -07001488void PeerConnection::DestroyReceiver(const std::string& track_id) {
1489 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001490 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001491 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001492 << " doesn't exist.";
1493 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001494 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001495 receivers_.erase(it);
1496 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497}
1498
zstein6dfd53a2017-03-06 13:49:03 -08001499void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001500 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001501 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001502 // After transitioning to "closed", ignore any additional states from
1503 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001504 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001505 return;
1506 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001508 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509}
1510
1511void PeerConnection::OnIceGatheringChange(
1512 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001513 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514 if (IsClosed()) {
1515 return;
1516 }
1517 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001518 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519}
1520
jbauch81bf7b02017-03-25 08:31:12 -07001521void PeerConnection::OnIceCandidate(
1522 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001523 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001524 if (IsClosed()) {
1525 return;
1526 }
jbauch81bf7b02017-03-25 08:31:12 -07001527 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528}
1529
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001530void PeerConnection::OnIceCandidatesRemoved(
1531 const std::vector<cricket::Candidate>& candidates) {
1532 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001533 if (IsClosed()) {
1534 return;
1535 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001536 observer_->OnIceCandidatesRemoved(candidates);
1537}
1538
Peter Thatcher54360512015-07-08 11:08:35 -07001539void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001540 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001541 if (IsClosed()) {
1542 return;
1543 }
Peter Thatcher54360512015-07-08 11:08:35 -07001544 observer_->OnIceConnectionReceivingChange(receiving);
1545}
1546
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547void PeerConnection::ChangeSignalingState(
1548 PeerConnectionInterface::SignalingState signaling_state) {
1549 signaling_state_ = signaling_state;
1550 if (signaling_state == kClosed) {
1551 ice_connection_state_ = kIceConnectionClosed;
1552 observer_->OnIceConnectionChange(ice_connection_state_);
1553 if (ice_gathering_state_ != kIceGatheringComplete) {
1554 ice_gathering_state_ = kIceGatheringComplete;
1555 observer_->OnIceGatheringChange(ice_gathering_state_);
1556 }
1557 }
1558 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559}
1560
deadbeefeb459812015-12-15 19:24:43 -08001561void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1562 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001563 if (IsClosed()) {
1564 return;
1565 }
deadbeefeb459812015-12-15 19:24:43 -08001566 auto sender = FindSenderForTrack(track);
1567 if (sender != senders_.end()) {
1568 // We already have a sender for this track, so just change the stream_id
1569 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001570 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001571 return;
1572 }
1573
1574 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001575 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1576 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001577 signaling_thread(),
1578 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1579 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001580 senders_.push_back(new_sender);
1581 // If the sender has already been configured in SDP, we call SetSsrc,
1582 // which will connect the sender to the underlying transport. This can
1583 // occur if a local session description that contains the ID of the sender
1584 // is set before AddStream is called. It can also occur if the local
1585 // session description is not changed and RemoveStream is called, and
1586 // later AddStream is called again with the same stream.
1587 const TrackInfo* track_info =
1588 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1589 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001590 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001591 }
1592}
1593
1594// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1595// indefinitely, when we have unified plan SDP.
1596void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1597 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001598 if (IsClosed()) {
1599 return;
1600 }
deadbeefeb459812015-12-15 19:24:43 -08001601 auto sender = FindSenderForTrack(track);
1602 if (sender == senders_.end()) {
1603 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1604 << " doesn't exist.";
1605 return;
1606 }
deadbeefa601f5c2016-06-06 14:27:39 -07001607 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001608 senders_.erase(sender);
1609}
1610
1611void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1612 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001613 if (IsClosed()) {
1614 return;
1615 }
deadbeefeb459812015-12-15 19:24:43 -08001616 auto sender = FindSenderForTrack(track);
1617 if (sender != senders_.end()) {
1618 // We already have a sender for this track, so just change the stream_id
1619 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001620 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001621 return;
1622 }
1623
1624 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001625 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1626 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001627 signaling_thread(), new VideoRtpSender(track, stream->label(),
1628 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001629 senders_.push_back(new_sender);
1630 const TrackInfo* track_info =
1631 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1632 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001633 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001634 }
1635}
1636
1637void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1638 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001639 if (IsClosed()) {
1640 return;
1641 }
deadbeefeb459812015-12-15 19:24:43 -08001642 auto sender = FindSenderForTrack(track);
1643 if (sender == senders_.end()) {
1644 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1645 << " doesn't exist.";
1646 return;
1647 }
deadbeefa601f5c2016-06-06 14:27:39 -07001648 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001649 senders_.erase(sender);
1650}
1651
deadbeefab9b2d12015-10-14 11:33:11 -07001652void PeerConnection::PostSetSessionDescriptionFailure(
1653 SetSessionDescriptionObserver* observer,
1654 const std::string& error) {
1655 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1656 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001657 signaling_thread()->Post(RTC_FROM_HERE, this,
1658 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001659}
1660
1661void PeerConnection::PostCreateSessionDescriptionFailure(
1662 CreateSessionDescriptionObserver* observer,
1663 const std::string& error) {
1664 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1665 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001666 signaling_thread()->Post(RTC_FROM_HERE, this,
1667 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001668}
1669
1670bool PeerConnection::GetOptionsForOffer(
1671 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1672 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001673 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1674 // ContentInfos.
1675 if (session_->local_description()) {
1676 for (const cricket::ContentInfo& content :
1677 session_->local_description()->description()->contents()) {
1678 session_options->transport_options[content.name] =
1679 cricket::TransportOptions();
1680 }
1681 }
deadbeef46c73892016-11-16 19:42:04 -08001682 session_options->enable_ice_renomination =
1683 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001684
htaaac2dea2016-03-10 13:35:55 -08001685 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001686 return false;
1687 }
1688
deadbeeffac06552015-11-25 11:26:01 -08001689 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001690 // Offer to receive audio/video if the constraint is not set and there are
1691 // send streams, or we're currently receiving.
1692 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1693 session_options->recv_audio =
1694 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1695 !remote_audio_tracks_.empty();
1696 }
1697 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1698 session_options->recv_video =
1699 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1700 !remote_video_tracks_.empty();
1701 }
deadbeefc80741f2015-10-22 13:14:45 -07001702
zhihuang9763d562016-08-05 11:14:50 -07001703 // Intentionally unset the data channel type for RTP data channel with the
1704 // second condition. Otherwise the RTP data channels would be successfully
1705 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1706 // when building with chromium. We want to leave RTP data channels broken, so
1707 // people won't try to use them.
1708 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1709 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001710 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001711
zhihuangaf388472016-11-02 16:49:48 -07001712 session_options->bundle_enabled =
1713 session_options->bundle_enabled &&
1714 (session_options->has_audio() || session_options->has_video() ||
1715 session_options->has_data());
1716
zhihuang8f65cdf2016-05-06 18:40:30 -07001717 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001718 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001719 return true;
1720}
1721
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001722void PeerConnection::InitializeOptionsForAnswer(
1723 cricket::MediaSessionOptions* session_options) {
1724 session_options->recv_audio = false;
1725 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001726 session_options->enable_ice_renomination =
1727 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001728}
1729
htaa2a49d92016-03-04 02:51:39 -08001730void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001731 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001732 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1733 // ContentInfos.
1734 if (session_->remote_description()) {
1735 // Initialize the transport_options map.
1736 for (const cricket::ContentInfo& content :
1737 session_->remote_description()->description()->contents()) {
1738 session_options->transport_options[content.name] =
1739 cricket::TransportOptions();
1740 }
1741 }
deadbeeffac06552015-11-25 11:26:01 -08001742 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001743 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1744 // are not signaled in the SDP so does not go through that path and must be
1745 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001746 // Intentionally unset the data channel type for RTP data channel. Otherwise
1747 // the RTP data channels would be successfully negotiated by default and the
1748 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1749 // We want to leave RTP data channels broken, so people won't try to use them.
1750 if (session_->data_channel_type() != cricket::DCT_RTP) {
1751 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001752 }
zhihuangaf388472016-11-02 16:49:48 -07001753 session_options->bundle_enabled =
1754 session_options->bundle_enabled &&
1755 (session_options->has_audio() || session_options->has_video() ||
1756 session_options->has_data());
1757
jbauchcb560652016-08-04 05:20:32 -07001758 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001759}
1760
1761bool PeerConnection::GetOptionsForAnswer(
1762 const MediaConstraintsInterface* constraints,
1763 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001764 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001765 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1766 return false;
1767 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001768 session_options->rtcp_cname = rtcp_cname_;
1769
htaa2a49d92016-03-04 02:51:39 -08001770 FinishOptionsForAnswer(session_options);
1771 return true;
1772}
1773
1774bool PeerConnection::GetOptionsForAnswer(
1775 const RTCOfferAnswerOptions& options,
1776 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001777 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001778 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001779 return false;
1780 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001781 session_options->rtcp_cname = rtcp_cname_;
1782
htaa2a49d92016-03-04 02:51:39 -08001783 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001784 return true;
1785}
1786
deadbeeffaac4972015-11-12 15:33:07 -08001787void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1788 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001789 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1790 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001791}
1792
deadbeefab9b2d12015-10-14 11:33:11 -07001793void PeerConnection::UpdateRemoteStreamsList(
1794 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001795 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001796 cricket::MediaType media_type,
1797 StreamCollection* new_streams) {
1798 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1799
1800 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001801 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001802 auto track_it = current_tracks->begin();
1803 while (track_it != current_tracks->end()) {
1804 const TrackInfo& info = *track_it;
1805 const cricket::StreamParams* params =
1806 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001807 bool track_exists = params && params->id == info.track_id;
1808 // If this is a default track, and we still need it, don't remove it.
1809 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1810 track_exists) {
1811 ++track_it;
1812 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001813 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1814 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001815 }
1816 }
1817
1818 // Find new and active tracks.
1819 for (const cricket::StreamParams& params : streams) {
1820 // The sync_label is the MediaStream label and the |stream.id| is the
1821 // track id.
1822 const std::string& stream_label = params.sync_label;
1823 const std::string& track_id = params.id;
1824 uint32_t ssrc = params.first_ssrc();
1825
1826 rtc::scoped_refptr<MediaStreamInterface> stream =
1827 remote_streams_->find(stream_label);
1828 if (!stream) {
1829 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001830 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1831 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001832 remote_streams_->AddStream(stream);
1833 new_streams->AddStream(stream);
1834 }
1835
1836 const TrackInfo* track_info =
1837 FindTrackInfo(*current_tracks, stream_label, track_id);
1838 if (!track_info) {
1839 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1840 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1841 }
1842 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001843
1844 // Add default track if necessary.
1845 if (default_track_needed) {
1846 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1847 remote_streams_->find(kDefaultStreamLabel);
1848 if (!default_stream) {
1849 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001850 default_stream = MediaStreamProxy::Create(
1851 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001852 remote_streams_->AddStream(default_stream);
1853 new_streams->AddStream(default_stream);
1854 }
1855 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1856 ? kDefaultAudioTrackLabel
1857 : kDefaultVideoTrackLabel;
1858 const TrackInfo* default_track_info =
1859 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1860 if (!default_track_info) {
1861 current_tracks->push_back(
1862 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1863 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1864 }
1865 }
deadbeefab9b2d12015-10-14 11:33:11 -07001866}
1867
1868void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1869 const std::string& track_id,
1870 uint32_t ssrc,
1871 cricket::MediaType media_type) {
1872 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1873
1874 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001875 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001876 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001877 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001878 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001879 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001880 }
1881}
1882
1883void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1884 const std::string& track_id,
1885 cricket::MediaType media_type) {
1886 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1887
1888 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001889 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1890 // will be notified which will end the AudioRtpReceiver::track().
1891 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001892 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1893 stream->FindAudioTrack(track_id);
1894 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001895 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001896 }
1897 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001898 // Stopping or destroying a VideoRtpReceiver will end the
1899 // VideoRtpReceiver::track().
1900 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001901 rtc::scoped_refptr<VideoTrackInterface> video_track =
1902 stream->FindVideoTrack(track_id);
1903 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001904 // There's no guarantee the track is still available, e.g. the track may
1905 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001906 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001907 }
1908 } else {
nisseede5da42017-01-12 05:15:36 -08001909 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001910 }
1911}
1912
1913void PeerConnection::UpdateEndedRemoteMediaStreams() {
1914 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1915 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1916 MediaStreamInterface* stream = remote_streams_->at(i);
1917 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1918 streams_to_remove.push_back(stream);
1919 }
1920 }
1921
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001922 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001923 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001924 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001925 }
1926}
1927
deadbeefab9b2d12015-10-14 11:33:11 -07001928void PeerConnection::UpdateLocalTracks(
1929 const std::vector<cricket::StreamParams>& streams,
1930 cricket::MediaType media_type) {
1931 TrackInfos* current_tracks = GetLocalTracks(media_type);
1932
1933 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1934 // don't match the new StreamParam.
1935 TrackInfos::iterator track_it = current_tracks->begin();
1936 while (track_it != current_tracks->end()) {
1937 const TrackInfo& info = *track_it;
1938 const cricket::StreamParams* params =
1939 cricket::GetStreamBySsrc(streams, info.ssrc);
1940 if (!params || params->id != info.track_id ||
1941 params->sync_label != info.stream_label) {
1942 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1943 media_type);
1944 track_it = current_tracks->erase(track_it);
1945 } else {
1946 ++track_it;
1947 }
1948 }
1949
1950 // Find new and active tracks.
1951 for (const cricket::StreamParams& params : streams) {
1952 // The sync_label is the MediaStream label and the |stream.id| is the
1953 // track id.
1954 const std::string& stream_label = params.sync_label;
1955 const std::string& track_id = params.id;
1956 uint32_t ssrc = params.first_ssrc();
1957 const TrackInfo* track_info =
1958 FindTrackInfo(*current_tracks, stream_label, track_id);
1959 if (!track_info) {
1960 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1961 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1962 }
1963 }
1964}
1965
1966void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1967 const std::string& track_id,
1968 uint32_t ssrc,
1969 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001970 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001971 if (!sender) {
1972 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1973 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001974 return;
1975 }
1976
deadbeeffac06552015-11-25 11:26:01 -08001977 if (sender->media_type() != media_type) {
1978 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1979 << " description with an unexpected media type.";
1980 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001981 }
deadbeeffac06552015-11-25 11:26:01 -08001982
1983 sender->set_stream_id(stream_label);
1984 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001985}
1986
1987void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1988 const std::string& track_id,
1989 uint32_t ssrc,
1990 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001991 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001992 if (!sender) {
1993 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001994 // SessionDescriptions has been renegotiated.
1995 return;
1996 }
deadbeeffac06552015-11-25 11:26:01 -08001997
1998 // A sender has been removed from the SessionDescription but it's still
1999 // associated with the PeerConnection. This only occurs if the SDP doesn't
2000 // match with the calls to CreateSender, AddStream and RemoveStream.
2001 if (sender->media_type() != media_type) {
2002 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2003 << " description with an unexpected media type.";
2004 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002005 }
deadbeeffac06552015-11-25 11:26:01 -08002006
2007 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002008}
2009
2010void PeerConnection::UpdateLocalRtpDataChannels(
2011 const cricket::StreamParamsVec& streams) {
2012 std::vector<std::string> existing_channels;
2013
2014 // Find new and active data channels.
2015 for (const cricket::StreamParams& params : streams) {
2016 // |it->sync_label| is actually the data channel label. The reason is that
2017 // we use the same naming of data channels as we do for
2018 // MediaStreams and Tracks.
2019 // For MediaStreams, the sync_label is the MediaStream label and the
2020 // track label is the same as |streamid|.
2021 const std::string& channel_label = params.sync_label;
2022 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002023 if (data_channel_it == rtp_data_channels_.end()) {
2024 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002025 continue;
2026 }
2027 // Set the SSRC the data channel should use for sending.
2028 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2029 existing_channels.push_back(data_channel_it->first);
2030 }
2031
2032 UpdateClosingRtpDataChannels(existing_channels, true);
2033}
2034
2035void PeerConnection::UpdateRemoteRtpDataChannels(
2036 const cricket::StreamParamsVec& streams) {
2037 std::vector<std::string> existing_channels;
2038
2039 // Find new and active data channels.
2040 for (const cricket::StreamParams& params : streams) {
2041 // The data channel label is either the mslabel or the SSRC if the mslabel
2042 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2043 std::string label = params.sync_label.empty()
2044 ? rtc::ToString(params.first_ssrc())
2045 : params.sync_label;
2046 auto data_channel_it = rtp_data_channels_.find(label);
2047 if (data_channel_it == rtp_data_channels_.end()) {
2048 // This is a new data channel.
2049 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2050 } else {
2051 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2052 }
2053 existing_channels.push_back(label);
2054 }
2055
2056 UpdateClosingRtpDataChannels(existing_channels, false);
2057}
2058
2059void PeerConnection::UpdateClosingRtpDataChannels(
2060 const std::vector<std::string>& active_channels,
2061 bool is_local_update) {
2062 auto it = rtp_data_channels_.begin();
2063 while (it != rtp_data_channels_.end()) {
2064 DataChannel* data_channel = it->second;
2065 if (std::find(active_channels.begin(), active_channels.end(),
2066 data_channel->label()) != active_channels.end()) {
2067 ++it;
2068 continue;
2069 }
2070
2071 if (is_local_update) {
2072 data_channel->SetSendSsrc(0);
2073 } else {
2074 data_channel->RemotePeerRequestClose();
2075 }
2076
2077 if (data_channel->state() == DataChannel::kClosed) {
2078 rtp_data_channels_.erase(it);
2079 it = rtp_data_channels_.begin();
2080 } else {
2081 ++it;
2082 }
2083 }
2084}
2085
2086void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2087 uint32_t remote_ssrc) {
2088 rtc::scoped_refptr<DataChannel> channel(
2089 InternalCreateDataChannel(label, nullptr));
2090 if (!channel.get()) {
2091 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2092 << "CreateDataChannel failed.";
2093 return;
2094 }
2095 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002096 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2097 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002098 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002099}
2100
2101rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2102 const std::string& label,
2103 const InternalDataChannelInit* config) {
2104 if (IsClosed()) {
2105 return nullptr;
2106 }
2107 if (session_->data_channel_type() == cricket::DCT_NONE) {
2108 LOG(LS_ERROR)
2109 << "InternalCreateDataChannel: Data is not supported in this call.";
2110 return nullptr;
2111 }
2112 InternalDataChannelInit new_config =
2113 config ? (*config) : InternalDataChannelInit();
2114 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2115 if (new_config.id < 0) {
2116 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002117 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002118 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2119 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2120 return nullptr;
2121 }
2122 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2123 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2124 << "because the id is already in use or out of range.";
2125 return nullptr;
2126 }
2127 }
2128
2129 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2130 session_.get(), session_->data_channel_type(), label, new_config));
2131 if (!channel) {
2132 sid_allocator_.ReleaseSid(new_config.id);
2133 return nullptr;
2134 }
2135
2136 if (channel->data_channel_type() == cricket::DCT_RTP) {
2137 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2138 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2139 << " already exists.";
2140 return nullptr;
2141 }
2142 rtp_data_channels_[channel->label()] = channel;
2143 } else {
2144 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2145 sctp_data_channels_.push_back(channel);
2146 channel->SignalClosed.connect(this,
2147 &PeerConnection::OnSctpDataChannelClosed);
2148 }
2149
hbos82ebe022016-11-14 01:41:09 -08002150 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002151 return channel;
2152}
2153
2154bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002155#ifdef HAVE_QUIC
2156 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2157 (session_->quic_data_transport() &&
2158 session_->quic_data_transport()->HasDataChannels());
2159#else
deadbeefab9b2d12015-10-14 11:33:11 -07002160 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002161#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002162}
2163
2164void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2165 for (const auto& channel : sctp_data_channels_) {
2166 if (channel->id() < 0) {
2167 int sid;
2168 if (!sid_allocator_.AllocateSid(role, &sid)) {
2169 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2170 continue;
2171 }
2172 channel->SetSctpSid(sid);
2173 }
2174 }
2175}
2176
2177void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002178 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002179 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2180 ++it) {
2181 if (it->get() == channel) {
2182 if (channel->id() >= 0) {
2183 sid_allocator_.ReleaseSid(channel->id());
2184 }
deadbeefbd292462015-12-14 18:15:29 -08002185 // Since this method is triggered by a signal from the DataChannel,
2186 // we can't free it directly here; we need to free it asynchronously.
2187 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002188 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002189 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2190 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002191 return;
2192 }
2193 }
2194}
2195
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002196void PeerConnection::OnVoiceChannelCreated() {
2197 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2198 session_->voice_channel(), senders_, receivers_,
2199 cricket::MEDIA_TYPE_AUDIO);
2200}
2201
deadbeefab9b2d12015-10-14 11:33:11 -07002202void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002203 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2204 cricket::VoiceChannel>(
2205 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2206}
2207
2208void PeerConnection::OnVideoChannelCreated() {
2209 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2210 session_->video_channel(), senders_, receivers_,
2211 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002212}
2213
2214void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002215 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2216 cricket::VideoChannel>(
2217 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002218}
2219
2220void PeerConnection::OnDataChannelCreated() {
2221 for (const auto& channel : sctp_data_channels_) {
2222 channel->OnTransportChannelCreated();
2223 }
2224}
2225
2226void PeerConnection::OnDataChannelDestroyed() {
2227 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2228 // DataChannel may callback to us and try to modify the list.
2229 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2230 temp_rtp_dcs.swap(rtp_data_channels_);
2231 for (const auto& kv : temp_rtp_dcs) {
2232 kv.second->OnTransportChannelDestroyed();
2233 }
2234
2235 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2236 temp_sctp_dcs.swap(sctp_data_channels_);
2237 for (const auto& channel : temp_sctp_dcs) {
2238 channel->OnTransportChannelDestroyed();
2239 }
2240}
2241
2242void PeerConnection::OnDataChannelOpenMessage(
2243 const std::string& label,
2244 const InternalDataChannelInit& config) {
2245 rtc::scoped_refptr<DataChannel> channel(
2246 InternalCreateDataChannel(label, &config));
2247 if (!channel.get()) {
2248 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2249 return;
2250 }
2251
deadbeefa601f5c2016-06-06 14:27:39 -07002252 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2253 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002254 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002255}
2256
deadbeefa601f5c2016-06-06 14:27:39 -07002257RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2258 auto it = std::find_if(
2259 senders_.begin(), senders_.end(),
2260 [id](const rtc::scoped_refptr<
2261 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2262 return sender->id() == id;
2263 });
2264 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002265}
2266
deadbeefa601f5c2016-06-06 14:27:39 -07002267std::vector<
2268 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002269PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2270 return std::find_if(
2271 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002272 [track](const rtc::scoped_refptr<
2273 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002274 return sender->track() == track;
2275 });
2276}
2277
deadbeefa601f5c2016-06-06 14:27:39 -07002278std::vector<rtc::scoped_refptr<
2279 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002280PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002281 return std::find_if(
2282 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002283 [track_id](const rtc::scoped_refptr<
2284 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002285 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002286 });
2287}
2288
deadbeefab9b2d12015-10-14 11:33:11 -07002289PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2290 cricket::MediaType media_type) {
2291 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2292 media_type == cricket::MEDIA_TYPE_VIDEO);
2293 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2294 : &remote_video_tracks_;
2295}
2296
2297PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2298 cricket::MediaType media_type) {
2299 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2300 media_type == cricket::MEDIA_TYPE_VIDEO);
2301 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2302 : &local_video_tracks_;
2303}
2304
2305const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2306 const PeerConnection::TrackInfos& infos,
2307 const std::string& stream_label,
2308 const std::string track_id) const {
2309 for (const TrackInfo& track_info : infos) {
2310 if (track_info.stream_label == stream_label &&
2311 track_info.track_id == track_id) {
2312 return &track_info;
2313 }
2314 }
2315 return nullptr;
2316}
2317
2318DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2319 for (const auto& channel : sctp_data_channels_) {
2320 if (channel->id() == sid) {
2321 return channel;
2322 }
2323 }
2324 return nullptr;
2325}
2326
deadbeef91dd5672016-05-18 16:55:30 -07002327bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002328 const RTCConfiguration& configuration) {
2329 cricket::ServerAddresses stun_servers;
2330 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002331 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2332 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002333 return false;
2334 }
2335
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002336 port_allocator_->Initialize();
2337
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002338 // To handle both internal and externally created port allocator, we will
2339 // enable BUNDLE here.
2340 int portallocator_flags = port_allocator_->flags();
2341 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002342 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2343 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002344 // If the disable-IPv6 flag was specified, we'll not override it
2345 // by experiment.
2346 if (configuration.disable_ipv6) {
2347 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002348 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2349 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002350 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2351 }
2352
zhihuangb09b3f92017-03-07 14:40:51 -08002353 if (configuration.disable_ipv6_on_wifi) {
2354 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2355 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2356 }
2357
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002358 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2359 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2360 LOG(LS_INFO) << "TCP candidates are disabled.";
2361 }
2362
honghaiz60347052016-05-31 18:29:12 -07002363 if (configuration.candidate_network_policy ==
2364 kCandidateNetworkPolicyLowCost) {
2365 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2366 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2367 }
2368
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002369 port_allocator_->set_flags(portallocator_flags);
2370 // No step delay is used while allocating ports.
2371 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2372 port_allocator_->set_candidate_filter(
2373 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2374
2375 // Call this last since it may create pooled allocator sessions using the
2376 // properties set above.
2377 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002378 configuration.ice_candidate_pool_size,
2379 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002380 return true;
2381}
2382
deadbeef91dd5672016-05-18 16:55:30 -07002383bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002384 const cricket::ServerAddresses& stun_servers,
2385 const std::vector<cricket::RelayServerConfig>& turn_servers,
2386 IceTransportsType type,
2387 int candidate_pool_size,
2388 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002389 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002390 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002391 // Call this last since it may create pooled allocator sessions using the
2392 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002393 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002394 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002395}
2396
ivoc14d5dbe2016-07-04 07:06:55 -07002397bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2398 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002399 if (!event_log_) {
2400 return false;
2401 }
skvlad11a9cbf2016-10-07 11:53:05 -07002402 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002403}
2404
2405void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002406 if (event_log_) {
2407 event_log_->StopLogging();
2408 }
ivoc14d5dbe2016-07-04 07:06:55 -07002409}
nisseeaabdf62017-05-05 02:23:02 -07002410
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411} // namespace webrtc