blob: 5007f3351ce5d1d420011f4b74eec2b60215e7b3 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "api/jsepicecandidate.h"
18#include "api/jsepsessiondescription.h"
19#include "api/mediaconstraintsinterface.h"
20#include "api/mediastreamproxy.h"
21#include "api/mediastreamtrackproxy.h"
22#include "call/call.h"
Elad Alon83ccca12017-10-04 13:18:26 +020023#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "logging/rtc_event_log/rtc_event_log.h"
25#include "media/sctp/sctptransport.h"
26#include "pc/audiotrack.h"
27#include "pc/channelmanager.h"
28#include "pc/dtmfsender.h"
29#include "pc/mediastream.h"
30#include "pc/mediastreamobserver.h"
31#include "pc/remoteaudiosource.h"
32#include "pc/rtpreceiver.h"
33#include "pc/rtpsender.h"
34#include "pc/streamcollection.h"
35#include "pc/videocapturertracksource.h"
36#include "pc/videotrack.h"
37#include "rtc_base/bind.h"
38#include "rtc_base/checks.h"
39#include "rtc_base/logging.h"
Elad Alon83ccca12017-10-04 13:18:26 +020040#include "rtc_base/ptr_util.h"
41#include "rtc_base/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/stringencode.h"
43#include "rtc_base/stringutils.h"
44#include "rtc_base/trace_event.h"
45#include "system_wrappers/include/clock.h"
46#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047
48namespace {
49
deadbeefab9b2d12015-10-14 11:33:11 -070050using webrtc::DataChannel;
51using webrtc::MediaConstraintsInterface;
52using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080054using webrtc::RTCError;
55using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070056using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080057using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070058using webrtc::RtpSenderProxy;
59using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070060using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061
deadbeefab9b2d12015-10-14 11:33:11 -070062static const char kDefaultStreamLabel[] = "default";
63static const char kDefaultAudioTrackLabel[] = "defaulta0";
64static const char kDefaultVideoTrackLabel[] = "defaultv0";
65
zhihuang8f65cdf2016-05-06 18:40:30 -070066// The length of RTCP CNAMEs.
67static const int kRtcpCnameLength = 16;
68
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000070 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070072 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080074 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075};
76
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000077struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078 explicit SetSessionDescriptionMsg(
79 webrtc::SetSessionDescriptionObserver* observer)
80 : observer(observer) {
81 }
82
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000083 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000084 std::string error;
85};
86
deadbeefab9b2d12015-10-14 11:33:11 -070087struct CreateSessionDescriptionMsg : public rtc::MessageData {
88 explicit CreateSessionDescriptionMsg(
89 webrtc::CreateSessionDescriptionObserver* observer)
90 : observer(observer) {}
91
92 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
93 std::string error;
94};
95
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000096struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000097 GetStatsMsg(webrtc::StatsObserver* observer,
98 webrtc::MediaStreamTrackInterface* track)
99 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000101 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000102 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103};
104
deadbeefab9b2d12015-10-14 11:33:11 -0700105// Check if we can send |new_stream| on a PeerConnection.
106bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
107 webrtc::MediaStreamInterface* new_stream) {
108 if (!new_stream || !current_streams) {
109 return false;
110 }
111 if (current_streams->find(new_stream->label()) != nullptr) {
112 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
113 << " is already added.";
114 return false;
115 }
116 return true;
117}
118
119bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
120 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
121}
122
deadbeef5e97fb52015-10-15 12:49:08 -0700123// If the direction is "recvonly" or "inactive", treat the description
124// as containing no streams.
125// See: https://code.google.com/p/webrtc/issues/detail?id=5054
126std::vector<cricket::StreamParams> GetActiveStreams(
127 const cricket::MediaContentDescription* desc) {
128 return MediaContentDirectionHasSend(desc->direction())
129 ? desc->streams()
130 : std::vector<cricket::StreamParams>();
131}
132
deadbeefab9b2d12015-10-14 11:33:11 -0700133bool IsValidOfferToReceiveMedia(int value) {
134 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
135 return (value >= Options::kUndefined) &&
136 (value <= Options::kMaxOfferToReceiveMedia);
137}
138
zhihuang1c378ed2017-08-17 14:10:50 -0700139// Add options to |[audio/video]_media_description_options| from |senders|.
140void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700141 const std::vector<rtc::scoped_refptr<
142 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700143 cricket::MediaDescriptionOptions* audio_media_description_options,
144 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700145 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700146 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
147 if (audio_media_description_options) {
148 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700149 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700150 }
151 } else {
152 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
153 if (video_media_description_options) {
154 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700155 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700156 }
157 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700158 }
zhihuang1c378ed2017-08-17 14:10:50 -0700159}
olka3c747662017-08-17 06:50:32 -0700160
zhihuang1c378ed2017-08-17 14:10:50 -0700161// Add options to |session_options| from |rtp_data_channels|.
162void AddRtpDataChannelOptions(
163 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
164 rtp_data_channels,
165 cricket::MediaDescriptionOptions* data_media_description_options) {
166 if (!data_media_description_options) {
167 return;
168 }
deadbeefab9b2d12015-10-14 11:33:11 -0700169 // Check for data channels.
170 for (const auto& kv : rtp_data_channels) {
171 const DataChannel* channel = kv.second;
172 if (channel->state() == DataChannel::kConnecting ||
173 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700174 // Legacy RTP data channels are signaled with the track/stream ID set to
175 // the data channel's label.
176 data_media_description_options->AddRtpDataChannel(channel->label(),
177 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700178 }
179 }
180}
181
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700182uint32_t ConvertIceTransportTypeToCandidateFilter(
183 PeerConnectionInterface::IceTransportsType type) {
184 switch (type) {
185 case PeerConnectionInterface::kNone:
186 return cricket::CF_NONE;
187 case PeerConnectionInterface::kRelay:
188 return cricket::CF_RELAY;
189 case PeerConnectionInterface::kNoHost:
190 return (cricket::CF_ALL & ~cricket::CF_HOST);
191 case PeerConnectionInterface::kAll:
192 return cricket::CF_ALL;
193 default:
nissec80e7412017-01-11 05:56:46 -0800194 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700195 }
196 return cricket::CF_NONE;
197}
198
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700199// Helper method to set a voice/video channel on all applicable senders
200// and receivers when one is created/destroyed by WebRtcSession.
201//
202// Used by On(Voice|Video)Channel(Created|Destroyed)
203template <class SENDER,
204 class RECEIVER,
205 class CHANNEL,
206 class SENDERS,
207 class RECEIVERS>
208void SetChannelOnSendersAndReceivers(CHANNEL* channel,
209 SENDERS& senders,
210 RECEIVERS& receivers,
211 cricket::MediaType media_type) {
212 for (auto& sender : senders) {
213 if (sender->media_type() == media_type) {
214 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
215 }
216 }
217 for (auto& receiver : receivers) {
218 if (receiver->media_type() == media_type) {
219 if (!channel) {
220 receiver->internal()->Stop();
221 }
222 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
223 }
224 }
225}
226
deadbeef293e9262017-01-11 12:28:30 -0800227// Helper to set an error and return from a method.
228bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
229 if (error) {
230 error->set_type(type);
231 }
232 return type == webrtc::RTCErrorType::NONE;
233}
234
Steve Anton038834f2017-07-14 15:59:59 -0700235bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
236 if (error_out) {
237 *error_out = std::move(error);
238 }
239 return error.ok();
240}
241
deadbeef0a6c4ca2015-10-06 11:38:28 -0700242} // namespace
243
244namespace webrtc {
245
deadbeef293e9262017-01-11 12:28:30 -0800246bool PeerConnectionInterface::RTCConfiguration::operator==(
247 const PeerConnectionInterface::RTCConfiguration& o) const {
248 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700249 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800250 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000251 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700252 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800253 BundlePolicy bundle_policy;
254 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700255 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
256 int ice_candidate_pool_size;
257 bool disable_ipv6;
258 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700259 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700260 bool enable_rtp_data_channel;
261 rtc::Optional<int> screencast_min_bitrate;
262 rtc::Optional<bool> combined_audio_video_bwe;
263 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800264 TcpCandidatePolicy tcp_candidate_policy;
265 CandidateNetworkPolicy candidate_network_policy;
266 int audio_jitter_buffer_max_packets;
267 bool audio_jitter_buffer_fast_accelerate;
268 int ice_connection_receiving_timeout;
269 int ice_backup_candidate_pair_ping_interval;
270 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800271 bool prioritize_most_likely_ice_candidate_pairs;
272 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800273 bool prune_turn_ports;
274 bool presume_writable_when_fully_relayed;
275 bool enable_ice_renomination;
276 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800277 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700278 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200279 webrtc::TurnCustomizer* turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800280 };
281 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
282 "Did you add something to RTCConfiguration and forget to "
283 "update operator==?");
284 return type == o.type && servers == o.servers &&
285 bundle_policy == o.bundle_policy &&
286 rtcp_mux_policy == o.rtcp_mux_policy &&
287 tcp_candidate_policy == o.tcp_candidate_policy &&
288 candidate_network_policy == o.candidate_network_policy &&
289 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
290 audio_jitter_buffer_fast_accelerate ==
291 o.audio_jitter_buffer_fast_accelerate &&
292 ice_connection_receiving_timeout ==
293 o.ice_connection_receiving_timeout &&
294 ice_backup_candidate_pair_ping_interval ==
295 o.ice_backup_candidate_pair_ping_interval &&
296 continual_gathering_policy == o.continual_gathering_policy &&
297 certificates == o.certificates &&
298 prioritize_most_likely_ice_candidate_pairs ==
299 o.prioritize_most_likely_ice_candidate_pairs &&
300 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800301 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700302 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800303 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800304 screencast_min_bitrate == o.screencast_min_bitrate &&
305 combined_audio_video_bwe == o.combined_audio_video_bwe &&
306 enable_dtls_srtp == o.enable_dtls_srtp &&
307 ice_candidate_pool_size == o.ice_candidate_pool_size &&
308 prune_turn_ports == o.prune_turn_ports &&
309 presume_writable_when_fully_relayed ==
310 o.presume_writable_when_fully_relayed &&
311 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800312 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700313 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200314 ice_regather_interval_range == o.ice_regather_interval_range &&
315 turn_customizer == o.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800316}
317
318bool PeerConnectionInterface::RTCConfiguration::operator!=(
319 const PeerConnectionInterface::RTCConfiguration& o) const {
320 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800321}
322
zhihuang8f65cdf2016-05-06 18:40:30 -0700323// Generate a RTCP CNAME when a PeerConnection is created.
324std::string GenerateRtcpCname() {
325 std::string cname;
326 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
327 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800328 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700329 }
330 return cname;
331}
332
zhihuang1c378ed2017-08-17 14:10:50 -0700333bool ValidateOfferAnswerOptions(
334 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
335 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
336 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700337}
338
zhihuang1c378ed2017-08-17 14:10:50 -0700339// From |rtc_options|, fill parts of |session_options| shared by all generated
340// m= sections (in other words, nothing that involves a map/array).
341void ExtractSharedMediaSessionOptions(
342 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
343 cricket::MediaSessionOptions* session_options) {
344 session_options->vad_enabled = rtc_options.voice_activity_detection;
345 session_options->bundle_enabled = rtc_options.use_rtp_mux;
346}
zhihuanga77e6bb2017-08-14 18:17:48 -0700347
zhihuang1c378ed2017-08-17 14:10:50 -0700348bool ConvertConstraintsToOfferAnswerOptions(
349 const MediaConstraintsInterface* constraints,
350 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700351 if (!constraints) {
352 return true;
353 }
zhihuang1c378ed2017-08-17 14:10:50 -0700354
355 bool value = false;
356 size_t mandatory_constraints_satisfied = 0;
357
358 if (FindConstraint(constraints,
359 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
360 &mandatory_constraints_satisfied)) {
361 offer_answer_options->offer_to_receive_audio =
362 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
363 kOfferToReceiveMediaTrue
364 : 0;
365 }
366
367 if (FindConstraint(constraints,
368 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
369 &mandatory_constraints_satisfied)) {
370 offer_answer_options->offer_to_receive_video =
371 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
372 kOfferToReceiveMediaTrue
373 : 0;
374 }
375 if (FindConstraint(constraints,
376 MediaConstraintsInterface::kVoiceActivityDetection, &value,
377 &mandatory_constraints_satisfied)) {
378 offer_answer_options->voice_activity_detection = value;
379 }
380 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
381 &mandatory_constraints_satisfied)) {
382 offer_answer_options->use_rtp_mux = value;
383 }
384 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
385 &value, &mandatory_constraints_satisfied)) {
386 offer_answer_options->ice_restart = value;
387 }
388
deadbeefab9b2d12015-10-14 11:33:11 -0700389 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
390}
391
zhihuang38ede132017-06-15 12:52:32 -0700392PeerConnection::PeerConnection(PeerConnectionFactory* factory,
393 std::unique_ptr<RtcEventLog> event_log,
394 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000395 : factory_(factory),
396 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000397 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700398 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000399 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700401 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700402 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700403 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700404 remote_streams_(StreamCollection::Create()),
405 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000406
407PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100408 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700409 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700410 // Need to detach RTP senders/receivers from WebRtcSession,
411 // since it's about to be destroyed.
412 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700413 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700414 }
415 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700416 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700417 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700418 // Destroy stats_ because it depends on session_.
419 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800420 if (stats_collector_) {
421 stats_collector_->WaitForPendingRequest();
422 stats_collector_ = nullptr;
423 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700424 // Now destroy session_ before destroying other members,
425 // because its destruction fires signals (such as VoiceChannelDestroyed)
426 // which will trigger some final actions in PeerConnection...
Steve Anton978b8762017-09-29 12:15:02 -0700427 owned_session_.reset(nullptr);
428 session_ = nullptr;
deadbeef91dd5672016-05-18 16:55:30 -0700429 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700430 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700431 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700432 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700433 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700434 call_.reset();
435 event_log_.reset();
436 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000437}
438
439bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000440 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700441 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200442 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800443 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100444 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700445
446 RTCError config_error = ValidateConfiguration(configuration);
447 if (!config_error.ok()) {
448 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
449 return false;
450 }
451
deadbeef293e9262017-01-11 12:28:30 -0800452 if (!allocator) {
453 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
454 << "This shouldn't happen if using PeerConnectionFactory.";
455 return false;
456 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200457
deadbeef653b8e02015-11-11 12:55:10 -0800458 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800459 // TODO(deadbeef): Why do we do this?
460 LOG(LS_ERROR) << "PeerConnection initialized without a "
461 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800462 return false;
463 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000464 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800465 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800466
deadbeef91dd5672016-05-18 16:55:30 -0700467 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700468 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700469 if (!network_thread()->Invoke<bool>(
470 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
471 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000472 return false;
473 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000474
Steve Anton978b8762017-09-29 12:15:02 -0700475 owned_session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700476 call_.get(), factory_->channel_manager(), configuration.media_config,
Steve Anton978b8762017-09-29 12:15:02 -0700477 event_log_.get(), network_thread(), worker_thread(), signaling_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700478 port_allocator_.get(),
479 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700480 factory_->CreateTransportController(
481 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800482 configuration.redetermine_role_on_ice_restart)),
Steve Antonda6c0952017-10-23 11:41:54 -0700483 factory_->CreateSctpTransportInternalFactory()));
Steve Anton978b8762017-09-29 12:15:02 -0700484 session_ = owned_session_.get();
zhihuang29ff8442016-07-27 11:07:25 -0700485
deadbeefab9b2d12015-10-14 11:33:11 -0700486 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700487 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000488
489 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200490 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800491 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000492 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700493 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000494
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495 // Register PeerConnection as receiver of local ice candidates.
496 // All the callbacks will be posted to the application from PeerConnection.
497 session_->RegisterIceObserver(this);
498 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700499 session_->SignalVoiceChannelCreated.connect(
500 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700501 session_->SignalVoiceChannelDestroyed.connect(
502 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700503 session_->SignalVideoChannelCreated.connect(
504 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700505 session_->SignalVideoChannelDestroyed.connect(
506 this, &PeerConnection::OnVideoChannelDestroyed);
507 session_->SignalDataChannelCreated.connect(
508 this, &PeerConnection::OnDataChannelCreated);
509 session_->SignalDataChannelDestroyed.connect(
510 this, &PeerConnection::OnDataChannelDestroyed);
511 session_->SignalDataChannelOpenMessage.connect(
512 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800513
514 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000515 return true;
516}
517
Steve Anton038834f2017-07-14 15:59:59 -0700518RTCError PeerConnection::ValidateConfiguration(
519 const RTCConfiguration& config) const {
520 if (config.ice_regather_interval_range &&
521 config.continual_gathering_policy == GATHER_ONCE) {
522 return RTCError(RTCErrorType::INVALID_PARAMETER,
523 "ice_regather_interval_range specified but continual "
524 "gathering policy is GATHER_ONCE");
525 }
526 return RTCError::OK();
527}
528
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000529rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000530PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700531 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000532}
533
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000534rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000535PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700536 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000537}
538
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000539bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100540 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000541 if (IsClosed()) {
542 return false;
543 }
deadbeefab9b2d12015-10-14 11:33:11 -0700544 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000545 return false;
546 }
deadbeefab9b2d12015-10-14 11:33:11 -0700547
548 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800549 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
550 observer->SignalAudioTrackAdded.connect(this,
551 &PeerConnection::OnAudioTrackAdded);
552 observer->SignalAudioTrackRemoved.connect(
553 this, &PeerConnection::OnAudioTrackRemoved);
554 observer->SignalVideoTrackAdded.connect(this,
555 &PeerConnection::OnVideoTrackAdded);
556 observer->SignalVideoTrackRemoved.connect(
557 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700558 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700559
deadbeefab9b2d12015-10-14 11:33:11 -0700560 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700561 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700562 }
563 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700564 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700565 }
566
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000567 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568 observer_->OnRenegotiationNeeded();
569 return true;
570}
571
572void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100573 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700574 if (!IsClosed()) {
575 for (const auto& track : local_stream->GetAudioTracks()) {
576 RemoveAudioTrack(track.get(), local_stream);
577 }
578 for (const auto& track : local_stream->GetVideoTracks()) {
579 RemoveVideoTrack(track.get(), local_stream);
580 }
deadbeefab9b2d12015-10-14 11:33:11 -0700581 }
deadbeefab9b2d12015-10-14 11:33:11 -0700582 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800583 stream_observers_.erase(
584 std::remove_if(
585 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700586 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800587 return observer->stream()->label().compare(local_stream->label()) ==
588 0;
589 }),
590 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700591
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592 if (IsClosed()) {
593 return;
594 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595 observer_->OnRenegotiationNeeded();
596}
597
deadbeefe1f9d832016-01-14 15:35:42 -0800598rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
599 MediaStreamTrackInterface* track,
600 std::vector<MediaStreamInterface*> streams) {
601 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
602 if (IsClosed()) {
603 return nullptr;
604 }
605 if (streams.size() >= 2) {
606 LOG(LS_ERROR)
607 << "Adding a track with two streams is not currently supported.";
608 return nullptr;
609 }
610 // TODO(deadbeef): Support adding a track to two different senders.
611 if (FindSenderForTrack(track) != senders_.end()) {
612 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
613 return nullptr;
614 }
615
616 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700617 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800618 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700619 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800620 signaling_thread(),
621 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700622 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800623 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700624 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800625 }
626 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700627 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800628 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700629 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800630 }
631 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700632 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800633 signaling_thread(),
634 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700635 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800636 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700637 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800638 }
639 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700640 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800641 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700642 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800643 }
644 } else {
645 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
646 return rtc::scoped_refptr<RtpSenderInterface>();
647 }
648
649 senders_.push_back(new_sender);
650 observer_->OnRenegotiationNeeded();
651 return new_sender;
652}
653
654bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
655 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
656 if (IsClosed()) {
657 return false;
658 }
659
660 auto it = std::find(senders_.begin(), senders_.end(), sender);
661 if (it == senders_.end()) {
662 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
663 return false;
664 }
deadbeefa601f5c2016-06-06 14:27:39 -0700665 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800666 senders_.erase(it);
667
668 observer_->OnRenegotiationNeeded();
669 return true;
670}
671
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000672rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100674 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700675 if (IsClosed()) {
676 return nullptr;
677 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678 if (!track) {
679 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800680 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 }
deadbeef20cb0c12017-02-01 20:27:00 -0800682 auto it = FindSenderForTrack(track);
683 if (it == senders_.end()) {
684 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
685 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000686 }
687
deadbeef20cb0c12017-02-01 20:27:00 -0800688 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689}
690
deadbeeffac06552015-11-25 11:26:01 -0800691rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800692 const std::string& kind,
693 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100694 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700695 if (IsClosed()) {
696 return nullptr;
697 }
deadbeefa601f5c2016-06-06 14:27:39 -0700698 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800699 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700700 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700701 signaling_thread(),
702 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800703 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700704 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700705 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800706 } else {
707 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800708 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800709 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800710 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700711 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800712 }
deadbeeffac06552015-11-25 11:26:01 -0800713 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800714 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800715}
716
deadbeef70ab1a12015-09-28 16:53:55 -0700717std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
718 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700719 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
720 for (const auto& sender : senders_) {
721 ret.push_back(sender.get());
722 }
723 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700724}
725
726std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
727PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700728 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
729 for (const auto& receiver : receivers_) {
730 ret.push_back(receiver.get());
731 }
732 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700733}
734
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000736 MediaStreamTrackInterface* track,
737 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100738 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700739 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800740 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 LOG(LS_ERROR) << "GetStats - observer is NULL.";
742 return false;
743 }
744
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000745 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700746 // The StatsCollector is used to tell if a track is valid because it may
747 // remember tracks that the PeerConnection previously removed.
748 if (track && !stats_->IsValidTrack(track->id())) {
749 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
750 << track->id();
751 return false;
752 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700753 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000754 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000755 return true;
756}
757
hbos74e1a4f2016-09-15 23:33:01 -0700758void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
759 RTC_DCHECK(stats_collector_);
760 stats_collector_->GetStatsReport(callback);
761}
762
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
764 return signaling_state_;
765}
766
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000767PeerConnectionInterface::IceConnectionState
768PeerConnection::ice_connection_state() {
769 return ice_connection_state_;
770}
771
772PeerConnectionInterface::IceGatheringState
773PeerConnection::ice_gathering_state() {
774 return ice_gathering_state_;
775}
776
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000777rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778PeerConnection::CreateDataChannel(
779 const std::string& label,
780 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100781 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700782
deadbeefab9b2d12015-10-14 11:33:11 -0700783 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000784
kwibergd1fe2812016-04-27 06:47:29 -0700785 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000786 if (config) {
787 internal_config.reset(new InternalDataChannelInit(*config));
788 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000789 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700790 InternalCreateDataChannel(label, internal_config.get()));
791 if (!channel.get()) {
792 return nullptr;
793 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000795 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
796 // the first SCTP DataChannel.
797 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
798 observer_->OnRenegotiationNeeded();
799 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000800
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801 return DataChannelProxy::Create(signaling_thread(), channel.get());
802}
803
804void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
805 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100806 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -0700807
zhihuang1c378ed2017-08-17 14:10:50 -0700808 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
809 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
810 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
811 // compares the mandatory fields parsed with the mandatory fields added in the
812 // |constraints| and some downstream applications might create offers with
813 // mandatory fields which would not be parsed in the helper method. For
814 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
815 // |constraints| as a mandatory field but it is not parsed.
816 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000817
zhihuang1c378ed2017-08-17 14:10:50 -0700818 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000819}
820
821void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
822 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100823 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -0700824
nisse7ce109a2017-01-31 00:57:56 -0800825 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000826 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
827 return;
828 }
deadbeefab9b2d12015-10-14 11:33:11 -0700829
Steve Anton8d3444d2017-10-20 15:30:51 -0700830 if (IsClosed()) {
831 std::string error = "CreateOffer called when PeerConnection is closed.";
832 LOG(LS_ERROR) << error;
833 PostCreateSessionDescriptionFailure(observer, error);
834 return;
835 }
836
zhihuang1c378ed2017-08-17 14:10:50 -0700837 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700838 std::string error = "CreateOffer called with invalid options.";
839 LOG(LS_ERROR) << error;
840 PostCreateSessionDescriptionFailure(observer, error);
841 return;
842 }
843
zhihuang1c378ed2017-08-17 14:10:50 -0700844 cricket::MediaSessionOptions session_options;
845 GetOptionsForOffer(options, &session_options);
deadbeefab9b2d12015-10-14 11:33:11 -0700846 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847}
848
849void PeerConnection::CreateAnswer(
850 CreateSessionDescriptionObserver* observer,
851 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100852 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -0700853
nisse7ce109a2017-01-31 00:57:56 -0800854 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
856 return;
857 }
deadbeefab9b2d12015-10-14 11:33:11 -0700858
zhihuang1c378ed2017-08-17 14:10:50 -0700859 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
860 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
861 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700862 std::string error = "CreateAnswer called with invalid constraints.";
863 LOG(LS_ERROR) << error;
864 PostCreateSessionDescriptionFailure(observer, error);
865 return;
866 }
867
Steve Anton8d3444d2017-10-20 15:30:51 -0700868 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -0800869}
870
871void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
872 const RTCOfferAnswerOptions& options) {
873 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800874 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800875 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
876 return;
877 }
878
Steve Anton8d3444d2017-10-20 15:30:51 -0700879 if (IsClosed()) {
880 std::string error = "CreateAnswer called when PeerConnection is closed.";
881 LOG(LS_ERROR) << error;
882 PostCreateSessionDescriptionFailure(observer, error);
883 return;
884 }
885
886 if (session_->remote_description() &&
887 session_->remote_description()->type() !=
888 SessionDescriptionInterface::kOffer) {
889 std::string error = "CreateAnswer called without remote offer.";
890 LOG(LS_ERROR) << error;
891 PostCreateSessionDescriptionFailure(observer, error);
892 return;
893 }
894
htaa2a49d92016-03-04 02:51:39 -0800895 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -0700896 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800897
898 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899}
900
901void PeerConnection::SetLocalDescription(
902 SetSessionDescriptionObserver* observer,
903 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100904 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -0800905 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
907 return;
908 }
909 if (!desc) {
910 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
911 return;
912 }
Steve Anton8d3444d2017-10-20 15:30:51 -0700913
914 // Takes the ownership of |desc| regardless of the result.
915 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
916
917 if (IsClosed()) {
918 std::string error = "Failed to set local " + desc->type() +
919 " sdp: Called in wrong state: STATE_CLOSED";
920 LOG(LS_ERROR) << error;
921 PostSetSessionDescriptionFailure(observer, error);
922 return;
923 }
924
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 // Update stats here so that we have the most recent stats for tracks and
926 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000927 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928 std::string error;
Steve Anton8d3444d2017-10-20 15:30:51 -0700929 if (!session_->SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 PostSetSessionDescriptionFailure(observer, error);
931 return;
932 }
deadbeefab9b2d12015-10-14 11:33:11 -0700933
934 // If setting the description decided our SSL role, allocate any necessary
935 // SCTP sids.
936 rtc::SSLRole role;
937 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800938 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700939 AllocateSctpSids(role);
940 }
941
942 // Update state and SSRC of local MediaStreams and DataChannels based on the
943 // local session description.
944 const cricket::ContentInfo* audio_content =
945 GetFirstAudioContent(desc->description());
946 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800947 if (audio_content->rejected) {
948 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
949 } else {
950 const cricket::AudioContentDescription* audio_desc =
951 static_cast<const cricket::AudioContentDescription*>(
952 audio_content->description);
953 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
954 }
deadbeefab9b2d12015-10-14 11:33:11 -0700955 }
956
957 const cricket::ContentInfo* video_content =
958 GetFirstVideoContent(desc->description());
959 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800960 if (video_content->rejected) {
961 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
962 } else {
963 const cricket::VideoContentDescription* video_desc =
964 static_cast<const cricket::VideoContentDescription*>(
965 video_content->description);
966 UpdateLocalTracks(video_desc->streams(), video_desc->type());
967 }
deadbeefab9b2d12015-10-14 11:33:11 -0700968 }
969
970 const cricket::ContentInfo* data_content =
971 GetFirstDataContent(desc->description());
972 if (data_content) {
973 const cricket::DataContentDescription* data_desc =
974 static_cast<const cricket::DataContentDescription*>(
975 data_content->description);
976 if (rtc::starts_with(data_desc->protocol().data(),
977 cricket::kMediaProtocolRtpPrefix)) {
978 UpdateLocalRtpDataChannels(data_desc->streams());
979 }
980 }
981
982 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700983 signaling_thread()->Post(RTC_FROM_HERE, this,
984 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700985
deadbeef42a42632017-03-10 15:18:00 -0800986 // According to JSEP, after setLocalDescription, changing the candidate pool
987 // size is not allowed, and changing the set of ICE servers will not result
988 // in new candidates being gathered.
989 port_allocator_->FreezeCandidatePool();
990
deadbeefcbecd352015-09-23 11:50:27 -0700991 // MaybeStartGathering needs to be called after posting
992 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
993 // before signaling that SetLocalDescription completed.
994 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -0800995
996 if (desc->type() == SessionDescriptionInterface::kAnswer) {
997 // TODO(deadbeef): We already had to hop to the network thread for
998 // MaybeStartGathering...
999 network_thread()->Invoke<void>(
1000 RTC_FROM_HERE,
1001 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1002 port_allocator_.get()));
1003 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001004}
1005
1006void PeerConnection::SetRemoteDescription(
1007 SetSessionDescriptionObserver* observer,
1008 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001009 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001010 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1012 return;
1013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014 if (!desc) {
1015 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1016 return;
1017 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001018
1019 // Takes the ownership of |desc| regardless of the result.
1020 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1021
1022 if (IsClosed()) {
1023 std::string error = "Failed to set remote " + desc->type() +
1024 " sdp: Called in wrong state: STATE_CLOSED";
1025 LOG(LS_ERROR) << error;
1026 PostSetSessionDescriptionFailure(observer, error);
1027 return;
1028 }
1029
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 // Update stats here so that we have the most recent stats for tracks and
1031 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001032 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033 std::string error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001034 if (!session_->SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035 PostSetSessionDescriptionFailure(observer, error);
1036 return;
1037 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038
deadbeefab9b2d12015-10-14 11:33:11 -07001039 // If setting the description decided our SSL role, allocate any necessary
1040 // SCTP sids.
1041 rtc::SSLRole role;
1042 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001043 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001044 AllocateSctpSids(role);
1045 }
1046
1047 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001048 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1049 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1050 const cricket::AudioContentDescription* audio_desc =
1051 GetFirstAudioContentDescription(remote_desc);
1052 const cricket::VideoContentDescription* video_desc =
1053 GetFirstVideoContentDescription(remote_desc);
1054 const cricket::DataContentDescription* data_desc =
1055 GetFirstDataContentDescription(remote_desc);
1056
1057 // Check if the descriptions include streams, just in case the peer supports
1058 // MSID, but doesn't indicate so with "a=msid-semantic".
1059 if (remote_desc->msid_supported() ||
1060 (audio_desc && !audio_desc->streams().empty()) ||
1061 (video_desc && !video_desc->streams().empty())) {
1062 remote_peer_supports_msid_ = true;
1063 }
deadbeefab9b2d12015-10-14 11:33:11 -07001064
1065 // We wait to signal new streams until we finish processing the description,
1066 // since only at that point will new streams have all their tracks.
1067 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1068
Steve Anton8d3444d2017-10-20 15:30:51 -07001069 // TODO(steveanton): When removing RTP senders/receivers in response to a
1070 // rejected media section, there is some cleanup logic that expects the voice/
1071 // video channel to still be set. But in this method the voice/video channel
1072 // would have been destroyed by WebRtcSession's SetRemoteDescription method
1073 // above, so the cleanup that relies on them fails to run. This is hard to fix
1074 // with WebRtcSession and PeerConnection separated, but once the classes are
1075 // merged it will be easy to call RemoveTracks right before destroying the
1076 // voice/video channels.
1077
deadbeefab9b2d12015-10-14 11:33:11 -07001078 // Find all audio rtp streams and create corresponding remote AudioTracks
1079 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001080 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001081 if (audio_content->rejected) {
1082 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1083 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001084 bool default_audio_track_needed =
1085 !remote_peer_supports_msid_ &&
1086 MediaContentDirectionHasSend(audio_desc->direction());
1087 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1088 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001089 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001090 }
deadbeefab9b2d12015-10-14 11:33:11 -07001091 }
1092
1093 // Find all video rtp streams and create corresponding remote VideoTracks
1094 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001095 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001096 if (video_content->rejected) {
1097 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1098 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001099 bool default_video_track_needed =
1100 !remote_peer_supports_msid_ &&
1101 MediaContentDirectionHasSend(video_desc->direction());
1102 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1103 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001104 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001105 }
deadbeefab9b2d12015-10-14 11:33:11 -07001106 }
1107
1108 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001109 if (data_desc) {
1110 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001111 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001112 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001113 }
1114 }
1115
1116 // Iterate new_streams and notify the observer about new MediaStreams.
1117 for (size_t i = 0; i < new_streams->count(); ++i) {
1118 MediaStreamInterface* new_stream = new_streams->at(i);
1119 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001120 observer_->OnAddStream(
1121 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001122 }
1123
deadbeefbda7e0b2015-12-08 17:13:40 -08001124 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001125
1126 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001127 signaling_thread()->Post(RTC_FROM_HERE, this,
1128 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001129
1130 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1131 // TODO(deadbeef): We already had to hop to the network thread for
1132 // MaybeStartGathering...
1133 network_thread()->Invoke<void>(
1134 RTC_FROM_HERE,
1135 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1136 port_allocator_.get()));
1137 }
deadbeeffc648b62015-10-13 16:42:33 -07001138}
1139
deadbeef46c73892016-11-16 19:42:04 -08001140PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1141 return configuration_;
1142}
1143
deadbeef293e9262017-01-11 12:28:30 -08001144bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1145 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001146 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001147
1148 if (session_->local_description() &&
1149 configuration.ice_candidate_pool_size !=
1150 configuration_.ice_candidate_pool_size) {
1151 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1152 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001153 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001154 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001155
deadbeef293e9262017-01-11 12:28:30 -08001156 // The simplest (and most future-compatible) way to tell if the config was
1157 // modified in an invalid way is to copy each property we do support
1158 // modifying, then use operator==. There are far more properties we don't
1159 // support modifying than those we do, and more could be added.
1160 RTCConfiguration modified_config = configuration_;
1161 modified_config.servers = configuration.servers;
1162 modified_config.type = configuration.type;
1163 modified_config.ice_candidate_pool_size =
1164 configuration.ice_candidate_pool_size;
1165 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001166 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001167 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001168 if (configuration != modified_config) {
1169 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1170 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1171 }
1172
Steve Anton038834f2017-07-14 15:59:59 -07001173 // Validate the modified configuration.
1174 RTCError validate_error = ValidateConfiguration(modified_config);
1175 if (!validate_error.ok()) {
1176 return SafeSetError(std::move(validate_error), error);
1177 }
1178
deadbeef293e9262017-01-11 12:28:30 -08001179 // Note that this isn't possible through chromium, since it's an unsigned
1180 // short in WebIDL.
1181 if (configuration.ice_candidate_pool_size < 0 ||
1182 configuration.ice_candidate_pool_size > UINT16_MAX) {
1183 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1184 }
1185
1186 // Parse ICE servers before hopping to network thread.
1187 cricket::ServerAddresses stun_servers;
1188 std::vector<cricket::RelayServerConfig> turn_servers;
1189 RTCErrorType parse_error =
1190 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1191 if (parse_error != RTCErrorType::NONE) {
1192 return SafeSetError(parse_error, error);
1193 }
1194
1195 // In theory this shouldn't fail.
1196 if (!network_thread()->Invoke<bool>(
1197 RTC_FROM_HERE,
1198 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1199 stun_servers, turn_servers, modified_config.type,
1200 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001201 modified_config.prune_turn_ports,
1202 modified_config.turn_customizer))) {
deadbeef293e9262017-01-11 12:28:30 -08001203 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1204 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1205 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001206
deadbeefd1a38b52016-12-10 13:15:33 -08001207 // As described in JSEP, calling setConfiguration with new ICE servers or
1208 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1209 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001210 if (modified_config.servers != configuration_.servers ||
1211 modified_config.type != configuration_.type ||
1212 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001213 session_->SetNeedsIceRestartFlag();
1214 }
skvladd1f5fda2017-02-03 16:54:05 -08001215
1216 if (modified_config.ice_check_min_interval !=
1217 configuration_.ice_check_min_interval) {
1218 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1219 }
1220
deadbeef293e9262017-01-11 12:28:30 -08001221 configuration_ = modified_config;
1222 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001223}
1224
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001225bool PeerConnection::AddIceCandidate(
1226 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001227 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001228 if (IsClosed()) {
1229 return false;
1230 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 return session_->ProcessIceMessage(ice_candidate);
1232}
1233
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001234bool PeerConnection::RemoveIceCandidates(
1235 const std::vector<cricket::Candidate>& candidates) {
1236 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1237 return session_->RemoveRemoteIceCandidates(candidates);
1238}
1239
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001240void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001241 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001242 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001243
1244 if (session_) {
1245 session_->set_metrics_observer(uma_observer_);
1246 }
1247
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001248 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001249 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001250 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001251 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001252 uma_observer_->IncrementEnumCounter(
1253 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1254 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001255 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001256 uma_observer_->IncrementEnumCounter(
1257 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1258 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001259 }
1260 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001261}
1262
zstein4b979802017-06-02 14:37:37 -07001263RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001264 if (!worker_thread()->IsCurrent()) {
1265 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001266 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1267 }
1268
1269 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1270 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1271 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1272 if (has_min && *bitrate.min_bitrate_bps < 0) {
1273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1274 "min_bitrate_bps <= 0");
1275 }
1276 if (has_current) {
1277 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1278 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1279 "current_bitrate_bps < min_bitrate_bps");
1280 } else if (*bitrate.current_bitrate_bps < 0) {
1281 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1282 "curent_bitrate_bps < 0");
1283 }
1284 }
1285 if (has_max) {
1286 if (has_current &&
1287 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1288 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1289 "max_bitrate_bps < current_bitrate_bps");
1290 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1291 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1292 "max_bitrate_bps < min_bitrate_bps");
1293 } else if (*bitrate.max_bitrate_bps < 0) {
1294 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1295 "max_bitrate_bps < 0");
1296 }
1297 }
1298
1299 Call::Config::BitrateConfigMask mask;
1300 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1301 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1302 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1303
1304 RTC_DCHECK(call_.get());
1305 call_->SetBitrateConfigMask(mask);
1306
1307 return RTCError::OK();
1308}
1309
Alex Narest78609d52017-10-20 10:37:47 +02001310void PeerConnection::SetBitrateAllocationStrategy(
1311 std::unique_ptr<rtc::BitrateAllocationStrategy>
1312 bitrate_allocation_strategy) {
1313 rtc::Thread* worker_thread = factory_->worker_thread();
1314 if (!worker_thread->IsCurrent()) {
1315 rtc::BitrateAllocationStrategy* strategy_raw =
1316 bitrate_allocation_strategy.release();
1317 auto functor = [this, strategy_raw]() {
1318 call_->SetBitrateAllocationStrategy(
1319 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1320 };
1321 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
1322 return;
1323 }
1324 RTC_DCHECK(call_.get());
1325 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
1326}
1327
Steve Anton8c0f7a72017-10-03 10:03:10 -07001328std::unique_ptr<rtc::SSLCertificate>
1329PeerConnection::GetRemoteAudioSSLCertificate() {
1330 if (!session_) {
1331 return nullptr;
1332 }
1333 auto* voice_channel = session_->voice_channel();
1334 if (!voice_channel) {
1335 return nullptr;
1336 }
1337 return GetRemoteSSLCertificate(voice_channel->transport_name());
1338}
1339
ivoc14d5dbe2016-07-04 07:06:55 -07001340bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1341 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001342 // TODO(eladalon): It would be better to not allow negative values into PC.
1343 const size_t max_size = (max_size_bytes < 0)
1344 ? RtcEventLog::kUnlimitedOutput
1345 : rtc::saturated_cast<size_t>(max_size_bytes);
1346 return StartRtcEventLog(
1347 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
1348}
1349
1350bool PeerConnection::StartRtcEventLog(
1351 std::unique_ptr<RtcEventLogOutput> output) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001352 // TODO(eladalon): In C++14, this can be done with a lambda.
1353 struct Functor {
1354 bool operator()() { return pc->StartRtcEventLog_w(std::move(output)); }
1355 PeerConnection* const pc;
1356 std::unique_ptr<RtcEventLogOutput> output;
Elad Alon99c3fe52017-10-13 16:29:40 +02001357 };
Karl Wibergd6b48192017-10-16 23:01:06 +02001358 return worker_thread()->Invoke<bool>(RTC_FROM_HERE,
1359 Functor{this, std::move(output)});
ivoc14d5dbe2016-07-04 07:06:55 -07001360}
1361
1362void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001363 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001364 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1365}
1366
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367const SessionDescriptionInterface* PeerConnection::local_description() const {
1368 return session_->local_description();
1369}
1370
1371const SessionDescriptionInterface* PeerConnection::remote_description() const {
1372 return session_->remote_description();
1373}
1374
deadbeeffe4a8a42016-12-20 17:56:17 -08001375const SessionDescriptionInterface* PeerConnection::current_local_description()
1376 const {
1377 return session_->current_local_description();
1378}
1379
1380const SessionDescriptionInterface* PeerConnection::current_remote_description()
1381 const {
1382 return session_->current_remote_description();
1383}
1384
1385const SessionDescriptionInterface* PeerConnection::pending_local_description()
1386 const {
1387 return session_->pending_local_description();
1388}
1389
1390const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1391 const {
1392 return session_->pending_remote_description();
1393}
1394
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001396 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001397 // Update stats here so that we have the most recent stats for tracks and
1398 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001399 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400
deadbeefd59daf82015-10-14 15:02:44 -07001401 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001402 network_thread()->Invoke<void>(
1403 RTC_FROM_HERE,
1404 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1405 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001406
Steve Anton978b8762017-09-29 12:15:02 -07001407 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001408 call_.reset();
1409 // The event log must outlive call (and any other object that uses it).
1410 event_log_.reset();
1411 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412}
1413
deadbeefd59daf82015-10-14 15:02:44 -07001414void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1415 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001417 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001418 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001419 break;
deadbeefd59daf82015-10-14 15:02:44 -07001420 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001421 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1422 break;
deadbeefd59daf82015-10-14 15:02:44 -07001423 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001424 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1425 break;
deadbeefd59daf82015-10-14 15:02:44 -07001426 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1428 break;
deadbeefd59daf82015-10-14 15:02:44 -07001429 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1431 break;
deadbeefd59daf82015-10-14 15:02:44 -07001432 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 ChangeSignalingState(PeerConnectionInterface::kStable);
1434 break;
deadbeefd59daf82015-10-14 15:02:44 -07001435 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436 ChangeSignalingState(PeerConnectionInterface::kClosed);
1437 break;
1438 default:
1439 break;
1440 }
1441}
1442
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001443void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1446 SetSessionDescriptionMsg* param =
1447 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1448 param->observer->OnSuccess();
1449 delete param;
1450 break;
1451 }
1452 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1453 SetSessionDescriptionMsg* param =
1454 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1455 param->observer->OnFailure(param->error);
1456 delete param;
1457 break;
1458 }
deadbeefab9b2d12015-10-14 11:33:11 -07001459 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1460 CreateSessionDescriptionMsg* param =
1461 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1462 param->observer->OnFailure(param->error);
1463 delete param;
1464 break;
1465 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466 case MSG_GETSTATS: {
1467 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001468 StatsReports reports;
1469 stats_->GetStats(param->track, &reports);
1470 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 delete param;
1472 break;
1473 }
deadbeefbd292462015-12-14 18:15:29 -08001474 case MSG_FREE_DATACHANNELS: {
1475 sctp_data_channels_to_free_.clear();
1476 break;
1477 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001479 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 break;
1481 }
1482}
1483
deadbeefab9b2d12015-10-14 11:33:11 -07001484void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001485 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001486 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001487 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1488 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001489 signaling_thread(),
1490 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1491 stream->AddTrack(
1492 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001493 receivers_.push_back(receiver);
1494 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1495 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1496 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497}
1498
deadbeefab9b2d12015-10-14 11:33:11 -07001499void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001500 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001501 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001502 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1503 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001504 signaling_thread(),
Steve Anton978b8762017-09-29 12:15:02 -07001505 new VideoRtpReceiver(track_id, worker_thread(), ssrc,
deadbeefe814a0d2017-02-25 18:15:09 -08001506 session_->video_channel()));
1507 stream->AddTrack(
1508 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001509 receivers_.push_back(receiver);
1510 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1511 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1512 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001513}
1514
deadbeef70ab1a12015-09-28 16:53:55 -07001515// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1516// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07001517rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
1518 const std::string& track_id) {
perkjd61bf802016-03-24 03:16:19 -07001519 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001520 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001521 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001522 << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07001523 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07001524 }
Henrik Boström933d8b02017-10-10 10:05:16 -07001525 (*it)->internal()->Stop();
1526 rtc::scoped_refptr<RtpReceiverInterface> receiver = *it;
1527 receivers_.erase(it);
1528 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001529}
1530
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001531void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1532 MediaStreamInterface* stream) {
1533 RTC_DCHECK(!IsClosed());
1534 auto sender = FindSenderForTrack(track);
1535 if (sender != senders_.end()) {
1536 // We already have a sender for this track, so just change the stream_id
1537 // so that it's correct in the next call to CreateOffer.
1538 (*sender)->internal()->set_stream_id(stream->label());
1539 return;
1540 }
1541
1542 // Normal case; we've never seen this track before.
1543 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1544 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1545 signaling_thread(),
Steve Anton8ffb9c32017-08-31 15:45:38 -07001546 new AudioRtpSender(track, {stream->label()},
1547 session_->voice_channel(), stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001548 senders_.push_back(new_sender);
1549 // If the sender has already been configured in SDP, we call SetSsrc,
1550 // which will connect the sender to the underlying transport. This can
1551 // occur if a local session description that contains the ID of the sender
1552 // is set before AddStream is called. It can also occur if the local
1553 // session description is not changed and RemoveStream is called, and
1554 // later AddStream is called again with the same stream.
1555 const TrackInfo* track_info =
1556 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1557 if (track_info) {
1558 new_sender->internal()->SetSsrc(track_info->ssrc);
1559 }
1560}
1561
1562// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1563// indefinitely, when we have unified plan SDP.
1564void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1565 MediaStreamInterface* stream) {
1566 RTC_DCHECK(!IsClosed());
1567 auto sender = FindSenderForTrack(track);
1568 if (sender == senders_.end()) {
1569 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1570 << " doesn't exist.";
1571 return;
1572 }
1573 (*sender)->internal()->Stop();
1574 senders_.erase(sender);
1575}
1576
1577void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1578 MediaStreamInterface* stream) {
1579 RTC_DCHECK(!IsClosed());
1580 auto sender = FindSenderForTrack(track);
1581 if (sender != senders_.end()) {
1582 // We already have a sender for this track, so just change the stream_id
1583 // so that it's correct in the next call to CreateOffer.
1584 (*sender)->internal()->set_stream_id(stream->label());
1585 return;
1586 }
1587
1588 // Normal case; we've never seen this track before.
1589 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1590 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton8ffb9c32017-08-31 15:45:38 -07001591 signaling_thread(), new VideoRtpSender(track, {stream->label()},
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001592 session_->video_channel()));
1593 senders_.push_back(new_sender);
1594 const TrackInfo* track_info =
1595 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1596 if (track_info) {
1597 new_sender->internal()->SetSsrc(track_info->ssrc);
1598 }
1599}
1600
1601void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1602 MediaStreamInterface* stream) {
1603 RTC_DCHECK(!IsClosed());
1604 auto sender = FindSenderForTrack(track);
1605 if (sender == senders_.end()) {
1606 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1607 << " doesn't exist.";
1608 return;
1609 }
1610 (*sender)->internal()->Stop();
1611 senders_.erase(sender);
1612}
1613
zstein6dfd53a2017-03-06 13:49:03 -08001614void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001615 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001616 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001617 // After transitioning to "closed", ignore any additional states from
1618 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001619 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001620 return;
1621 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001622 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001623 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001624}
1625
1626void PeerConnection::OnIceGatheringChange(
1627 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001628 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001629 if (IsClosed()) {
1630 return;
1631 }
1632 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001633 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634}
1635
jbauch81bf7b02017-03-25 08:31:12 -07001636void PeerConnection::OnIceCandidate(
1637 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001638 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001639 if (IsClosed()) {
1640 return;
1641 }
jbauch81bf7b02017-03-25 08:31:12 -07001642 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001643}
1644
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001645void PeerConnection::OnIceCandidatesRemoved(
1646 const std::vector<cricket::Candidate>& candidates) {
1647 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001648 if (IsClosed()) {
1649 return;
1650 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001651 observer_->OnIceCandidatesRemoved(candidates);
1652}
1653
Peter Thatcher54360512015-07-08 11:08:35 -07001654void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001655 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001656 if (IsClosed()) {
1657 return;
1658 }
Peter Thatcher54360512015-07-08 11:08:35 -07001659 observer_->OnIceConnectionReceivingChange(receiving);
1660}
1661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001662void PeerConnection::ChangeSignalingState(
1663 PeerConnectionInterface::SignalingState signaling_state) {
1664 signaling_state_ = signaling_state;
1665 if (signaling_state == kClosed) {
1666 ice_connection_state_ = kIceConnectionClosed;
1667 observer_->OnIceConnectionChange(ice_connection_state_);
1668 if (ice_gathering_state_ != kIceGatheringComplete) {
1669 ice_gathering_state_ = kIceGatheringComplete;
1670 observer_->OnIceGatheringChange(ice_gathering_state_);
1671 }
1672 }
1673 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674}
1675
deadbeefeb459812015-12-15 19:24:43 -08001676void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1677 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001678 if (IsClosed()) {
1679 return;
1680 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001681 AddAudioTrack(track, stream);
1682 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001683}
1684
deadbeefeb459812015-12-15 19:24:43 -08001685void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1686 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001687 if (IsClosed()) {
1688 return;
1689 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001690 RemoveAudioTrack(track, stream);
1691 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001692}
1693
1694void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1695 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001696 if (IsClosed()) {
1697 return;
1698 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001699 AddVideoTrack(track, stream);
1700 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001701}
1702
1703void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1704 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001705 if (IsClosed()) {
1706 return;
1707 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001708 RemoveVideoTrack(track, stream);
1709 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001710}
1711
deadbeefab9b2d12015-10-14 11:33:11 -07001712void PeerConnection::PostSetSessionDescriptionFailure(
1713 SetSessionDescriptionObserver* observer,
1714 const std::string& error) {
1715 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1716 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001717 signaling_thread()->Post(RTC_FROM_HERE, this,
1718 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001719}
1720
1721void PeerConnection::PostCreateSessionDescriptionFailure(
1722 CreateSessionDescriptionObserver* observer,
1723 const std::string& error) {
1724 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1725 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001726 signaling_thread()->Post(RTC_FROM_HERE, this,
1727 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001728}
1729
zhihuang1c378ed2017-08-17 14:10:50 -07001730void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001731 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1732 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001733 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1734
1735 // Figure out transceiver directional preferences.
1736 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1737 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1738
1739 // By default, generate sendrecv/recvonly m= sections.
1740 bool recv_audio = true;
1741 bool recv_video = true;
1742
1743 // By default, only offer a new m= section if we have media to send with it.
1744 bool offer_new_audio_description = send_audio;
1745 bool offer_new_video_description = send_video;
1746 bool offer_new_data_description = HasDataChannels();
1747
1748 // The "offer_to_receive_X" options allow those defaults to be overridden.
1749 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1750 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1751 offer_new_audio_description =
1752 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1753 }
1754 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1755 recv_video = (rtc_options.offer_to_receive_video > 0);
1756 offer_new_video_description =
1757 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1758 }
1759
1760 rtc::Optional<size_t> audio_index;
1761 rtc::Optional<size_t> video_index;
1762 rtc::Optional<size_t> data_index;
1763 // If a current description exists, generate m= sections in the same order,
1764 // using the first audio/video/data section that appears and rejecting
1765 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001766 if (session_->local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07001767 GenerateMediaDescriptionOptions(
1768 session_->local_description(),
1769 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1770 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1771 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001772 }
1773
zhihuang1c378ed2017-08-17 14:10:50 -07001774 // Add audio/video/data m= sections to the end if needed.
1775 if (!audio_index && offer_new_audio_description) {
1776 session_options->media_description_options.push_back(
1777 cricket::MediaDescriptionOptions(
1778 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1779 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1780 audio_index = rtc::Optional<size_t>(
1781 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001782 }
zhihuang1c378ed2017-08-17 14:10:50 -07001783 if (!video_index && offer_new_video_description) {
1784 session_options->media_description_options.push_back(
1785 cricket::MediaDescriptionOptions(
1786 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1787 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1788 video_index = rtc::Optional<size_t>(
1789 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001790 }
zhihuang1c378ed2017-08-17 14:10:50 -07001791 if (!data_index && offer_new_data_description) {
1792 session_options->media_description_options.push_back(
1793 cricket::MediaDescriptionOptions(
1794 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1795 cricket::RtpTransceiverDirection(true, true), false));
1796 data_index = rtc::Optional<size_t>(
1797 session_options->media_description_options.size() - 1);
1798 }
1799
1800 cricket::MediaDescriptionOptions* audio_media_description_options =
1801 !audio_index ? nullptr
1802 : &session_options->media_description_options[*audio_index];
1803 cricket::MediaDescriptionOptions* video_media_description_options =
1804 !video_index ? nullptr
1805 : &session_options->media_description_options[*video_index];
1806 cricket::MediaDescriptionOptions* data_media_description_options =
1807 !data_index ? nullptr
1808 : &session_options->media_description_options[*data_index];
1809
1810 // Apply ICE restart flag and renomination flag.
1811 for (auto& options : session_options->media_description_options) {
1812 options.transport_options.ice_restart = rtc_options.ice_restart;
1813 options.transport_options.enable_ice_renomination =
1814 configuration_.enable_ice_renomination;
1815 }
1816
1817 AddRtpSenderOptions(senders_, audio_media_description_options,
1818 video_media_description_options);
1819 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001820
zhihuang9763d562016-08-05 11:14:50 -07001821 // Intentionally unset the data channel type for RTP data channel with the
1822 // second condition. Otherwise the RTP data channels would be successfully
1823 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1824 // when building with chromium. We want to leave RTP data channels broken, so
1825 // people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001826 if (!rtp_data_channels_.empty() ||
1827 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001828 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001829 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001830
1831 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001832 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001833}
1834
zhihuang1c378ed2017-08-17 14:10:50 -07001835void PeerConnection::GetOptionsForAnswer(
1836 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001837 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001838 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001839
zhihuang1c378ed2017-08-17 14:10:50 -07001840 // Figure out transceiver directional preferences.
1841 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1842 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1843
1844 // By default, generate sendrecv/recvonly m= sections. The direction is also
1845 // restricted by the direction in the offer.
1846 bool recv_audio = true;
1847 bool recv_video = true;
1848
1849 // The "offer_to_receive_X" options allow those defaults to be overridden.
1850 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1851 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001852 }
zhihuang1c378ed2017-08-17 14:10:50 -07001853 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1854 recv_video = (rtc_options.offer_to_receive_video > 0);
1855 }
1856
1857 rtc::Optional<size_t> audio_index;
1858 rtc::Optional<size_t> video_index;
1859 rtc::Optional<size_t> data_index;
zhihuang141aacb2017-08-29 13:23:53 -07001860 if (session_->remote_description()) {
1861 // The pending remote description should be an offer.
1862 RTC_DCHECK(session_->remote_description()->type() ==
1863 SessionDescriptionInterface::kOffer);
1864 // Generate m= sections that match those in the offer.
1865 // Note that mediasession.cc will handle intersection our preferred
1866 // direction with the offered direction.
1867 GenerateMediaDescriptionOptions(
1868 session_->remote_description(),
1869 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1870 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1871 &video_index, &data_index, session_options);
1872 }
zhihuang1c378ed2017-08-17 14:10:50 -07001873
1874 cricket::MediaDescriptionOptions* audio_media_description_options =
1875 !audio_index ? nullptr
1876 : &session_options->media_description_options[*audio_index];
1877 cricket::MediaDescriptionOptions* video_media_description_options =
1878 !video_index ? nullptr
1879 : &session_options->media_description_options[*video_index];
1880 cricket::MediaDescriptionOptions* data_media_description_options =
1881 !data_index ? nullptr
1882 : &session_options->media_description_options[*data_index];
1883
1884 // Apply ICE renomination flag.
1885 for (auto& options : session_options->media_description_options) {
1886 options.transport_options.enable_ice_renomination =
1887 configuration_.enable_ice_renomination;
1888 }
1889
1890 AddRtpSenderOptions(senders_, audio_media_description_options,
1891 video_media_description_options);
1892 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
1893
zhihuang9763d562016-08-05 11:14:50 -07001894 // Intentionally unset the data channel type for RTP data channel. Otherwise
1895 // the RTP data channels would be successfully negotiated by default and the
1896 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1897 // We want to leave RTP data channels broken, so people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001898 if (!rtp_data_channels_.empty() ||
1899 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001900 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001901 }
zhihuangaf388472016-11-02 16:49:48 -07001902
zhihuang1c378ed2017-08-17 14:10:50 -07001903 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001904 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001905}
1906
zhihuang1c378ed2017-08-17 14:10:50 -07001907void PeerConnection::GenerateMediaDescriptionOptions(
1908 const SessionDescriptionInterface* session_desc,
1909 cricket::RtpTransceiverDirection audio_direction,
1910 cricket::RtpTransceiverDirection video_direction,
1911 rtc::Optional<size_t>* audio_index,
1912 rtc::Optional<size_t>* video_index,
1913 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08001914 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001915 for (const cricket::ContentInfo& content :
1916 session_desc->description()->contents()) {
1917 if (IsAudioContent(&content)) {
1918 // If we already have an audio m= section, reject this extra one.
1919 if (*audio_index) {
1920 session_options->media_description_options.push_back(
1921 cricket::MediaDescriptionOptions(
1922 cricket::MEDIA_TYPE_AUDIO, content.name,
1923 cricket::RtpTransceiverDirection(false, false), true));
1924 } else {
1925 session_options->media_description_options.push_back(
1926 cricket::MediaDescriptionOptions(
1927 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
1928 !audio_direction.send && !audio_direction.recv));
1929 *audio_index = rtc::Optional<size_t>(
1930 session_options->media_description_options.size() - 1);
1931 }
1932 } else if (IsVideoContent(&content)) {
1933 // If we already have an video m= section, reject this extra one.
1934 if (*video_index) {
1935 session_options->media_description_options.push_back(
1936 cricket::MediaDescriptionOptions(
1937 cricket::MEDIA_TYPE_VIDEO, content.name,
1938 cricket::RtpTransceiverDirection(false, false), true));
1939 } else {
1940 session_options->media_description_options.push_back(
1941 cricket::MediaDescriptionOptions(
1942 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1943 !video_direction.send && !video_direction.recv));
1944 *video_index = rtc::Optional<size_t>(
1945 session_options->media_description_options.size() - 1);
1946 }
1947 } else {
1948 RTC_DCHECK(IsDataContent(&content));
1949 // If we already have an data m= section, reject this extra one.
1950 if (*data_index) {
1951 session_options->media_description_options.push_back(
1952 cricket::MediaDescriptionOptions(
1953 cricket::MEDIA_TYPE_DATA, content.name,
1954 cricket::RtpTransceiverDirection(false, false), true));
1955 } else {
1956 session_options->media_description_options.push_back(
1957 cricket::MediaDescriptionOptions(
1958 cricket::MEDIA_TYPE_DATA, content.name,
1959 // Direction for data sections is meaningless, but legacy
1960 // endpoints might expect sendrecv.
1961 cricket::RtpTransceiverDirection(true, true), false));
1962 *data_index = rtc::Optional<size_t>(
1963 session_options->media_description_options.size() - 1);
1964 }
1965 }
htaa2a49d92016-03-04 02:51:39 -08001966 }
deadbeefab9b2d12015-10-14 11:33:11 -07001967}
1968
deadbeeffaac4972015-11-12 15:33:07 -08001969void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1970 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001971 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1972 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001973}
1974
deadbeefab9b2d12015-10-14 11:33:11 -07001975void PeerConnection::UpdateRemoteStreamsList(
1976 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001977 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001978 cricket::MediaType media_type,
1979 StreamCollection* new_streams) {
1980 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1981
1982 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001983 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001984 auto track_it = current_tracks->begin();
1985 while (track_it != current_tracks->end()) {
1986 const TrackInfo& info = *track_it;
1987 const cricket::StreamParams* params =
1988 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001989 bool track_exists = params && params->id == info.track_id;
1990 // If this is a default track, and we still need it, don't remove it.
1991 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1992 track_exists) {
1993 ++track_it;
1994 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001995 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1996 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001997 }
1998 }
1999
2000 // Find new and active tracks.
2001 for (const cricket::StreamParams& params : streams) {
2002 // The sync_label is the MediaStream label and the |stream.id| is the
2003 // track id.
2004 const std::string& stream_label = params.sync_label;
2005 const std::string& track_id = params.id;
2006 uint32_t ssrc = params.first_ssrc();
2007
2008 rtc::scoped_refptr<MediaStreamInterface> stream =
2009 remote_streams_->find(stream_label);
2010 if (!stream) {
2011 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002012 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2013 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002014 remote_streams_->AddStream(stream);
2015 new_streams->AddStream(stream);
2016 }
2017
2018 const TrackInfo* track_info =
2019 FindTrackInfo(*current_tracks, stream_label, track_id);
2020 if (!track_info) {
2021 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2022 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2023 }
2024 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002025
2026 // Add default track if necessary.
2027 if (default_track_needed) {
2028 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2029 remote_streams_->find(kDefaultStreamLabel);
2030 if (!default_stream) {
2031 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002032 default_stream = MediaStreamProxy::Create(
2033 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002034 remote_streams_->AddStream(default_stream);
2035 new_streams->AddStream(default_stream);
2036 }
2037 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2038 ? kDefaultAudioTrackLabel
2039 : kDefaultVideoTrackLabel;
2040 const TrackInfo* default_track_info =
2041 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2042 if (!default_track_info) {
2043 current_tracks->push_back(
2044 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2045 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2046 }
2047 }
deadbeefab9b2d12015-10-14 11:33:11 -07002048}
2049
2050void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2051 const std::string& track_id,
2052 uint32_t ssrc,
2053 cricket::MediaType media_type) {
2054 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2055
2056 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002057 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002058 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002059 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002060 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002061 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002062 }
2063}
2064
2065void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2066 const std::string& track_id,
2067 cricket::MediaType media_type) {
2068 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2069
Henrik Boström933d8b02017-10-10 10:05:16 -07002070 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002071 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002072 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2073 // will be notified which will end the AudioRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002074 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002075 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2076 stream->FindAudioTrack(track_id);
2077 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002078 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002079 }
2080 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002081 // Stopping or destroying a VideoRtpReceiver will end the
2082 // VideoRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002083 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002084 rtc::scoped_refptr<VideoTrackInterface> video_track =
2085 stream->FindVideoTrack(track_id);
2086 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002087 // There's no guarantee the track is still available, e.g. the track may
2088 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002089 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002090 }
2091 } else {
nisseede5da42017-01-12 05:15:36 -08002092 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002093 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002094 if (receiver) {
2095 observer_->OnRemoveTrack(receiver);
2096 }
deadbeefab9b2d12015-10-14 11:33:11 -07002097}
2098
2099void PeerConnection::UpdateEndedRemoteMediaStreams() {
2100 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2101 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2102 MediaStreamInterface* stream = remote_streams_->at(i);
2103 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2104 streams_to_remove.push_back(stream);
2105 }
2106 }
2107
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002108 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002109 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002110 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002111 }
2112}
2113
deadbeefab9b2d12015-10-14 11:33:11 -07002114void PeerConnection::UpdateLocalTracks(
2115 const std::vector<cricket::StreamParams>& streams,
2116 cricket::MediaType media_type) {
2117 TrackInfos* current_tracks = GetLocalTracks(media_type);
2118
2119 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2120 // don't match the new StreamParam.
2121 TrackInfos::iterator track_it = current_tracks->begin();
2122 while (track_it != current_tracks->end()) {
2123 const TrackInfo& info = *track_it;
2124 const cricket::StreamParams* params =
2125 cricket::GetStreamBySsrc(streams, info.ssrc);
2126 if (!params || params->id != info.track_id ||
2127 params->sync_label != info.stream_label) {
2128 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2129 media_type);
2130 track_it = current_tracks->erase(track_it);
2131 } else {
2132 ++track_it;
2133 }
2134 }
2135
2136 // Find new and active tracks.
2137 for (const cricket::StreamParams& params : streams) {
2138 // The sync_label is the MediaStream label and the |stream.id| is the
2139 // track id.
2140 const std::string& stream_label = params.sync_label;
2141 const std::string& track_id = params.id;
2142 uint32_t ssrc = params.first_ssrc();
2143 const TrackInfo* track_info =
2144 FindTrackInfo(*current_tracks, stream_label, track_id);
2145 if (!track_info) {
2146 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2147 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2148 }
2149 }
2150}
2151
2152void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2153 const std::string& track_id,
2154 uint32_t ssrc,
2155 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002156 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002157 if (!sender) {
2158 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2159 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002160 return;
2161 }
2162
deadbeeffac06552015-11-25 11:26:01 -08002163 if (sender->media_type() != media_type) {
2164 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2165 << " description with an unexpected media type.";
2166 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002167 }
deadbeeffac06552015-11-25 11:26:01 -08002168
2169 sender->set_stream_id(stream_label);
2170 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002171}
2172
2173void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2174 const std::string& track_id,
2175 uint32_t ssrc,
2176 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002177 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002178 if (!sender) {
2179 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002180 // SessionDescriptions has been renegotiated.
2181 return;
2182 }
deadbeeffac06552015-11-25 11:26:01 -08002183
2184 // A sender has been removed from the SessionDescription but it's still
2185 // associated with the PeerConnection. This only occurs if the SDP doesn't
2186 // match with the calls to CreateSender, AddStream and RemoveStream.
2187 if (sender->media_type() != media_type) {
2188 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2189 << " description with an unexpected media type.";
2190 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002191 }
deadbeeffac06552015-11-25 11:26:01 -08002192
2193 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002194}
2195
2196void PeerConnection::UpdateLocalRtpDataChannels(
2197 const cricket::StreamParamsVec& streams) {
2198 std::vector<std::string> existing_channels;
2199
2200 // Find new and active data channels.
2201 for (const cricket::StreamParams& params : streams) {
2202 // |it->sync_label| is actually the data channel label. The reason is that
2203 // we use the same naming of data channels as we do for
2204 // MediaStreams and Tracks.
2205 // For MediaStreams, the sync_label is the MediaStream label and the
2206 // track label is the same as |streamid|.
2207 const std::string& channel_label = params.sync_label;
2208 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002209 if (data_channel_it == rtp_data_channels_.end()) {
2210 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002211 continue;
2212 }
2213 // Set the SSRC the data channel should use for sending.
2214 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2215 existing_channels.push_back(data_channel_it->first);
2216 }
2217
2218 UpdateClosingRtpDataChannels(existing_channels, true);
2219}
2220
2221void PeerConnection::UpdateRemoteRtpDataChannels(
2222 const cricket::StreamParamsVec& streams) {
2223 std::vector<std::string> existing_channels;
2224
2225 // Find new and active data channels.
2226 for (const cricket::StreamParams& params : streams) {
2227 // The data channel label is either the mslabel or the SSRC if the mslabel
2228 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2229 std::string label = params.sync_label.empty()
2230 ? rtc::ToString(params.first_ssrc())
2231 : params.sync_label;
2232 auto data_channel_it = rtp_data_channels_.find(label);
2233 if (data_channel_it == rtp_data_channels_.end()) {
2234 // This is a new data channel.
2235 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2236 } else {
2237 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2238 }
2239 existing_channels.push_back(label);
2240 }
2241
2242 UpdateClosingRtpDataChannels(existing_channels, false);
2243}
2244
2245void PeerConnection::UpdateClosingRtpDataChannels(
2246 const std::vector<std::string>& active_channels,
2247 bool is_local_update) {
2248 auto it = rtp_data_channels_.begin();
2249 while (it != rtp_data_channels_.end()) {
2250 DataChannel* data_channel = it->second;
2251 if (std::find(active_channels.begin(), active_channels.end(),
2252 data_channel->label()) != active_channels.end()) {
2253 ++it;
2254 continue;
2255 }
2256
2257 if (is_local_update) {
2258 data_channel->SetSendSsrc(0);
2259 } else {
2260 data_channel->RemotePeerRequestClose();
2261 }
2262
2263 if (data_channel->state() == DataChannel::kClosed) {
2264 rtp_data_channels_.erase(it);
2265 it = rtp_data_channels_.begin();
2266 } else {
2267 ++it;
2268 }
2269 }
2270}
2271
2272void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2273 uint32_t remote_ssrc) {
2274 rtc::scoped_refptr<DataChannel> channel(
2275 InternalCreateDataChannel(label, nullptr));
2276 if (!channel.get()) {
2277 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2278 << "CreateDataChannel failed.";
2279 return;
2280 }
2281 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002282 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2283 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002284 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002285}
2286
2287rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2288 const std::string& label,
2289 const InternalDataChannelInit* config) {
2290 if (IsClosed()) {
2291 return nullptr;
2292 }
2293 if (session_->data_channel_type() == cricket::DCT_NONE) {
2294 LOG(LS_ERROR)
2295 << "InternalCreateDataChannel: Data is not supported in this call.";
2296 return nullptr;
2297 }
2298 InternalDataChannelInit new_config =
2299 config ? (*config) : InternalDataChannelInit();
2300 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2301 if (new_config.id < 0) {
2302 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002303 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002304 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2305 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2306 return nullptr;
2307 }
2308 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2309 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2310 << "because the id is already in use or out of range.";
2311 return nullptr;
2312 }
2313 }
2314
2315 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
Steve Anton978b8762017-09-29 12:15:02 -07002316 session_, session_->data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002317 if (!channel) {
2318 sid_allocator_.ReleaseSid(new_config.id);
2319 return nullptr;
2320 }
2321
2322 if (channel->data_channel_type() == cricket::DCT_RTP) {
2323 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2324 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2325 << " already exists.";
2326 return nullptr;
2327 }
2328 rtp_data_channels_[channel->label()] = channel;
2329 } else {
2330 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2331 sctp_data_channels_.push_back(channel);
2332 channel->SignalClosed.connect(this,
2333 &PeerConnection::OnSctpDataChannelClosed);
2334 }
2335
hbos82ebe022016-11-14 01:41:09 -08002336 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002337 return channel;
2338}
2339
2340bool PeerConnection::HasDataChannels() const {
2341 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2342}
2343
2344void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2345 for (const auto& channel : sctp_data_channels_) {
2346 if (channel->id() < 0) {
2347 int sid;
2348 if (!sid_allocator_.AllocateSid(role, &sid)) {
2349 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2350 continue;
2351 }
2352 channel->SetSctpSid(sid);
2353 }
2354 }
2355}
2356
2357void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002358 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002359 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2360 ++it) {
2361 if (it->get() == channel) {
2362 if (channel->id() >= 0) {
2363 sid_allocator_.ReleaseSid(channel->id());
2364 }
deadbeefbd292462015-12-14 18:15:29 -08002365 // Since this method is triggered by a signal from the DataChannel,
2366 // we can't free it directly here; we need to free it asynchronously.
2367 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002368 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002369 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2370 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002371 return;
2372 }
2373 }
2374}
2375
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002376void PeerConnection::OnVoiceChannelCreated() {
2377 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2378 session_->voice_channel(), senders_, receivers_,
2379 cricket::MEDIA_TYPE_AUDIO);
2380}
2381
deadbeefab9b2d12015-10-14 11:33:11 -07002382void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002383 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2384 cricket::VoiceChannel>(
2385 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2386}
2387
2388void PeerConnection::OnVideoChannelCreated() {
2389 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2390 session_->video_channel(), senders_, receivers_,
2391 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002392}
2393
2394void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002395 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2396 cricket::VideoChannel>(
2397 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002398}
2399
2400void PeerConnection::OnDataChannelCreated() {
2401 for (const auto& channel : sctp_data_channels_) {
2402 channel->OnTransportChannelCreated();
2403 }
2404}
2405
2406void PeerConnection::OnDataChannelDestroyed() {
2407 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2408 // DataChannel may callback to us and try to modify the list.
2409 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2410 temp_rtp_dcs.swap(rtp_data_channels_);
2411 for (const auto& kv : temp_rtp_dcs) {
2412 kv.second->OnTransportChannelDestroyed();
2413 }
2414
2415 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2416 temp_sctp_dcs.swap(sctp_data_channels_);
2417 for (const auto& channel : temp_sctp_dcs) {
2418 channel->OnTransportChannelDestroyed();
2419 }
2420}
2421
2422void PeerConnection::OnDataChannelOpenMessage(
2423 const std::string& label,
2424 const InternalDataChannelInit& config) {
2425 rtc::scoped_refptr<DataChannel> channel(
2426 InternalCreateDataChannel(label, &config));
2427 if (!channel.get()) {
2428 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2429 return;
2430 }
2431
deadbeefa601f5c2016-06-06 14:27:39 -07002432 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2433 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002434 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002435}
2436
zhihuang1c378ed2017-08-17 14:10:50 -07002437bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2438 return std::find_if(
2439 senders_.begin(), senders_.end(),
2440 [type](const rtc::scoped_refptr<
2441 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2442 return sender->media_type() == type;
2443 }) != senders_.end();
2444}
2445
deadbeefa601f5c2016-06-06 14:27:39 -07002446RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2447 auto it = std::find_if(
2448 senders_.begin(), senders_.end(),
2449 [id](const rtc::scoped_refptr<
2450 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2451 return sender->id() == id;
2452 });
2453 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002454}
2455
deadbeefa601f5c2016-06-06 14:27:39 -07002456std::vector<
2457 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002458PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2459 return std::find_if(
2460 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002461 [track](const rtc::scoped_refptr<
2462 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002463 return sender->track() == track;
2464 });
2465}
2466
deadbeefa601f5c2016-06-06 14:27:39 -07002467std::vector<rtc::scoped_refptr<
2468 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002469PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002470 return std::find_if(
2471 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002472 [track_id](const rtc::scoped_refptr<
2473 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002474 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002475 });
2476}
2477
deadbeefab9b2d12015-10-14 11:33:11 -07002478PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2479 cricket::MediaType media_type) {
2480 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2481 media_type == cricket::MEDIA_TYPE_VIDEO);
2482 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2483 : &remote_video_tracks_;
2484}
2485
2486PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2487 cricket::MediaType media_type) {
2488 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2489 media_type == cricket::MEDIA_TYPE_VIDEO);
2490 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2491 : &local_video_tracks_;
2492}
2493
2494const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2495 const PeerConnection::TrackInfos& infos,
2496 const std::string& stream_label,
2497 const std::string track_id) const {
2498 for (const TrackInfo& track_info : infos) {
2499 if (track_info.stream_label == stream_label &&
2500 track_info.track_id == track_id) {
2501 return &track_info;
2502 }
2503 }
2504 return nullptr;
2505}
2506
2507DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2508 for (const auto& channel : sctp_data_channels_) {
2509 if (channel->id() == sid) {
2510 return channel;
2511 }
2512 }
2513 return nullptr;
2514}
2515
deadbeef91dd5672016-05-18 16:55:30 -07002516bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002517 const RTCConfiguration& configuration) {
2518 cricket::ServerAddresses stun_servers;
2519 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002520 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2521 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002522 return false;
2523 }
2524
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002525 port_allocator_->Initialize();
2526
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002527 // To handle both internal and externally created port allocator, we will
2528 // enable BUNDLE here.
2529 int portallocator_flags = port_allocator_->flags();
2530 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002531 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2532 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002533 // If the disable-IPv6 flag was specified, we'll not override it
2534 // by experiment.
2535 if (configuration.disable_ipv6) {
2536 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002537 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2538 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002539 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2540 }
2541
zhihuangb09b3f92017-03-07 14:40:51 -08002542 if (configuration.disable_ipv6_on_wifi) {
2543 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2544 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2545 }
2546
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002547 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2548 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2549 LOG(LS_INFO) << "TCP candidates are disabled.";
2550 }
2551
honghaiz60347052016-05-31 18:29:12 -07002552 if (configuration.candidate_network_policy ==
2553 kCandidateNetworkPolicyLowCost) {
2554 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2555 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2556 }
2557
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002558 port_allocator_->set_flags(portallocator_flags);
2559 // No step delay is used while allocating ports.
2560 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2561 port_allocator_->set_candidate_filter(
2562 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002563 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002564
2565 // Call this last since it may create pooled allocator sessions using the
2566 // properties set above.
2567 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002568 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002569 configuration.prune_turn_ports,
2570 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002571 return true;
2572}
2573
deadbeef91dd5672016-05-18 16:55:30 -07002574bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002575 const cricket::ServerAddresses& stun_servers,
2576 const std::vector<cricket::RelayServerConfig>& turn_servers,
2577 IceTransportsType type,
2578 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002579 bool prune_turn_ports,
2580 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002581 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002582 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002583 // Call this last since it may create pooled allocator sessions using the
2584 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002585 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02002586 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
2587 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002588}
2589
Elad Alon99c3fe52017-10-13 16:29:40 +02002590bool PeerConnection::StartRtcEventLog_w(
2591 std::unique_ptr<RtcEventLogOutput> output) {
zhihuang77985012017-02-07 15:45:16 -08002592 if (!event_log_) {
2593 return false;
2594 }
Elad Alon99c3fe52017-10-13 16:29:40 +02002595 return event_log_->StartLogging(std::move(output));
ivoc14d5dbe2016-07-04 07:06:55 -07002596}
2597
2598void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002599 if (event_log_) {
2600 event_log_->StopLogging();
2601 }
ivoc14d5dbe2016-07-04 07:06:55 -07002602}
nisseeaabdf62017-05-05 02:23:02 -07002603
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604} // namespace webrtc