blob: 42664b04efd23f7067102aaa55610100386f45e3 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
ossu7bb87ee2017-01-23 04:56:25 -080011#include "webrtc/pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
kwiberg0eb15ed2015-12-17 03:04:15 -080014#include <utility>
15#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000016
Henrik Kjellander15583c12016-02-10 10:53:12 +010017#include "webrtc/api/jsepicecandidate.h"
18#include "webrtc/api/jsepsessiondescription.h"
19#include "webrtc/api/mediaconstraintsinterface.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010020#include "webrtc/api/mediastreamproxy.h"
21#include "webrtc/api/mediastreamtrackproxy.h"
ossuf515ab82016-12-07 04:52:58 -080022#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070023#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
deadbeef953c2ce2017-01-09 14:53:41 -080024#include "webrtc/media/sctp/sctptransport.h"
ossu7bb87ee2017-01-23 04:56:25 -080025#include "webrtc/pc/audiotrack.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010026#include "webrtc/pc/channelmanager.h"
ossu7bb87ee2017-01-23 04:56:25 -080027#include "webrtc/pc/dtmfsender.h"
28#include "webrtc/pc/mediastream.h"
29#include "webrtc/pc/mediastreamobserver.h"
30#include "webrtc/pc/remoteaudiosource.h"
31#include "webrtc/pc/rtpreceiver.h"
32#include "webrtc/pc/rtpsender.h"
33#include "webrtc/pc/streamcollection.h"
34#include "webrtc/pc/videocapturertracksource.h"
35#include "webrtc/pc/videotrack.h"
Edward Lemurc20978e2017-07-06 19:44:34 +020036#include "webrtc/rtc_base/bind.h"
37#include "webrtc/rtc_base/checks.h"
38#include "webrtc/rtc_base/logging.h"
39#include "webrtc/rtc_base/stringencode.h"
40#include "webrtc/rtc_base/stringutils.h"
41#include "webrtc/rtc_base/trace_event.h"
ossu7bb87ee2017-01-23 04:56:25 -080042#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
45namespace {
46
deadbeefab9b2d12015-10-14 11:33:11 -070047using webrtc::DataChannel;
48using webrtc::MediaConstraintsInterface;
49using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080051using webrtc::RTCError;
52using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070053using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080054using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070055using webrtc::RtpSenderProxy;
56using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070057using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
deadbeefab9b2d12015-10-14 11:33:11 -070059static const char kDefaultStreamLabel[] = "default";
60static const char kDefaultAudioTrackLabel[] = "defaulta0";
61static const char kDefaultVideoTrackLabel[] = "defaultv0";
62
zhihuang8f65cdf2016-05-06 18:40:30 -070063// The length of RTCP CNAMEs.
64static const int kRtcpCnameLength = 16;
65
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000067 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070069 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080071 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072};
73
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000074struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075 explicit SetSessionDescriptionMsg(
76 webrtc::SetSessionDescriptionObserver* observer)
77 : observer(observer) {
78 }
79
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000080 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081 std::string error;
82};
83
deadbeefab9b2d12015-10-14 11:33:11 -070084struct CreateSessionDescriptionMsg : public rtc::MessageData {
85 explicit CreateSessionDescriptionMsg(
86 webrtc::CreateSessionDescriptionObserver* observer)
87 : observer(observer) {}
88
89 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
90 std::string error;
91};
92
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000093struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000094 GetStatsMsg(webrtc::StatsObserver* observer,
95 webrtc::MediaStreamTrackInterface* track)
96 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000098 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000099 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100};
101
deadbeefab9b2d12015-10-14 11:33:11 -0700102// Check if we can send |new_stream| on a PeerConnection.
103bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
104 webrtc::MediaStreamInterface* new_stream) {
105 if (!new_stream || !current_streams) {
106 return false;
107 }
108 if (current_streams->find(new_stream->label()) != nullptr) {
109 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
110 << " is already added.";
111 return false;
112 }
113 return true;
114}
115
116bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
117 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
118}
119
deadbeef5e97fb52015-10-15 12:49:08 -0700120// If the direction is "recvonly" or "inactive", treat the description
121// as containing no streams.
122// See: https://code.google.com/p/webrtc/issues/detail?id=5054
123std::vector<cricket::StreamParams> GetActiveStreams(
124 const cricket::MediaContentDescription* desc) {
125 return MediaContentDirectionHasSend(desc->direction())
126 ? desc->streams()
127 : std::vector<cricket::StreamParams>();
128}
129
deadbeefab9b2d12015-10-14 11:33:11 -0700130bool IsValidOfferToReceiveMedia(int value) {
131 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
132 return (value >= Options::kUndefined) &&
133 (value <= Options::kMaxOfferToReceiveMedia);
134}
135
136// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800137void AddSendStreams(
138 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700139 const std::vector<rtc::scoped_refptr<
140 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800141 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
142 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700143 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800144 for (const auto& sender : senders) {
145 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700146 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700147 }
148
149 // Check for data channels.
150 for (const auto& kv : rtp_data_channels) {
151 const DataChannel* channel = kv.second;
152 if (channel->state() == DataChannel::kConnecting ||
153 channel->state() == DataChannel::kOpen) {
154 // |streamid| and |sync_label| are both set to the DataChannel label
155 // here so they can be signaled the same way as MediaStreams and Tracks.
156 // For MediaStreams, the sync_label is the MediaStream label and the
157 // track label is the same as |streamid|.
158 const std::string& streamid = channel->label();
159 const std::string& sync_label = channel->label();
160 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
161 sync_label);
162 }
163 }
164}
165
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700166uint32_t ConvertIceTransportTypeToCandidateFilter(
167 PeerConnectionInterface::IceTransportsType type) {
168 switch (type) {
169 case PeerConnectionInterface::kNone:
170 return cricket::CF_NONE;
171 case PeerConnectionInterface::kRelay:
172 return cricket::CF_RELAY;
173 case PeerConnectionInterface::kNoHost:
174 return (cricket::CF_ALL & ~cricket::CF_HOST);
175 case PeerConnectionInterface::kAll:
176 return cricket::CF_ALL;
177 default:
nissec80e7412017-01-11 05:56:46 -0800178 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700179 }
180 return cricket::CF_NONE;
181}
182
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700183// Helper method to set a voice/video channel on all applicable senders
184// and receivers when one is created/destroyed by WebRtcSession.
185//
186// Used by On(Voice|Video)Channel(Created|Destroyed)
187template <class SENDER,
188 class RECEIVER,
189 class CHANNEL,
190 class SENDERS,
191 class RECEIVERS>
192void SetChannelOnSendersAndReceivers(CHANNEL* channel,
193 SENDERS& senders,
194 RECEIVERS& receivers,
195 cricket::MediaType media_type) {
196 for (auto& sender : senders) {
197 if (sender->media_type() == media_type) {
198 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
199 }
200 }
201 for (auto& receiver : receivers) {
202 if (receiver->media_type() == media_type) {
203 if (!channel) {
204 receiver->internal()->Stop();
205 }
206 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
207 }
208 }
209}
210
deadbeef293e9262017-01-11 12:28:30 -0800211// Helper to set an error and return from a method.
212bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
213 if (error) {
214 error->set_type(type);
215 }
216 return type == webrtc::RTCErrorType::NONE;
217}
218
deadbeef0a6c4ca2015-10-06 11:38:28 -0700219} // namespace
220
221namespace webrtc {
222
deadbeef293e9262017-01-11 12:28:30 -0800223bool PeerConnectionInterface::RTCConfiguration::operator==(
224 const PeerConnectionInterface::RTCConfiguration& o) const {
225 // This static_assert prevents us from accidentally breaking operator==.
Steve Antonaa41f0c2017-07-11 14:38:29 -0700226 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800227 struct stuff_being_tested_for_equality {
deadbeef293e9262017-01-11 12:28:30 -0800228 IceServers servers;
Steve Antonaa41f0c2017-07-11 14:38:29 -0700229 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800230 BundlePolicy bundle_policy;
231 RtcpMuxPolicy rtcp_mux_policy;
Steve Antonaa41f0c2017-07-11 14:38:29 -0700232 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
233 int ice_candidate_pool_size;
234 bool disable_ipv6;
235 bool disable_ipv6_on_wifi;
236 bool enable_rtp_data_channel;
237 rtc::Optional<int> screencast_min_bitrate;
238 rtc::Optional<bool> combined_audio_video_bwe;
239 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800240 TcpCandidatePolicy tcp_candidate_policy;
241 CandidateNetworkPolicy candidate_network_policy;
242 int audio_jitter_buffer_max_packets;
243 bool audio_jitter_buffer_fast_accelerate;
244 int ice_connection_receiving_timeout;
245 int ice_backup_candidate_pair_ping_interval;
246 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800247 bool prioritize_most_likely_ice_candidate_pairs;
248 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800249 bool enable_quic;
deadbeef293e9262017-01-11 12:28:30 -0800250 bool prune_turn_ports;
251 bool presume_writable_when_fully_relayed;
252 bool enable_ice_renomination;
253 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800254 rtc::Optional<int> ice_check_min_interval;
Steve Antonaa41f0c2017-07-11 14:38:29 -0700255 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800256 };
257 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
258 "Did you add something to RTCConfiguration and forget to "
259 "update operator==?");
260 return type == o.type && servers == o.servers &&
261 bundle_policy == o.bundle_policy &&
262 rtcp_mux_policy == o.rtcp_mux_policy &&
263 tcp_candidate_policy == o.tcp_candidate_policy &&
264 candidate_network_policy == o.candidate_network_policy &&
265 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
266 audio_jitter_buffer_fast_accelerate ==
267 o.audio_jitter_buffer_fast_accelerate &&
268 ice_connection_receiving_timeout ==
269 o.ice_connection_receiving_timeout &&
270 ice_backup_candidate_pair_ping_interval ==
271 o.ice_backup_candidate_pair_ping_interval &&
272 continual_gathering_policy == o.continual_gathering_policy &&
273 certificates == o.certificates &&
274 prioritize_most_likely_ice_candidate_pairs ==
275 o.prioritize_most_likely_ice_candidate_pairs &&
276 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800277 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeef293e9262017-01-11 12:28:30 -0800278 enable_rtp_data_channel == o.enable_rtp_data_channel &&
279 enable_quic == o.enable_quic &&
280 screencast_min_bitrate == o.screencast_min_bitrate &&
281 combined_audio_video_bwe == o.combined_audio_video_bwe &&
282 enable_dtls_srtp == o.enable_dtls_srtp &&
283 ice_candidate_pool_size == o.ice_candidate_pool_size &&
284 prune_turn_ports == o.prune_turn_ports &&
285 presume_writable_when_fully_relayed ==
286 o.presume_writable_when_fully_relayed &&
287 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800288 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Antonaa41f0c2017-07-11 14:38:29 -0700289 ice_check_min_interval == o.ice_check_min_interval &&
290 ice_regather_interval_range == o.ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800291}
292
293bool PeerConnectionInterface::RTCConfiguration::operator!=(
294 const PeerConnectionInterface::RTCConfiguration& o) const {
295 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800296}
297
zhihuang8f65cdf2016-05-06 18:40:30 -0700298// Generate a RTCP CNAME when a PeerConnection is created.
299std::string GenerateRtcpCname() {
300 std::string cname;
301 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
302 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800303 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700304 }
305 return cname;
306}
307
htaa2a49d92016-03-04 02:51:39 -0800308bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700309 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800310 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700311 cricket::MediaSessionOptions* session_options) {
312 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
313 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
314 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
315 return false;
316 }
317
htaaac2dea2016-03-10 13:35:55 -0800318 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700319 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700320 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800321 } else {
322 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700323 }
htaaac2dea2016-03-10 13:35:55 -0800324 // For offers, we only offer video if we have it or it's forced by options.
325 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700326 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700327 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800328 } else if (is_offer) {
329 session_options->recv_video = false;
330 } else {
331 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700332 }
333
334 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700335 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800336 for (auto& kv : session_options->transport_options) {
337 kv.second.ice_restart = rtc_options.ice_restart;
338 }
deadbeefab9b2d12015-10-14 11:33:11 -0700339
340 return true;
341}
342
343bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
344 cricket::MediaSessionOptions* session_options) {
345 bool value = false;
346 size_t mandatory_constraints_satisfied = 0;
347
348 // kOfferToReceiveAudio defaults to true according to spec.
349 if (!FindConstraint(constraints,
350 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
351 &mandatory_constraints_satisfied) ||
352 value) {
353 session_options->recv_audio = true;
354 }
355
356 // kOfferToReceiveVideo defaults to false according to spec. But
357 // if it is an answer and video is offered, we should still accept video
358 // per default.
359 value = false;
360 if (!FindConstraint(constraints,
361 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
362 &mandatory_constraints_satisfied) ||
363 value) {
364 session_options->recv_video = true;
365 }
366
367 if (FindConstraint(constraints,
368 MediaConstraintsInterface::kVoiceActivityDetection, &value,
369 &mandatory_constraints_satisfied)) {
370 session_options->vad_enabled = value;
371 }
372
373 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
374 &mandatory_constraints_satisfied)) {
375 session_options->bundle_enabled = value;
376 } else {
377 // kUseRtpMux defaults to true according to spec.
378 session_options->bundle_enabled = true;
379 }
deadbeefab9b2d12015-10-14 11:33:11 -0700380
deadbeef0ed85b22016-02-23 17:24:52 -0800381 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700382 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
383 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700384 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800385 ice_restart = true;
386 }
387 for (auto& kv : session_options->transport_options) {
388 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700389 }
390
391 if (!constraints) {
392 return true;
393 }
394 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
395}
396
zhihuang38ede132017-06-15 12:52:32 -0700397PeerConnection::PeerConnection(PeerConnectionFactory* factory,
398 std::unique_ptr<RtcEventLog> event_log,
399 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400 : factory_(factory),
401 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000402 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700403 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000405 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700406 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700407 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700408 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700409 remote_streams_(StreamCollection::Create()),
410 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000411
412PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100413 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700414 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700415 // Need to detach RTP senders/receivers from WebRtcSession,
416 // since it's about to be destroyed.
417 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700418 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700419 }
420 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700421 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700422 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700423 // Destroy stats_ because it depends on session_.
424 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800425 if (stats_collector_) {
426 stats_collector_->WaitForPendingRequest();
427 stats_collector_ = nullptr;
428 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700429 // Now destroy session_ before destroying other members,
430 // because its destruction fires signals (such as VoiceChannelDestroyed)
431 // which will trigger some final actions in PeerConnection...
432 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700433 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700434 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700435 [this] { port_allocator_.reset(); });
436 // call_ must be destroyed on the worker thread.
437 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
438 [this] { call_.reset(); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000439}
440
441bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000442 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700443 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200444 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800445 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100446 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800447 if (!allocator) {
448 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
449 << "This shouldn't happen if using PeerConnectionFactory.";
450 return false;
451 }
deadbeef653b8e02015-11-11 12:55:10 -0800452 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800453 // TODO(deadbeef): Why do we do this?
454 LOG(LS_ERROR) << "PeerConnection initialized without a "
455 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800456 return false;
457 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000458 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800459 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800460
deadbeef91dd5672016-05-18 16:55:30 -0700461 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700462 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700463 if (!network_thread()->Invoke<bool>(
464 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
465 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000466 return false;
467 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000468
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000469
zhihuang29ff8442016-07-27 11:07:25 -0700470 session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700471 call_.get(), factory_->channel_manager(), configuration.media_config,
472 event_log_.get(),
473 factory_->network_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700474 factory_->worker_thread(), factory_->signaling_thread(),
475 port_allocator_.get(),
476 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700477 factory_->CreateTransportController(
478 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800479 configuration.redetermine_role_on_ice_restart)),
480#ifdef HAVE_SCTP
481 std::unique_ptr<cricket::SctpTransportInternalFactory>(
482 new cricket::SctpTransportFactory(factory_->network_thread()))
483#else
484 nullptr
485#endif
486 ));
zhihuang29ff8442016-07-27 11:07:25 -0700487
deadbeefab9b2d12015-10-14 11:33:11 -0700488 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700489 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000490
491 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200492 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800493 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000494 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700495 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000496
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497 // Register PeerConnection as receiver of local ice candidates.
498 // All the callbacks will be posted to the application from PeerConnection.
499 session_->RegisterIceObserver(this);
500 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700501 session_->SignalVoiceChannelCreated.connect(
502 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700503 session_->SignalVoiceChannelDestroyed.connect(
504 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700505 session_->SignalVideoChannelCreated.connect(
506 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700507 session_->SignalVideoChannelDestroyed.connect(
508 this, &PeerConnection::OnVideoChannelDestroyed);
509 session_->SignalDataChannelCreated.connect(
510 this, &PeerConnection::OnDataChannelCreated);
511 session_->SignalDataChannelDestroyed.connect(
512 this, &PeerConnection::OnDataChannelDestroyed);
513 session_->SignalDataChannelOpenMessage.connect(
514 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800515
516 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000517 return true;
518}
519
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000520rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000521PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700522 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000523}
524
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000525rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000526PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700527 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000528}
529
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000530bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100531 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000532 if (IsClosed()) {
533 return false;
534 }
deadbeefab9b2d12015-10-14 11:33:11 -0700535 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000536 return false;
537 }
deadbeefab9b2d12015-10-14 11:33:11 -0700538
539 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800540 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
541 observer->SignalAudioTrackAdded.connect(this,
542 &PeerConnection::OnAudioTrackAdded);
543 observer->SignalAudioTrackRemoved.connect(
544 this, &PeerConnection::OnAudioTrackRemoved);
545 observer->SignalVideoTrackAdded.connect(this,
546 &PeerConnection::OnVideoTrackAdded);
547 observer->SignalVideoTrackRemoved.connect(
548 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700549 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700550
deadbeefab9b2d12015-10-14 11:33:11 -0700551 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800552 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700553 }
554 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800555 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700556 }
557
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000558 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000559 observer_->OnRenegotiationNeeded();
560 return true;
561}
562
563void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100564 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700565 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800566 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700567 }
568 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800569 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700570 }
571
572 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800573 stream_observers_.erase(
574 std::remove_if(
575 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700576 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800577 return observer->stream()->label().compare(local_stream->label()) ==
578 0;
579 }),
580 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700581
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000582 if (IsClosed()) {
583 return;
584 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585 observer_->OnRenegotiationNeeded();
586}
587
deadbeefe1f9d832016-01-14 15:35:42 -0800588rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
589 MediaStreamTrackInterface* track,
590 std::vector<MediaStreamInterface*> streams) {
591 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
592 if (IsClosed()) {
593 return nullptr;
594 }
595 if (streams.size() >= 2) {
596 LOG(LS_ERROR)
597 << "Adding a track with two streams is not currently supported.";
598 return nullptr;
599 }
600 // TODO(deadbeef): Support adding a track to two different senders.
601 if (FindSenderForTrack(track) != senders_.end()) {
602 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
603 return nullptr;
604 }
605
606 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700607 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800608 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700609 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800610 signaling_thread(),
611 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700612 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800613 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700614 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800615 }
616 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700617 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800618 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700619 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800620 }
621 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700622 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800623 signaling_thread(),
624 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700625 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800626 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700627 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800628 }
629 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700630 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800631 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700632 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800633 }
634 } else {
635 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
636 return rtc::scoped_refptr<RtpSenderInterface>();
637 }
638
639 senders_.push_back(new_sender);
640 observer_->OnRenegotiationNeeded();
641 return new_sender;
642}
643
644bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
645 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
646 if (IsClosed()) {
647 return false;
648 }
649
650 auto it = std::find(senders_.begin(), senders_.end(), sender);
651 if (it == senders_.end()) {
652 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
653 return false;
654 }
deadbeefa601f5c2016-06-06 14:27:39 -0700655 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800656 senders_.erase(it);
657
658 observer_->OnRenegotiationNeeded();
659 return true;
660}
661
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000662rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100664 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700665 if (IsClosed()) {
666 return nullptr;
667 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668 if (!track) {
669 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800670 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671 }
deadbeef20cb0c12017-02-01 20:27:00 -0800672 auto it = FindSenderForTrack(track);
673 if (it == senders_.end()) {
674 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
675 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 }
677
deadbeef20cb0c12017-02-01 20:27:00 -0800678 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000679}
680
deadbeeffac06552015-11-25 11:26:01 -0800681rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800682 const std::string& kind,
683 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100684 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700685 if (IsClosed()) {
686 return nullptr;
687 }
deadbeefa601f5c2016-06-06 14:27:39 -0700688 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800689 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700690 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700691 signaling_thread(),
692 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800693 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700694 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700695 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800696 } else {
697 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800698 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800699 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800700 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700701 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800702 }
deadbeeffac06552015-11-25 11:26:01 -0800703 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800704 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800705}
706
deadbeef70ab1a12015-09-28 16:53:55 -0700707std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
708 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700709 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
710 for (const auto& sender : senders_) {
711 ret.push_back(sender.get());
712 }
713 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700714}
715
716std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
717PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700718 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
719 for (const auto& receiver : receivers_) {
720 ret.push_back(receiver.get());
721 }
722 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700723}
724
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000726 MediaStreamTrackInterface* track,
727 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100728 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700729 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800730 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 LOG(LS_ERROR) << "GetStats - observer is NULL.";
732 return false;
733 }
734
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000735 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700736 // The StatsCollector is used to tell if a track is valid because it may
737 // remember tracks that the PeerConnection previously removed.
738 if (track && !stats_->IsValidTrack(track->id())) {
739 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
740 << track->id();
741 return false;
742 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700743 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000744 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 return true;
746}
747
hbos74e1a4f2016-09-15 23:33:01 -0700748void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
749 RTC_DCHECK(stats_collector_);
750 stats_collector_->GetStatsReport(callback);
751}
752
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
754 return signaling_state_;
755}
756
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000757PeerConnectionInterface::IceConnectionState
758PeerConnection::ice_connection_state() {
759 return ice_connection_state_;
760}
761
762PeerConnectionInterface::IceGatheringState
763PeerConnection::ice_gathering_state() {
764 return ice_gathering_state_;
765}
766
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000767rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000768PeerConnection::CreateDataChannel(
769 const std::string& label,
770 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100771 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700772#ifdef HAVE_QUIC
773 if (session_->data_channel_type() == cricket::DCT_QUIC) {
774 // TODO(zhihuang): Handle case when config is NULL.
775 if (!config) {
776 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
777 return nullptr;
778 }
779 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
780 if (!config->reliable || config->ordered) {
781 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
782 "ordered delivery.";
783 return nullptr;
784 }
785 return session_->quic_data_transport()->CreateDataChannel(label, config);
786 }
787#endif // HAVE_QUIC
788
deadbeefab9b2d12015-10-14 11:33:11 -0700789 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000790
kwibergd1fe2812016-04-27 06:47:29 -0700791 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000792 if (config) {
793 internal_config.reset(new InternalDataChannelInit(*config));
794 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000795 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700796 InternalCreateDataChannel(label, internal_config.get()));
797 if (!channel.get()) {
798 return nullptr;
799 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000801 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
802 // the first SCTP DataChannel.
803 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
804 observer_->OnRenegotiationNeeded();
805 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000806
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 return DataChannelProxy::Create(signaling_thread(), channel.get());
808}
809
810void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
811 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100812 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800813 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
815 return;
816 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000817 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000818
819 bool value;
820 size_t mandatory_constraints = 0;
821
822 if (FindConstraint(constraints,
823 MediaConstraintsInterface::kOfferToReceiveAudio,
824 &value,
825 &mandatory_constraints)) {
826 options.offer_to_receive_audio =
827 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
828 }
829
830 if (FindConstraint(constraints,
831 MediaConstraintsInterface::kOfferToReceiveVideo,
832 &value,
833 &mandatory_constraints)) {
834 options.offer_to_receive_video =
835 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
836 }
837
838 if (FindConstraint(constraints,
839 MediaConstraintsInterface::kVoiceActivityDetection,
840 &value,
841 &mandatory_constraints)) {
842 options.voice_activity_detection = value;
843 }
844
845 if (FindConstraint(constraints,
846 MediaConstraintsInterface::kIceRestart,
847 &value,
848 &mandatory_constraints)) {
849 options.ice_restart = value;
850 }
851
852 if (FindConstraint(constraints,
853 MediaConstraintsInterface::kUseRtpMux,
854 &value,
855 &mandatory_constraints)) {
856 options.use_rtp_mux = value;
857 }
858
859 CreateOffer(observer, options);
860}
861
862void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
863 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100864 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800865 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000866 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
867 return;
868 }
deadbeefab9b2d12015-10-14 11:33:11 -0700869
870 cricket::MediaSessionOptions session_options;
871 if (!GetOptionsForOffer(options, &session_options)) {
872 std::string error = "CreateOffer called with invalid options.";
873 LOG(LS_ERROR) << error;
874 PostCreateSessionDescriptionFailure(observer, error);
875 return;
876 }
877
878 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879}
880
881void PeerConnection::CreateAnswer(
882 CreateSessionDescriptionObserver* observer,
883 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100884 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800885 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
887 return;
888 }
deadbeefab9b2d12015-10-14 11:33:11 -0700889
890 cricket::MediaSessionOptions session_options;
891 if (!GetOptionsForAnswer(constraints, &session_options)) {
892 std::string error = "CreateAnswer called with invalid constraints.";
893 LOG(LS_ERROR) << error;
894 PostCreateSessionDescriptionFailure(observer, error);
895 return;
896 }
897
htaa2a49d92016-03-04 02:51:39 -0800898 session_->CreateAnswer(observer, session_options);
899}
900
901void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
902 const RTCOfferAnswerOptions& options) {
903 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800904 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800905 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
906 return;
907 }
908
909 cricket::MediaSessionOptions session_options;
910 if (!GetOptionsForAnswer(options, &session_options)) {
911 std::string error = "CreateAnswer called with invalid options.";
912 LOG(LS_ERROR) << error;
913 PostCreateSessionDescriptionFailure(observer, error);
914 return;
915 }
916
917 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918}
919
920void PeerConnection::SetLocalDescription(
921 SetSessionDescriptionObserver* observer,
922 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100923 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700924 if (IsClosed()) {
925 return;
926 }
nisse7ce109a2017-01-31 00:57:56 -0800927 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
929 return;
930 }
931 if (!desc) {
932 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
933 return;
934 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 // Update stats here so that we have the most recent stats for tracks and
936 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000937 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 std::string error;
939 if (!session_->SetLocalDescription(desc, &error)) {
940 PostSetSessionDescriptionFailure(observer, error);
941 return;
942 }
deadbeefab9b2d12015-10-14 11:33:11 -0700943
944 // If setting the description decided our SSL role, allocate any necessary
945 // SCTP sids.
946 rtc::SSLRole role;
947 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800948 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700949 AllocateSctpSids(role);
950 }
951
952 // Update state and SSRC of local MediaStreams and DataChannels based on the
953 // local session description.
954 const cricket::ContentInfo* audio_content =
955 GetFirstAudioContent(desc->description());
956 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800957 if (audio_content->rejected) {
958 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
959 } else {
960 const cricket::AudioContentDescription* audio_desc =
961 static_cast<const cricket::AudioContentDescription*>(
962 audio_content->description);
963 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
964 }
deadbeefab9b2d12015-10-14 11:33:11 -0700965 }
966
967 const cricket::ContentInfo* video_content =
968 GetFirstVideoContent(desc->description());
969 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800970 if (video_content->rejected) {
971 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
972 } else {
973 const cricket::VideoContentDescription* video_desc =
974 static_cast<const cricket::VideoContentDescription*>(
975 video_content->description);
976 UpdateLocalTracks(video_desc->streams(), video_desc->type());
977 }
deadbeefab9b2d12015-10-14 11:33:11 -0700978 }
979
980 const cricket::ContentInfo* data_content =
981 GetFirstDataContent(desc->description());
982 if (data_content) {
983 const cricket::DataContentDescription* data_desc =
984 static_cast<const cricket::DataContentDescription*>(
985 data_content->description);
986 if (rtc::starts_with(data_desc->protocol().data(),
987 cricket::kMediaProtocolRtpPrefix)) {
988 UpdateLocalRtpDataChannels(data_desc->streams());
989 }
990 }
991
992 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700993 signaling_thread()->Post(RTC_FROM_HERE, this,
994 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700995
deadbeef42a42632017-03-10 15:18:00 -0800996 // According to JSEP, after setLocalDescription, changing the candidate pool
997 // size is not allowed, and changing the set of ICE servers will not result
998 // in new candidates being gathered.
999 port_allocator_->FreezeCandidatePool();
1000
deadbeefcbecd352015-09-23 11:50:27 -07001001 // MaybeStartGathering needs to be called after posting
1002 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1003 // before signaling that SetLocalDescription completed.
1004 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001005
1006 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1007 // TODO(deadbeef): We already had to hop to the network thread for
1008 // MaybeStartGathering...
1009 network_thread()->Invoke<void>(
1010 RTC_FROM_HERE,
1011 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1012 port_allocator_.get()));
1013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014}
1015
1016void PeerConnection::SetRemoteDescription(
1017 SetSessionDescriptionObserver* observer,
1018 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001019 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001020 if (IsClosed()) {
1021 return;
1022 }
nisse7ce109a2017-01-31 00:57:56 -08001023 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1025 return;
1026 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027 if (!desc) {
1028 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1029 return;
1030 }
1031 // Update stats here so that we have the most recent stats for tracks and
1032 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001033 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 std::string error;
1035 if (!session_->SetRemoteDescription(desc, &error)) {
1036 PostSetSessionDescriptionFailure(observer, error);
1037 return;
1038 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039
deadbeefab9b2d12015-10-14 11:33:11 -07001040 // If setting the description decided our SSL role, allocate any necessary
1041 // SCTP sids.
1042 rtc::SSLRole role;
1043 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001044 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001045 AllocateSctpSids(role);
1046 }
1047
1048 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001049 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1050 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1051 const cricket::AudioContentDescription* audio_desc =
1052 GetFirstAudioContentDescription(remote_desc);
1053 const cricket::VideoContentDescription* video_desc =
1054 GetFirstVideoContentDescription(remote_desc);
1055 const cricket::DataContentDescription* data_desc =
1056 GetFirstDataContentDescription(remote_desc);
1057
1058 // Check if the descriptions include streams, just in case the peer supports
1059 // MSID, but doesn't indicate so with "a=msid-semantic".
1060 if (remote_desc->msid_supported() ||
1061 (audio_desc && !audio_desc->streams().empty()) ||
1062 (video_desc && !video_desc->streams().empty())) {
1063 remote_peer_supports_msid_ = true;
1064 }
deadbeefab9b2d12015-10-14 11:33:11 -07001065
1066 // We wait to signal new streams until we finish processing the description,
1067 // since only at that point will new streams have all their tracks.
1068 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1069
1070 // Find all audio rtp streams and create corresponding remote AudioTracks
1071 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001072 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001073 if (audio_content->rejected) {
1074 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1075 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001076 bool default_audio_track_needed =
1077 !remote_peer_supports_msid_ &&
1078 MediaContentDirectionHasSend(audio_desc->direction());
1079 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1080 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001081 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001082 }
deadbeefab9b2d12015-10-14 11:33:11 -07001083 }
1084
1085 // Find all video rtp streams and create corresponding remote VideoTracks
1086 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001087 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001088 if (video_content->rejected) {
1089 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1090 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001091 bool default_video_track_needed =
1092 !remote_peer_supports_msid_ &&
1093 MediaContentDirectionHasSend(video_desc->direction());
1094 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1095 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001096 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001097 }
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099
1100 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001101 if (data_desc) {
1102 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001103 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001104 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001105 }
1106 }
1107
1108 // Iterate new_streams and notify the observer about new MediaStreams.
1109 for (size_t i = 0; i < new_streams->count(); ++i) {
1110 MediaStreamInterface* new_stream = new_streams->at(i);
1111 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001112 observer_->OnAddStream(
1113 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001114 }
1115
deadbeefbda7e0b2015-12-08 17:13:40 -08001116 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001117
1118 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001119 signaling_thread()->Post(RTC_FROM_HERE, this,
1120 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001121
1122 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1123 // TODO(deadbeef): We already had to hop to the network thread for
1124 // MaybeStartGathering...
1125 network_thread()->Invoke<void>(
1126 RTC_FROM_HERE,
1127 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1128 port_allocator_.get()));
1129 }
deadbeeffc648b62015-10-13 16:42:33 -07001130}
1131
deadbeef46c73892016-11-16 19:42:04 -08001132PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1133 return configuration_;
1134}
1135
deadbeef293e9262017-01-11 12:28:30 -08001136bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1137 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001138 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001139
1140 if (session_->local_description() &&
1141 configuration.ice_candidate_pool_size !=
1142 configuration_.ice_candidate_pool_size) {
1143 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1144 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001145 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001146 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001147
deadbeef293e9262017-01-11 12:28:30 -08001148 // The simplest (and most future-compatible) way to tell if the config was
1149 // modified in an invalid way is to copy each property we do support
1150 // modifying, then use operator==. There are far more properties we don't
1151 // support modifying than those we do, and more could be added.
1152 RTCConfiguration modified_config = configuration_;
1153 modified_config.servers = configuration.servers;
1154 modified_config.type = configuration.type;
1155 modified_config.ice_candidate_pool_size =
1156 configuration.ice_candidate_pool_size;
1157 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001158 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001159 if (configuration != modified_config) {
1160 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1161 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1162 }
1163
1164 // Note that this isn't possible through chromium, since it's an unsigned
1165 // short in WebIDL.
1166 if (configuration.ice_candidate_pool_size < 0 ||
1167 configuration.ice_candidate_pool_size > UINT16_MAX) {
1168 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1169 }
1170
1171 // Parse ICE servers before hopping to network thread.
1172 cricket::ServerAddresses stun_servers;
1173 std::vector<cricket::RelayServerConfig> turn_servers;
1174 RTCErrorType parse_error =
1175 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1176 if (parse_error != RTCErrorType::NONE) {
1177 return SafeSetError(parse_error, error);
1178 }
1179
1180 // In theory this shouldn't fail.
1181 if (!network_thread()->Invoke<bool>(
1182 RTC_FROM_HERE,
1183 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1184 stun_servers, turn_servers, modified_config.type,
1185 modified_config.ice_candidate_pool_size,
1186 modified_config.prune_turn_ports))) {
1187 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1188 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1189 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001190
deadbeefd1a38b52016-12-10 13:15:33 -08001191 // As described in JSEP, calling setConfiguration with new ICE servers or
1192 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1193 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001194 if (modified_config.servers != configuration_.servers ||
1195 modified_config.type != configuration_.type ||
1196 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001197 session_->SetNeedsIceRestartFlag();
1198 }
skvladd1f5fda2017-02-03 16:54:05 -08001199
1200 if (modified_config.ice_check_min_interval !=
1201 configuration_.ice_check_min_interval) {
1202 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1203 }
1204
deadbeef293e9262017-01-11 12:28:30 -08001205 configuration_ = modified_config;
1206 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001207}
1208
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209bool PeerConnection::AddIceCandidate(
1210 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001211 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001212 if (IsClosed()) {
1213 return false;
1214 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001215 return session_->ProcessIceMessage(ice_candidate);
1216}
1217
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001218bool PeerConnection::RemoveIceCandidates(
1219 const std::vector<cricket::Candidate>& candidates) {
1220 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1221 return session_->RemoveRemoteIceCandidates(candidates);
1222}
1223
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001224void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001225 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001226 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001227
1228 if (session_) {
1229 session_->set_metrics_observer(uma_observer_);
1230 }
1231
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001232 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001233 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001234 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001235 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001236 uma_observer_->IncrementEnumCounter(
1237 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1238 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001239 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001240 uma_observer_->IncrementEnumCounter(
1241 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1242 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001243 }
1244 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001245}
1246
zstein4b979802017-06-02 14:37:37 -07001247RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
1248 rtc::Thread* worker_thread = factory_->worker_thread();
1249 if (!worker_thread->IsCurrent()) {
1250 return worker_thread->Invoke<RTCError>(
1251 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1252 }
1253
1254 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1255 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1256 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1257 if (has_min && *bitrate.min_bitrate_bps < 0) {
1258 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1259 "min_bitrate_bps <= 0");
1260 }
1261 if (has_current) {
1262 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1263 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1264 "current_bitrate_bps < min_bitrate_bps");
1265 } else if (*bitrate.current_bitrate_bps < 0) {
1266 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1267 "curent_bitrate_bps < 0");
1268 }
1269 }
1270 if (has_max) {
1271 if (has_current &&
1272 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1274 "max_bitrate_bps < current_bitrate_bps");
1275 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1277 "max_bitrate_bps < min_bitrate_bps");
1278 } else if (*bitrate.max_bitrate_bps < 0) {
1279 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1280 "max_bitrate_bps < 0");
1281 }
1282 }
1283
1284 Call::Config::BitrateConfigMask mask;
1285 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1286 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1287 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1288
1289 RTC_DCHECK(call_.get());
1290 call_->SetBitrateConfigMask(mask);
1291
1292 return RTCError::OK();
1293}
1294
ivoc14d5dbe2016-07-04 07:06:55 -07001295bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1296 int64_t max_size_bytes) {
1297 return factory_->worker_thread()->Invoke<bool>(
1298 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1299 max_size_bytes));
1300}
1301
1302void PeerConnection::StopRtcEventLog() {
1303 factory_->worker_thread()->Invoke<void>(
1304 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1305}
1306
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307const SessionDescriptionInterface* PeerConnection::local_description() const {
1308 return session_->local_description();
1309}
1310
1311const SessionDescriptionInterface* PeerConnection::remote_description() const {
1312 return session_->remote_description();
1313}
1314
deadbeeffe4a8a42016-12-20 17:56:17 -08001315const SessionDescriptionInterface* PeerConnection::current_local_description()
1316 const {
1317 return session_->current_local_description();
1318}
1319
1320const SessionDescriptionInterface* PeerConnection::current_remote_description()
1321 const {
1322 return session_->current_remote_description();
1323}
1324
1325const SessionDescriptionInterface* PeerConnection::pending_local_description()
1326 const {
1327 return session_->pending_local_description();
1328}
1329
1330const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1331 const {
1332 return session_->pending_remote_description();
1333}
1334
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001336 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 // Update stats here so that we have the most recent stats for tracks and
1338 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001339 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340
deadbeefd59daf82015-10-14 15:02:44 -07001341 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001342 network_thread()->Invoke<void>(
1343 RTC_FROM_HERE,
1344 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1345 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001346
1347 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
1348 [this] { call_.reset(); });
terelius33860252017-05-12 23:37:18 -07001349
1350 // The event log must outlive call (and any other object that uses it).
1351 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352}
1353
deadbeefd59daf82015-10-14 15:02:44 -07001354void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1355 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001357 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001359 break;
deadbeefd59daf82015-10-14 15:02:44 -07001360 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1362 break;
deadbeefd59daf82015-10-14 15:02:44 -07001363 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1365 break;
deadbeefd59daf82015-10-14 15:02:44 -07001366 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1368 break;
deadbeefd59daf82015-10-14 15:02:44 -07001369 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1371 break;
deadbeefd59daf82015-10-14 15:02:44 -07001372 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373 ChangeSignalingState(PeerConnectionInterface::kStable);
1374 break;
deadbeefd59daf82015-10-14 15:02:44 -07001375 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376 ChangeSignalingState(PeerConnectionInterface::kClosed);
1377 break;
1378 default:
1379 break;
1380 }
1381}
1382
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001383void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1386 SetSessionDescriptionMsg* param =
1387 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1388 param->observer->OnSuccess();
1389 delete param;
1390 break;
1391 }
1392 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1393 SetSessionDescriptionMsg* param =
1394 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1395 param->observer->OnFailure(param->error);
1396 delete param;
1397 break;
1398 }
deadbeefab9b2d12015-10-14 11:33:11 -07001399 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1400 CreateSessionDescriptionMsg* param =
1401 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1402 param->observer->OnFailure(param->error);
1403 delete param;
1404 break;
1405 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406 case MSG_GETSTATS: {
1407 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001408 StatsReports reports;
1409 stats_->GetStats(param->track, &reports);
1410 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 delete param;
1412 break;
1413 }
deadbeefbd292462015-12-14 18:15:29 -08001414 case MSG_FREE_DATACHANNELS: {
1415 sctp_data_channels_to_free_.clear();
1416 break;
1417 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001418 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001419 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001420 break;
1421 }
1422}
1423
deadbeefab9b2d12015-10-14 11:33:11 -07001424void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001425 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001426 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001427 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1428 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001429 signaling_thread(),
1430 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1431 stream->AddTrack(
1432 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001433 receivers_.push_back(receiver);
1434 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1435 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1436 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437}
1438
deadbeefab9b2d12015-10-14 11:33:11 -07001439void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001440 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001441 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001442 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1443 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001444 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001445 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1446 session_->video_channel()));
1447 stream->AddTrack(
1448 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001449 receivers_.push_back(receiver);
1450 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1451 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1452 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453}
1454
deadbeef70ab1a12015-09-28 16:53:55 -07001455// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1456// description.
perkjd61bf802016-03-24 03:16:19 -07001457void PeerConnection::DestroyReceiver(const std::string& track_id) {
1458 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001459 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001460 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001461 << " doesn't exist.";
1462 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001463 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001464 receivers_.erase(it);
1465 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466}
1467
zstein6dfd53a2017-03-06 13:49:03 -08001468void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001470 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001471 // After transitioning to "closed", ignore any additional states from
1472 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001473 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001474 return;
1475 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001477 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478}
1479
1480void PeerConnection::OnIceGatheringChange(
1481 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001482 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 if (IsClosed()) {
1484 return;
1485 }
1486 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001487 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488}
1489
jbauch81bf7b02017-03-25 08:31:12 -07001490void PeerConnection::OnIceCandidate(
1491 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001492 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001493 if (IsClosed()) {
1494 return;
1495 }
jbauch81bf7b02017-03-25 08:31:12 -07001496 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497}
1498
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001499void PeerConnection::OnIceCandidatesRemoved(
1500 const std::vector<cricket::Candidate>& candidates) {
1501 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001502 if (IsClosed()) {
1503 return;
1504 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001505 observer_->OnIceCandidatesRemoved(candidates);
1506}
1507
Peter Thatcher54360512015-07-08 11:08:35 -07001508void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001509 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001510 if (IsClosed()) {
1511 return;
1512 }
Peter Thatcher54360512015-07-08 11:08:35 -07001513 observer_->OnIceConnectionReceivingChange(receiving);
1514}
1515
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001516void PeerConnection::ChangeSignalingState(
1517 PeerConnectionInterface::SignalingState signaling_state) {
1518 signaling_state_ = signaling_state;
1519 if (signaling_state == kClosed) {
1520 ice_connection_state_ = kIceConnectionClosed;
1521 observer_->OnIceConnectionChange(ice_connection_state_);
1522 if (ice_gathering_state_ != kIceGatheringComplete) {
1523 ice_gathering_state_ = kIceGatheringComplete;
1524 observer_->OnIceGatheringChange(ice_gathering_state_);
1525 }
1526 }
1527 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528}
1529
deadbeefeb459812015-12-15 19:24:43 -08001530void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1531 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001532 if (IsClosed()) {
1533 return;
1534 }
deadbeefeb459812015-12-15 19:24:43 -08001535 auto sender = FindSenderForTrack(track);
1536 if (sender != senders_.end()) {
1537 // We already have a sender for this track, so just change the stream_id
1538 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001539 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001540 return;
1541 }
1542
1543 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001544 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1545 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001546 signaling_thread(),
1547 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1548 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001549 senders_.push_back(new_sender);
1550 // If the sender has already been configured in SDP, we call SetSsrc,
1551 // which will connect the sender to the underlying transport. This can
1552 // occur if a local session description that contains the ID of the sender
1553 // is set before AddStream is called. It can also occur if the local
1554 // session description is not changed and RemoveStream is called, and
1555 // later AddStream is called again with the same stream.
1556 const TrackInfo* track_info =
1557 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1558 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001559 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001560 }
1561}
1562
1563// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1564// indefinitely, when we have unified plan SDP.
1565void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1566 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001567 if (IsClosed()) {
1568 return;
1569 }
deadbeefeb459812015-12-15 19:24:43 -08001570 auto sender = FindSenderForTrack(track);
1571 if (sender == senders_.end()) {
1572 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1573 << " doesn't exist.";
1574 return;
1575 }
deadbeefa601f5c2016-06-06 14:27:39 -07001576 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001577 senders_.erase(sender);
1578}
1579
1580void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1581 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001582 if (IsClosed()) {
1583 return;
1584 }
deadbeefeb459812015-12-15 19:24:43 -08001585 auto sender = FindSenderForTrack(track);
1586 if (sender != senders_.end()) {
1587 // We already have a sender for this track, so just change the stream_id
1588 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001589 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001590 return;
1591 }
1592
1593 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001594 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1595 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001596 signaling_thread(), new VideoRtpSender(track, stream->label(),
1597 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001598 senders_.push_back(new_sender);
1599 const TrackInfo* track_info =
1600 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1601 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001602 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001603 }
1604}
1605
1606void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1607 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001608 if (IsClosed()) {
1609 return;
1610 }
deadbeefeb459812015-12-15 19:24:43 -08001611 auto sender = FindSenderForTrack(track);
1612 if (sender == senders_.end()) {
1613 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1614 << " doesn't exist.";
1615 return;
1616 }
deadbeefa601f5c2016-06-06 14:27:39 -07001617 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001618 senders_.erase(sender);
1619}
1620
deadbeefab9b2d12015-10-14 11:33:11 -07001621void PeerConnection::PostSetSessionDescriptionFailure(
1622 SetSessionDescriptionObserver* observer,
1623 const std::string& error) {
1624 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1625 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001626 signaling_thread()->Post(RTC_FROM_HERE, this,
1627 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001628}
1629
1630void PeerConnection::PostCreateSessionDescriptionFailure(
1631 CreateSessionDescriptionObserver* observer,
1632 const std::string& error) {
1633 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1634 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001635 signaling_thread()->Post(RTC_FROM_HERE, this,
1636 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001637}
1638
1639bool PeerConnection::GetOptionsForOffer(
1640 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1641 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001642 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1643 // ContentInfos.
1644 if (session_->local_description()) {
1645 for (const cricket::ContentInfo& content :
1646 session_->local_description()->description()->contents()) {
1647 session_options->transport_options[content.name] =
1648 cricket::TransportOptions();
1649 }
1650 }
deadbeef46c73892016-11-16 19:42:04 -08001651 session_options->enable_ice_renomination =
1652 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001653
htaaac2dea2016-03-10 13:35:55 -08001654 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001655 return false;
1656 }
1657
deadbeeffac06552015-11-25 11:26:01 -08001658 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001659 // Offer to receive audio/video if the constraint is not set and there are
1660 // send streams, or we're currently receiving.
1661 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1662 session_options->recv_audio =
1663 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1664 !remote_audio_tracks_.empty();
1665 }
1666 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1667 session_options->recv_video =
1668 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1669 !remote_video_tracks_.empty();
1670 }
deadbeefc80741f2015-10-22 13:14:45 -07001671
zhihuang9763d562016-08-05 11:14:50 -07001672 // Intentionally unset the data channel type for RTP data channel with the
1673 // second condition. Otherwise the RTP data channels would be successfully
1674 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1675 // when building with chromium. We want to leave RTP data channels broken, so
1676 // people won't try to use them.
1677 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1678 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001679 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001680
zhihuangaf388472016-11-02 16:49:48 -07001681 session_options->bundle_enabled =
1682 session_options->bundle_enabled &&
1683 (session_options->has_audio() || session_options->has_video() ||
1684 session_options->has_data());
1685
zhihuang8f65cdf2016-05-06 18:40:30 -07001686 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001687 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001688 return true;
1689}
1690
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001691void PeerConnection::InitializeOptionsForAnswer(
1692 cricket::MediaSessionOptions* session_options) {
1693 session_options->recv_audio = false;
1694 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001695 session_options->enable_ice_renomination =
1696 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001697}
1698
htaa2a49d92016-03-04 02:51:39 -08001699void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001700 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001701 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1702 // ContentInfos.
1703 if (session_->remote_description()) {
1704 // Initialize the transport_options map.
1705 for (const cricket::ContentInfo& content :
1706 session_->remote_description()->description()->contents()) {
1707 session_options->transport_options[content.name] =
1708 cricket::TransportOptions();
1709 }
1710 }
deadbeeffac06552015-11-25 11:26:01 -08001711 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001712 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1713 // are not signaled in the SDP so does not go through that path and must be
1714 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001715 // Intentionally unset the data channel type for RTP data channel. Otherwise
1716 // the RTP data channels would be successfully negotiated by default and the
1717 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1718 // We want to leave RTP data channels broken, so people won't try to use them.
1719 if (session_->data_channel_type() != cricket::DCT_RTP) {
1720 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001721 }
zhihuangaf388472016-11-02 16:49:48 -07001722 session_options->bundle_enabled =
1723 session_options->bundle_enabled &&
1724 (session_options->has_audio() || session_options->has_video() ||
1725 session_options->has_data());
1726
jbauchcb560652016-08-04 05:20:32 -07001727 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001728}
1729
1730bool PeerConnection::GetOptionsForAnswer(
1731 const MediaConstraintsInterface* constraints,
1732 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001733 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001734 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1735 return false;
1736 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001737 session_options->rtcp_cname = rtcp_cname_;
1738
htaa2a49d92016-03-04 02:51:39 -08001739 FinishOptionsForAnswer(session_options);
1740 return true;
1741}
1742
1743bool PeerConnection::GetOptionsForAnswer(
1744 const RTCOfferAnswerOptions& options,
1745 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001746 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001747 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001748 return false;
1749 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001750 session_options->rtcp_cname = rtcp_cname_;
1751
htaa2a49d92016-03-04 02:51:39 -08001752 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001753 return true;
1754}
1755
deadbeeffaac4972015-11-12 15:33:07 -08001756void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1757 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001758 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1759 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001760}
1761
deadbeefab9b2d12015-10-14 11:33:11 -07001762void PeerConnection::UpdateRemoteStreamsList(
1763 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001764 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001765 cricket::MediaType media_type,
1766 StreamCollection* new_streams) {
1767 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1768
1769 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001770 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001771 auto track_it = current_tracks->begin();
1772 while (track_it != current_tracks->end()) {
1773 const TrackInfo& info = *track_it;
1774 const cricket::StreamParams* params =
1775 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001776 bool track_exists = params && params->id == info.track_id;
1777 // If this is a default track, and we still need it, don't remove it.
1778 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1779 track_exists) {
1780 ++track_it;
1781 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001782 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1783 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001784 }
1785 }
1786
1787 // Find new and active tracks.
1788 for (const cricket::StreamParams& params : streams) {
1789 // The sync_label is the MediaStream label and the |stream.id| is the
1790 // track id.
1791 const std::string& stream_label = params.sync_label;
1792 const std::string& track_id = params.id;
1793 uint32_t ssrc = params.first_ssrc();
1794
1795 rtc::scoped_refptr<MediaStreamInterface> stream =
1796 remote_streams_->find(stream_label);
1797 if (!stream) {
1798 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001799 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1800 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001801 remote_streams_->AddStream(stream);
1802 new_streams->AddStream(stream);
1803 }
1804
1805 const TrackInfo* track_info =
1806 FindTrackInfo(*current_tracks, stream_label, track_id);
1807 if (!track_info) {
1808 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1809 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1810 }
1811 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001812
1813 // Add default track if necessary.
1814 if (default_track_needed) {
1815 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1816 remote_streams_->find(kDefaultStreamLabel);
1817 if (!default_stream) {
1818 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001819 default_stream = MediaStreamProxy::Create(
1820 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001821 remote_streams_->AddStream(default_stream);
1822 new_streams->AddStream(default_stream);
1823 }
1824 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1825 ? kDefaultAudioTrackLabel
1826 : kDefaultVideoTrackLabel;
1827 const TrackInfo* default_track_info =
1828 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1829 if (!default_track_info) {
1830 current_tracks->push_back(
1831 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1832 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1833 }
1834 }
deadbeefab9b2d12015-10-14 11:33:11 -07001835}
1836
1837void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1838 const std::string& track_id,
1839 uint32_t ssrc,
1840 cricket::MediaType media_type) {
1841 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1842
1843 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001844 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001845 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001846 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001847 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001848 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001849 }
1850}
1851
1852void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1853 const std::string& track_id,
1854 cricket::MediaType media_type) {
1855 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1856
1857 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001858 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1859 // will be notified which will end the AudioRtpReceiver::track().
1860 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001861 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1862 stream->FindAudioTrack(track_id);
1863 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001864 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001865 }
1866 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001867 // Stopping or destroying a VideoRtpReceiver will end the
1868 // VideoRtpReceiver::track().
1869 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001870 rtc::scoped_refptr<VideoTrackInterface> video_track =
1871 stream->FindVideoTrack(track_id);
1872 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001873 // There's no guarantee the track is still available, e.g. the track may
1874 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001875 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001876 }
1877 } else {
nisseede5da42017-01-12 05:15:36 -08001878 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001879 }
1880}
1881
1882void PeerConnection::UpdateEndedRemoteMediaStreams() {
1883 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1884 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1885 MediaStreamInterface* stream = remote_streams_->at(i);
1886 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1887 streams_to_remove.push_back(stream);
1888 }
1889 }
1890
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001891 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001892 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001893 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001894 }
1895}
1896
deadbeefab9b2d12015-10-14 11:33:11 -07001897void PeerConnection::UpdateLocalTracks(
1898 const std::vector<cricket::StreamParams>& streams,
1899 cricket::MediaType media_type) {
1900 TrackInfos* current_tracks = GetLocalTracks(media_type);
1901
1902 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1903 // don't match the new StreamParam.
1904 TrackInfos::iterator track_it = current_tracks->begin();
1905 while (track_it != current_tracks->end()) {
1906 const TrackInfo& info = *track_it;
1907 const cricket::StreamParams* params =
1908 cricket::GetStreamBySsrc(streams, info.ssrc);
1909 if (!params || params->id != info.track_id ||
1910 params->sync_label != info.stream_label) {
1911 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1912 media_type);
1913 track_it = current_tracks->erase(track_it);
1914 } else {
1915 ++track_it;
1916 }
1917 }
1918
1919 // Find new and active tracks.
1920 for (const cricket::StreamParams& params : streams) {
1921 // The sync_label is the MediaStream label and the |stream.id| is the
1922 // track id.
1923 const std::string& stream_label = params.sync_label;
1924 const std::string& track_id = params.id;
1925 uint32_t ssrc = params.first_ssrc();
1926 const TrackInfo* track_info =
1927 FindTrackInfo(*current_tracks, stream_label, track_id);
1928 if (!track_info) {
1929 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1930 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1931 }
1932 }
1933}
1934
1935void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1936 const std::string& track_id,
1937 uint32_t ssrc,
1938 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001939 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001940 if (!sender) {
1941 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1942 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001943 return;
1944 }
1945
deadbeeffac06552015-11-25 11:26:01 -08001946 if (sender->media_type() != media_type) {
1947 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1948 << " description with an unexpected media type.";
1949 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001950 }
deadbeeffac06552015-11-25 11:26:01 -08001951
1952 sender->set_stream_id(stream_label);
1953 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001954}
1955
1956void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1957 const std::string& track_id,
1958 uint32_t ssrc,
1959 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001960 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001961 if (!sender) {
1962 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001963 // SessionDescriptions has been renegotiated.
1964 return;
1965 }
deadbeeffac06552015-11-25 11:26:01 -08001966
1967 // A sender has been removed from the SessionDescription but it's still
1968 // associated with the PeerConnection. This only occurs if the SDP doesn't
1969 // match with the calls to CreateSender, AddStream and RemoveStream.
1970 if (sender->media_type() != media_type) {
1971 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1972 << " description with an unexpected media type.";
1973 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001974 }
deadbeeffac06552015-11-25 11:26:01 -08001975
1976 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001977}
1978
1979void PeerConnection::UpdateLocalRtpDataChannels(
1980 const cricket::StreamParamsVec& streams) {
1981 std::vector<std::string> existing_channels;
1982
1983 // Find new and active data channels.
1984 for (const cricket::StreamParams& params : streams) {
1985 // |it->sync_label| is actually the data channel label. The reason is that
1986 // we use the same naming of data channels as we do for
1987 // MediaStreams and Tracks.
1988 // For MediaStreams, the sync_label is the MediaStream label and the
1989 // track label is the same as |streamid|.
1990 const std::string& channel_label = params.sync_label;
1991 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08001992 if (data_channel_it == rtp_data_channels_.end()) {
1993 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07001994 continue;
1995 }
1996 // Set the SSRC the data channel should use for sending.
1997 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1998 existing_channels.push_back(data_channel_it->first);
1999 }
2000
2001 UpdateClosingRtpDataChannels(existing_channels, true);
2002}
2003
2004void PeerConnection::UpdateRemoteRtpDataChannels(
2005 const cricket::StreamParamsVec& streams) {
2006 std::vector<std::string> existing_channels;
2007
2008 // Find new and active data channels.
2009 for (const cricket::StreamParams& params : streams) {
2010 // The data channel label is either the mslabel or the SSRC if the mslabel
2011 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2012 std::string label = params.sync_label.empty()
2013 ? rtc::ToString(params.first_ssrc())
2014 : params.sync_label;
2015 auto data_channel_it = rtp_data_channels_.find(label);
2016 if (data_channel_it == rtp_data_channels_.end()) {
2017 // This is a new data channel.
2018 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2019 } else {
2020 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2021 }
2022 existing_channels.push_back(label);
2023 }
2024
2025 UpdateClosingRtpDataChannels(existing_channels, false);
2026}
2027
2028void PeerConnection::UpdateClosingRtpDataChannels(
2029 const std::vector<std::string>& active_channels,
2030 bool is_local_update) {
2031 auto it = rtp_data_channels_.begin();
2032 while (it != rtp_data_channels_.end()) {
2033 DataChannel* data_channel = it->second;
2034 if (std::find(active_channels.begin(), active_channels.end(),
2035 data_channel->label()) != active_channels.end()) {
2036 ++it;
2037 continue;
2038 }
2039
2040 if (is_local_update) {
2041 data_channel->SetSendSsrc(0);
2042 } else {
2043 data_channel->RemotePeerRequestClose();
2044 }
2045
2046 if (data_channel->state() == DataChannel::kClosed) {
2047 rtp_data_channels_.erase(it);
2048 it = rtp_data_channels_.begin();
2049 } else {
2050 ++it;
2051 }
2052 }
2053}
2054
2055void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2056 uint32_t remote_ssrc) {
2057 rtc::scoped_refptr<DataChannel> channel(
2058 InternalCreateDataChannel(label, nullptr));
2059 if (!channel.get()) {
2060 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2061 << "CreateDataChannel failed.";
2062 return;
2063 }
2064 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002065 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2066 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002067 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002068}
2069
2070rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2071 const std::string& label,
2072 const InternalDataChannelInit* config) {
2073 if (IsClosed()) {
2074 return nullptr;
2075 }
2076 if (session_->data_channel_type() == cricket::DCT_NONE) {
2077 LOG(LS_ERROR)
2078 << "InternalCreateDataChannel: Data is not supported in this call.";
2079 return nullptr;
2080 }
2081 InternalDataChannelInit new_config =
2082 config ? (*config) : InternalDataChannelInit();
2083 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2084 if (new_config.id < 0) {
2085 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002086 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002087 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2088 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2089 return nullptr;
2090 }
2091 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2092 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2093 << "because the id is already in use or out of range.";
2094 return nullptr;
2095 }
2096 }
2097
2098 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2099 session_.get(), session_->data_channel_type(), label, new_config));
2100 if (!channel) {
2101 sid_allocator_.ReleaseSid(new_config.id);
2102 return nullptr;
2103 }
2104
2105 if (channel->data_channel_type() == cricket::DCT_RTP) {
2106 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2107 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2108 << " already exists.";
2109 return nullptr;
2110 }
2111 rtp_data_channels_[channel->label()] = channel;
2112 } else {
2113 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2114 sctp_data_channels_.push_back(channel);
2115 channel->SignalClosed.connect(this,
2116 &PeerConnection::OnSctpDataChannelClosed);
2117 }
2118
hbos82ebe022016-11-14 01:41:09 -08002119 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002120 return channel;
2121}
2122
2123bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002124#ifdef HAVE_QUIC
2125 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2126 (session_->quic_data_transport() &&
2127 session_->quic_data_transport()->HasDataChannels());
2128#else
deadbeefab9b2d12015-10-14 11:33:11 -07002129 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002130#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002131}
2132
2133void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2134 for (const auto& channel : sctp_data_channels_) {
2135 if (channel->id() < 0) {
2136 int sid;
2137 if (!sid_allocator_.AllocateSid(role, &sid)) {
2138 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2139 continue;
2140 }
2141 channel->SetSctpSid(sid);
2142 }
2143 }
2144}
2145
2146void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002147 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002148 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2149 ++it) {
2150 if (it->get() == channel) {
2151 if (channel->id() >= 0) {
2152 sid_allocator_.ReleaseSid(channel->id());
2153 }
deadbeefbd292462015-12-14 18:15:29 -08002154 // Since this method is triggered by a signal from the DataChannel,
2155 // we can't free it directly here; we need to free it asynchronously.
2156 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002157 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002158 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2159 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002160 return;
2161 }
2162 }
2163}
2164
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002165void PeerConnection::OnVoiceChannelCreated() {
2166 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2167 session_->voice_channel(), senders_, receivers_,
2168 cricket::MEDIA_TYPE_AUDIO);
2169}
2170
deadbeefab9b2d12015-10-14 11:33:11 -07002171void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002172 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2173 cricket::VoiceChannel>(
2174 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2175}
2176
2177void PeerConnection::OnVideoChannelCreated() {
2178 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2179 session_->video_channel(), senders_, receivers_,
2180 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002181}
2182
2183void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002184 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2185 cricket::VideoChannel>(
2186 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002187}
2188
2189void PeerConnection::OnDataChannelCreated() {
2190 for (const auto& channel : sctp_data_channels_) {
2191 channel->OnTransportChannelCreated();
2192 }
2193}
2194
2195void PeerConnection::OnDataChannelDestroyed() {
2196 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2197 // DataChannel may callback to us and try to modify the list.
2198 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2199 temp_rtp_dcs.swap(rtp_data_channels_);
2200 for (const auto& kv : temp_rtp_dcs) {
2201 kv.second->OnTransportChannelDestroyed();
2202 }
2203
2204 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2205 temp_sctp_dcs.swap(sctp_data_channels_);
2206 for (const auto& channel : temp_sctp_dcs) {
2207 channel->OnTransportChannelDestroyed();
2208 }
2209}
2210
2211void PeerConnection::OnDataChannelOpenMessage(
2212 const std::string& label,
2213 const InternalDataChannelInit& config) {
2214 rtc::scoped_refptr<DataChannel> channel(
2215 InternalCreateDataChannel(label, &config));
2216 if (!channel.get()) {
2217 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2218 return;
2219 }
2220
deadbeefa601f5c2016-06-06 14:27:39 -07002221 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2222 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002223 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002224}
2225
deadbeefa601f5c2016-06-06 14:27:39 -07002226RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2227 auto it = std::find_if(
2228 senders_.begin(), senders_.end(),
2229 [id](const rtc::scoped_refptr<
2230 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2231 return sender->id() == id;
2232 });
2233 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002234}
2235
deadbeefa601f5c2016-06-06 14:27:39 -07002236std::vector<
2237 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002238PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2239 return std::find_if(
2240 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002241 [track](const rtc::scoped_refptr<
2242 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002243 return sender->track() == track;
2244 });
2245}
2246
deadbeefa601f5c2016-06-06 14:27:39 -07002247std::vector<rtc::scoped_refptr<
2248 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002249PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002250 return std::find_if(
2251 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002252 [track_id](const rtc::scoped_refptr<
2253 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002254 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002255 });
2256}
2257
deadbeefab9b2d12015-10-14 11:33:11 -07002258PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2259 cricket::MediaType media_type) {
2260 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2261 media_type == cricket::MEDIA_TYPE_VIDEO);
2262 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2263 : &remote_video_tracks_;
2264}
2265
2266PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2267 cricket::MediaType media_type) {
2268 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2269 media_type == cricket::MEDIA_TYPE_VIDEO);
2270 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2271 : &local_video_tracks_;
2272}
2273
2274const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2275 const PeerConnection::TrackInfos& infos,
2276 const std::string& stream_label,
2277 const std::string track_id) const {
2278 for (const TrackInfo& track_info : infos) {
2279 if (track_info.stream_label == stream_label &&
2280 track_info.track_id == track_id) {
2281 return &track_info;
2282 }
2283 }
2284 return nullptr;
2285}
2286
2287DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2288 for (const auto& channel : sctp_data_channels_) {
2289 if (channel->id() == sid) {
2290 return channel;
2291 }
2292 }
2293 return nullptr;
2294}
2295
deadbeef91dd5672016-05-18 16:55:30 -07002296bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002297 const RTCConfiguration& configuration) {
2298 cricket::ServerAddresses stun_servers;
2299 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002300 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2301 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002302 return false;
2303 }
2304
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002305 port_allocator_->Initialize();
2306
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002307 // To handle both internal and externally created port allocator, we will
2308 // enable BUNDLE here.
2309 int portallocator_flags = port_allocator_->flags();
2310 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002311 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2312 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002313 // If the disable-IPv6 flag was specified, we'll not override it
2314 // by experiment.
2315 if (configuration.disable_ipv6) {
2316 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002317 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2318 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002319 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2320 }
2321
zhihuangb09b3f92017-03-07 14:40:51 -08002322 if (configuration.disable_ipv6_on_wifi) {
2323 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2324 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2325 }
2326
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002327 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2328 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2329 LOG(LS_INFO) << "TCP candidates are disabled.";
2330 }
2331
honghaiz60347052016-05-31 18:29:12 -07002332 if (configuration.candidate_network_policy ==
2333 kCandidateNetworkPolicyLowCost) {
2334 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2335 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2336 }
2337
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002338 port_allocator_->set_flags(portallocator_flags);
2339 // No step delay is used while allocating ports.
2340 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2341 port_allocator_->set_candidate_filter(
2342 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2343
2344 // Call this last since it may create pooled allocator sessions using the
2345 // properties set above.
2346 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002347 configuration.ice_candidate_pool_size,
2348 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002349 return true;
2350}
2351
deadbeef91dd5672016-05-18 16:55:30 -07002352bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002353 const cricket::ServerAddresses& stun_servers,
2354 const std::vector<cricket::RelayServerConfig>& turn_servers,
2355 IceTransportsType type,
2356 int candidate_pool_size,
2357 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002358 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002359 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002360 // Call this last since it may create pooled allocator sessions using the
2361 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002362 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002363 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002364}
2365
ivoc14d5dbe2016-07-04 07:06:55 -07002366bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2367 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002368 if (!event_log_) {
2369 return false;
2370 }
skvlad11a9cbf2016-10-07 11:53:05 -07002371 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002372}
2373
2374void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002375 if (event_log_) {
2376 event_log_->StopLogging();
2377 }
ivoc14d5dbe2016-07-04 07:06:55 -07002378}
nisseeaabdf62017-05-05 02:23:02 -07002379
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380} // namespace webrtc