blob: 3889222e03136a285c16bf6ec1f8bbca9595ada2 [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
Steve Antonba818672017-11-06 10:21:57 -080048namespace webrtc {
49
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050namespace {
51
deadbeefab9b2d12015-10-14 11:33:11 -070052using webrtc::DataChannel;
53using webrtc::MediaConstraintsInterface;
54using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080056using webrtc::RTCError;
57using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070058using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080059using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070060using webrtc::RtpSenderProxy;
61using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070062using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063
deadbeefab9b2d12015-10-14 11:33:11 -070064static const char kDefaultStreamLabel[] = "default";
65static const char kDefaultAudioTrackLabel[] = "defaulta0";
66static const char kDefaultVideoTrackLabel[] = "defaultv0";
67
zhihuang8f65cdf2016-05-06 18:40:30 -070068// The length of RTCP CNAMEs.
69static const int kRtcpCnameLength = 16;
70
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000072 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070074 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080076 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077};
78
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000079struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080 explicit SetSessionDescriptionMsg(
81 webrtc::SetSessionDescriptionObserver* observer)
82 : observer(observer) {
83 }
84
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000085 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086 std::string error;
87};
88
deadbeefab9b2d12015-10-14 11:33:11 -070089struct CreateSessionDescriptionMsg : public rtc::MessageData {
90 explicit CreateSessionDescriptionMsg(
91 webrtc::CreateSessionDescriptionObserver* observer)
92 : observer(observer) {}
93
94 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
95 std::string error;
96};
97
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000098struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000099 GetStatsMsg(webrtc::StatsObserver* observer,
100 webrtc::MediaStreamTrackInterface* track)
101 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000103 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000104 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105};
106
deadbeefab9b2d12015-10-14 11:33:11 -0700107// Check if we can send |new_stream| on a PeerConnection.
108bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
109 webrtc::MediaStreamInterface* new_stream) {
110 if (!new_stream || !current_streams) {
111 return false;
112 }
113 if (current_streams->find(new_stream->label()) != nullptr) {
114 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
115 << " is already added.";
116 return false;
117 }
118 return true;
119}
120
121bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
122 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
123}
124
deadbeef5e97fb52015-10-15 12:49:08 -0700125// If the direction is "recvonly" or "inactive", treat the description
126// as containing no streams.
127// See: https://code.google.com/p/webrtc/issues/detail?id=5054
128std::vector<cricket::StreamParams> GetActiveStreams(
129 const cricket::MediaContentDescription* desc) {
130 return MediaContentDirectionHasSend(desc->direction())
131 ? desc->streams()
132 : std::vector<cricket::StreamParams>();
133}
134
deadbeefab9b2d12015-10-14 11:33:11 -0700135bool IsValidOfferToReceiveMedia(int value) {
136 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
137 return (value >= Options::kUndefined) &&
138 (value <= Options::kMaxOfferToReceiveMedia);
139}
140
zhihuang1c378ed2017-08-17 14:10:50 -0700141// Add options to |[audio/video]_media_description_options| from |senders|.
142void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700143 const std::vector<rtc::scoped_refptr<
144 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700145 cricket::MediaDescriptionOptions* audio_media_description_options,
146 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700147 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700148 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
149 if (audio_media_description_options) {
150 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700151 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700152 }
153 } else {
154 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
155 if (video_media_description_options) {
156 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700157 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700158 }
159 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700160 }
zhihuang1c378ed2017-08-17 14:10:50 -0700161}
olka3c747662017-08-17 06:50:32 -0700162
zhihuang1c378ed2017-08-17 14:10:50 -0700163// Add options to |session_options| from |rtp_data_channels|.
164void AddRtpDataChannelOptions(
165 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
166 rtp_data_channels,
167 cricket::MediaDescriptionOptions* data_media_description_options) {
168 if (!data_media_description_options) {
169 return;
170 }
deadbeefab9b2d12015-10-14 11:33:11 -0700171 // Check for data channels.
172 for (const auto& kv : rtp_data_channels) {
173 const DataChannel* channel = kv.second;
174 if (channel->state() == DataChannel::kConnecting ||
175 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 // Legacy RTP data channels are signaled with the track/stream ID set to
177 // the data channel's label.
178 data_media_description_options->AddRtpDataChannel(channel->label(),
179 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700180 }
181 }
182}
183
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700184uint32_t ConvertIceTransportTypeToCandidateFilter(
185 PeerConnectionInterface::IceTransportsType type) {
186 switch (type) {
187 case PeerConnectionInterface::kNone:
188 return cricket::CF_NONE;
189 case PeerConnectionInterface::kRelay:
190 return cricket::CF_RELAY;
191 case PeerConnectionInterface::kNoHost:
192 return (cricket::CF_ALL & ~cricket::CF_HOST);
193 case PeerConnectionInterface::kAll:
194 return cricket::CF_ALL;
195 default:
nissec80e7412017-01-11 05:56:46 -0800196 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700197 }
198 return cricket::CF_NONE;
199}
200
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700201// Helper method to set a voice/video channel on all applicable senders
202// and receivers when one is created/destroyed by WebRtcSession.
203//
204// Used by On(Voice|Video)Channel(Created|Destroyed)
205template <class SENDER,
206 class RECEIVER,
207 class CHANNEL,
208 class SENDERS,
209 class RECEIVERS>
210void SetChannelOnSendersAndReceivers(CHANNEL* channel,
Steve Anton36b29d12017-10-30 09:57:42 -0700211 const SENDERS& senders,
212 const RECEIVERS& receivers,
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700213 cricket::MediaType media_type) {
214 for (auto& sender : senders) {
215 if (sender->media_type() == media_type) {
216 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
217 }
218 }
219 for (auto& receiver : receivers) {
220 if (receiver->media_type() == media_type) {
221 if (!channel) {
222 receiver->internal()->Stop();
223 }
224 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
225 }
226 }
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
deadbeef0a6c4ca2015-10-06 11:38:28 -0700244} // namespace
245
Steve Antonba818672017-11-06 10:21:57 -0800246std::string GetSignalingStateString(
247 PeerConnectionInterface::SignalingState state) {
248 switch (state) {
249 case PeerConnectionInterface::kStable:
250 return "kStable";
251 case PeerConnectionInterface::kHaveLocalOffer:
252 return "kHaveLocalOffer";
253 case PeerConnectionInterface::kHaveLocalPrAnswer:
254 return "kHavePrAnswer";
255 case PeerConnectionInterface::kHaveRemoteOffer:
256 return "kHaveRemoteOffer";
257 case PeerConnectionInterface::kHaveRemotePrAnswer:
258 return "kHaveRemotePrAnswer";
259 case PeerConnectionInterface::kClosed:
260 return "kClosed";
261 }
262 RTC_NOTREACHED();
263 return "";
264}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265
deadbeef293e9262017-01-11 12:28:30 -0800266bool PeerConnectionInterface::RTCConfiguration::operator==(
267 const PeerConnectionInterface::RTCConfiguration& o) const {
268 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700269 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800270 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000271 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700272 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800273 BundlePolicy bundle_policy;
274 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700275 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
276 int ice_candidate_pool_size;
277 bool disable_ipv6;
278 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700279 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700280 bool enable_rtp_data_channel;
281 rtc::Optional<int> screencast_min_bitrate;
282 rtc::Optional<bool> combined_audio_video_bwe;
283 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800284 TcpCandidatePolicy tcp_candidate_policy;
285 CandidateNetworkPolicy candidate_network_policy;
286 int audio_jitter_buffer_max_packets;
287 bool audio_jitter_buffer_fast_accelerate;
288 int ice_connection_receiving_timeout;
289 int ice_backup_candidate_pair_ping_interval;
290 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800291 bool prioritize_most_likely_ice_candidate_pairs;
292 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800293 bool prune_turn_ports;
294 bool presume_writable_when_fully_relayed;
295 bool enable_ice_renomination;
296 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800297 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700298 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200299 webrtc::TurnCustomizer* turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800300 };
301 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
302 "Did you add something to RTCConfiguration and forget to "
303 "update operator==?");
304 return type == o.type && servers == o.servers &&
305 bundle_policy == o.bundle_policy &&
306 rtcp_mux_policy == o.rtcp_mux_policy &&
307 tcp_candidate_policy == o.tcp_candidate_policy &&
308 candidate_network_policy == o.candidate_network_policy &&
309 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
310 audio_jitter_buffer_fast_accelerate ==
311 o.audio_jitter_buffer_fast_accelerate &&
312 ice_connection_receiving_timeout ==
313 o.ice_connection_receiving_timeout &&
314 ice_backup_candidate_pair_ping_interval ==
315 o.ice_backup_candidate_pair_ping_interval &&
316 continual_gathering_policy == o.continual_gathering_policy &&
317 certificates == o.certificates &&
318 prioritize_most_likely_ice_candidate_pairs ==
319 o.prioritize_most_likely_ice_candidate_pairs &&
320 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800321 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700322 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800323 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800324 screencast_min_bitrate == o.screencast_min_bitrate &&
325 combined_audio_video_bwe == o.combined_audio_video_bwe &&
326 enable_dtls_srtp == o.enable_dtls_srtp &&
327 ice_candidate_pool_size == o.ice_candidate_pool_size &&
328 prune_turn_ports == o.prune_turn_ports &&
329 presume_writable_when_fully_relayed ==
330 o.presume_writable_when_fully_relayed &&
331 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800332 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700333 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200334 ice_regather_interval_range == o.ice_regather_interval_range &&
335 turn_customizer == o.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800336}
337
338bool PeerConnectionInterface::RTCConfiguration::operator!=(
339 const PeerConnectionInterface::RTCConfiguration& o) const {
340 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800341}
342
zhihuang8f65cdf2016-05-06 18:40:30 -0700343// Generate a RTCP CNAME when a PeerConnection is created.
344std::string GenerateRtcpCname() {
345 std::string cname;
346 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
347 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800348 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700349 }
350 return cname;
351}
352
zhihuang1c378ed2017-08-17 14:10:50 -0700353bool ValidateOfferAnswerOptions(
354 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
355 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
356 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700357}
358
zhihuang1c378ed2017-08-17 14:10:50 -0700359// From |rtc_options|, fill parts of |session_options| shared by all generated
360// m= sections (in other words, nothing that involves a map/array).
361void ExtractSharedMediaSessionOptions(
362 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
363 cricket::MediaSessionOptions* session_options) {
364 session_options->vad_enabled = rtc_options.voice_activity_detection;
365 session_options->bundle_enabled = rtc_options.use_rtp_mux;
366}
zhihuanga77e6bb2017-08-14 18:17:48 -0700367
zhihuang1c378ed2017-08-17 14:10:50 -0700368bool ConvertConstraintsToOfferAnswerOptions(
369 const MediaConstraintsInterface* constraints,
370 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700371 if (!constraints) {
372 return true;
373 }
zhihuang1c378ed2017-08-17 14:10:50 -0700374
375 bool value = false;
376 size_t mandatory_constraints_satisfied = 0;
377
378 if (FindConstraint(constraints,
379 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
380 &mandatory_constraints_satisfied)) {
381 offer_answer_options->offer_to_receive_audio =
382 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
383 kOfferToReceiveMediaTrue
384 : 0;
385 }
386
387 if (FindConstraint(constraints,
388 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
389 &mandatory_constraints_satisfied)) {
390 offer_answer_options->offer_to_receive_video =
391 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
392 kOfferToReceiveMediaTrue
393 : 0;
394 }
395 if (FindConstraint(constraints,
396 MediaConstraintsInterface::kVoiceActivityDetection, &value,
397 &mandatory_constraints_satisfied)) {
398 offer_answer_options->voice_activity_detection = value;
399 }
400 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
401 &mandatory_constraints_satisfied)) {
402 offer_answer_options->use_rtp_mux = value;
403 }
404 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
405 &value, &mandatory_constraints_satisfied)) {
406 offer_answer_options->ice_restart = value;
407 }
408
deadbeefab9b2d12015-10-14 11:33:11 -0700409 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
410}
411
zhihuang38ede132017-06-15 12:52:32 -0700412PeerConnection::PeerConnection(PeerConnectionFactory* factory,
413 std::unique_ptr<RtcEventLog> event_log,
414 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000415 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700416 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700417 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700418 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700419 remote_streams_(StreamCollection::Create()),
420 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000421
422PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100423 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700424 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700425 // Need to detach RTP senders/receivers from WebRtcSession,
426 // since it's about to be destroyed.
427 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700428 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700429 }
430 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700431 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700432 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700433 // Destroy stats_ because it depends on session_.
434 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800435 if (stats_collector_) {
436 stats_collector_->WaitForPendingRequest();
437 stats_collector_ = nullptr;
438 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700439 // Now destroy session_ before destroying other members,
440 // because its destruction fires signals (such as VoiceChannelDestroyed)
441 // which will trigger some final actions in PeerConnection...
Steve Anton978b8762017-09-29 12:15:02 -0700442 owned_session_.reset(nullptr);
443 session_ = nullptr;
deadbeef91dd5672016-05-18 16:55:30 -0700444 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700445 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700446 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700447 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700448 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700449 call_.reset();
450 event_log_.reset();
451 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000452}
453
454bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000455 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700456 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200457 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800458 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100459 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700460
461 RTCError config_error = ValidateConfiguration(configuration);
462 if (!config_error.ok()) {
463 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
464 return false;
465 }
466
deadbeef293e9262017-01-11 12:28:30 -0800467 if (!allocator) {
468 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
469 << "This shouldn't happen if using PeerConnectionFactory.";
470 return false;
471 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200472
deadbeef653b8e02015-11-11 12:55:10 -0800473 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800474 // TODO(deadbeef): Why do we do this?
475 LOG(LS_ERROR) << "PeerConnection initialized without a "
476 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800477 return false;
478 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000479 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800480 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800481
deadbeef91dd5672016-05-18 16:55:30 -0700482 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700483 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700484 if (!network_thread()->Invoke<bool>(
485 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
486 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000487 return false;
488 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000489
Steve Antonba818672017-11-06 10:21:57 -0800490 owned_session_.reset(
491 new WebRtcSession(this,
492 std::unique_ptr<cricket::TransportController>(
493 factory_->CreateTransportController(
494 port_allocator_.get(),
495 configuration.redetermine_role_on_ice_restart)),
496 factory_->CreateSctpTransportInternalFactory()));
Steve Anton978b8762017-09-29 12:15:02 -0700497 session_ = owned_session_.get();
zhihuang29ff8442016-07-27 11:07:25 -0700498
deadbeefab9b2d12015-10-14 11:33:11 -0700499 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700500 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000501
Steve Antonba818672017-11-06 10:21:57 -0800502 // Need to set configuration before initializing WebRtcSession because it will
503 // reach back to fetch the media config.
504 configuration_ = configuration;
505
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000506 // Initialize the WebRtcSession. It creates transport channels etc.
Steve Antond5585ca2017-10-23 14:49:26 -0700507 session_->Initialize(factory_->options(), std::move(cert_generator),
508 configuration, this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000509
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000510 return true;
511}
512
Steve Anton038834f2017-07-14 15:59:59 -0700513RTCError PeerConnection::ValidateConfiguration(
514 const RTCConfiguration& config) const {
515 if (config.ice_regather_interval_range &&
516 config.continual_gathering_policy == GATHER_ONCE) {
517 return RTCError(RTCErrorType::INVALID_PARAMETER,
518 "ice_regather_interval_range specified but continual "
519 "gathering policy is GATHER_ONCE");
520 }
521 return RTCError::OK();
522}
523
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000524rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700526 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000527}
528
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000529rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000530PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700531 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000532}
533
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000534bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100535 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000536 if (IsClosed()) {
537 return false;
538 }
deadbeefab9b2d12015-10-14 11:33:11 -0700539 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540 return false;
541 }
deadbeefab9b2d12015-10-14 11:33:11 -0700542
543 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800544 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
545 observer->SignalAudioTrackAdded.connect(this,
546 &PeerConnection::OnAudioTrackAdded);
547 observer->SignalAudioTrackRemoved.connect(
548 this, &PeerConnection::OnAudioTrackRemoved);
549 observer->SignalVideoTrackAdded.connect(this,
550 &PeerConnection::OnVideoTrackAdded);
551 observer->SignalVideoTrackRemoved.connect(
552 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700553 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700554
deadbeefab9b2d12015-10-14 11:33:11 -0700555 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700556 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700557 }
558 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700559 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700560 }
561
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000562 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000563 observer_->OnRenegotiationNeeded();
564 return true;
565}
566
567void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100568 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700569 if (!IsClosed()) {
570 for (const auto& track : local_stream->GetAudioTracks()) {
571 RemoveAudioTrack(track.get(), local_stream);
572 }
573 for (const auto& track : local_stream->GetVideoTracks()) {
574 RemoveVideoTrack(track.get(), local_stream);
575 }
deadbeefab9b2d12015-10-14 11:33:11 -0700576 }
deadbeefab9b2d12015-10-14 11:33:11 -0700577 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800578 stream_observers_.erase(
579 std::remove_if(
580 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700581 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800582 return observer->stream()->label().compare(local_stream->label()) ==
583 0;
584 }),
585 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700586
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587 if (IsClosed()) {
588 return;
589 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590 observer_->OnRenegotiationNeeded();
591}
592
deadbeefe1f9d832016-01-14 15:35:42 -0800593rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
594 MediaStreamTrackInterface* track,
595 std::vector<MediaStreamInterface*> streams) {
596 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
597 if (IsClosed()) {
598 return nullptr;
599 }
600 if (streams.size() >= 2) {
601 LOG(LS_ERROR)
602 << "Adding a track with two streams is not currently supported.";
603 return nullptr;
604 }
605 // TODO(deadbeef): Support adding a track to two different senders.
606 if (FindSenderForTrack(track) != senders_.end()) {
607 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
608 return nullptr;
609 }
610
611 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700612 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800613 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700614 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800615 signaling_thread(),
616 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700617 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800618 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700619 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800620 }
621 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700622 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800623 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700624 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800625 }
626 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700627 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800628 signaling_thread(),
629 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700630 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800631 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700632 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800633 }
634 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700635 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800636 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700637 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800638 }
639 } else {
640 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
641 return rtc::scoped_refptr<RtpSenderInterface>();
642 }
643
644 senders_.push_back(new_sender);
645 observer_->OnRenegotiationNeeded();
646 return new_sender;
647}
648
649bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
650 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
651 if (IsClosed()) {
652 return false;
653 }
654
655 auto it = std::find(senders_.begin(), senders_.end(), sender);
656 if (it == senders_.end()) {
657 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
658 return false;
659 }
deadbeefa601f5c2016-06-06 14:27:39 -0700660 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800661 senders_.erase(it);
662
663 observer_->OnRenegotiationNeeded();
664 return true;
665}
666
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000667rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100669 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700670 if (IsClosed()) {
671 return nullptr;
672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 if (!track) {
674 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800675 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 }
deadbeef20cb0c12017-02-01 20:27:00 -0800677 auto it = FindSenderForTrack(track);
678 if (it == senders_.end()) {
679 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
680 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 }
682
deadbeef20cb0c12017-02-01 20:27:00 -0800683 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684}
685
deadbeeffac06552015-11-25 11:26:01 -0800686rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800687 const std::string& kind,
688 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100689 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700690 if (IsClosed()) {
691 return nullptr;
692 }
deadbeefa601f5c2016-06-06 14:27:39 -0700693 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800694 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700695 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700696 signaling_thread(),
697 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800698 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700699 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700700 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800701 } else {
702 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800703 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800704 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800705 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700706 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800707 }
deadbeeffac06552015-11-25 11:26:01 -0800708 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800709 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800710}
711
deadbeef70ab1a12015-09-28 16:53:55 -0700712std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
713 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700714 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
715 for (const auto& sender : senders_) {
716 ret.push_back(sender.get());
717 }
718 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700719}
720
721std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
722PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700723 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
724 for (const auto& receiver : receivers_) {
725 ret.push_back(receiver.get());
726 }
727 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700728}
729
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000731 MediaStreamTrackInterface* track,
732 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100733 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700734 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800735 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 LOG(LS_ERROR) << "GetStats - observer is NULL.";
737 return false;
738 }
739
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000740 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700741 // The StatsCollector is used to tell if a track is valid because it may
742 // remember tracks that the PeerConnection previously removed.
743 if (track && !stats_->IsValidTrack(track->id())) {
744 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
745 << track->id();
746 return false;
747 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700748 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000749 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750 return true;
751}
752
hbos74e1a4f2016-09-15 23:33:01 -0700753void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
754 RTC_DCHECK(stats_collector_);
755 stats_collector_->GetStatsReport(callback);
756}
757
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
759 return signaling_state_;
760}
761
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762PeerConnectionInterface::IceConnectionState
763PeerConnection::ice_connection_state() {
764 return ice_connection_state_;
765}
766
767PeerConnectionInterface::IceGatheringState
768PeerConnection::ice_gathering_state() {
769 return ice_gathering_state_;
770}
771
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000772rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000773PeerConnection::CreateDataChannel(
774 const std::string& label,
775 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100776 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700777
deadbeefab9b2d12015-10-14 11:33:11 -0700778 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000779
kwibergd1fe2812016-04-27 06:47:29 -0700780 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000781 if (config) {
782 internal_config.reset(new InternalDataChannelInit(*config));
783 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000784 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700785 InternalCreateDataChannel(label, internal_config.get()));
786 if (!channel.get()) {
787 return nullptr;
788 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000789
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000790 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
791 // the first SCTP DataChannel.
792 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
793 observer_->OnRenegotiationNeeded();
794 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000795
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 return DataChannelProxy::Create(signaling_thread(), channel.get());
797}
798
799void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
800 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100801 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -0700802
zhihuang1c378ed2017-08-17 14:10:50 -0700803 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
804 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
805 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
806 // compares the mandatory fields parsed with the mandatory fields added in the
807 // |constraints| and some downstream applications might create offers with
808 // mandatory fields which would not be parsed in the helper method. For
809 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
810 // |constraints| as a mandatory field but it is not parsed.
811 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000812
zhihuang1c378ed2017-08-17 14:10:50 -0700813 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000814}
815
816void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
817 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100818 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -0700819
nisse7ce109a2017-01-31 00:57:56 -0800820 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000821 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
822 return;
823 }
deadbeefab9b2d12015-10-14 11:33:11 -0700824
Steve Anton8d3444d2017-10-20 15:30:51 -0700825 if (IsClosed()) {
826 std::string error = "CreateOffer called when PeerConnection is closed.";
827 LOG(LS_ERROR) << error;
828 PostCreateSessionDescriptionFailure(observer, error);
829 return;
830 }
831
zhihuang1c378ed2017-08-17 14:10:50 -0700832 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700833 std::string error = "CreateOffer called with invalid options.";
834 LOG(LS_ERROR) << error;
835 PostCreateSessionDescriptionFailure(observer, error);
836 return;
837 }
838
zhihuang1c378ed2017-08-17 14:10:50 -0700839 cricket::MediaSessionOptions session_options;
840 GetOptionsForOffer(options, &session_options);
deadbeefab9b2d12015-10-14 11:33:11 -0700841 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842}
843
844void PeerConnection::CreateAnswer(
845 CreateSessionDescriptionObserver* observer,
846 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100847 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -0700848
nisse7ce109a2017-01-31 00:57:56 -0800849 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
851 return;
852 }
deadbeefab9b2d12015-10-14 11:33:11 -0700853
zhihuang1c378ed2017-08-17 14:10:50 -0700854 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
855 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
856 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700857 std::string error = "CreateAnswer called with invalid constraints.";
858 LOG(LS_ERROR) << error;
859 PostCreateSessionDescriptionFailure(observer, error);
860 return;
861 }
862
Steve Anton8d3444d2017-10-20 15:30:51 -0700863 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -0800864}
865
866void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
867 const RTCOfferAnswerOptions& options) {
868 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800869 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800870 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
871 return;
872 }
873
Steve Anton8d3444d2017-10-20 15:30:51 -0700874 if (IsClosed()) {
875 std::string error = "CreateAnswer called when PeerConnection is closed.";
876 LOG(LS_ERROR) << error;
877 PostCreateSessionDescriptionFailure(observer, error);
878 return;
879 }
880
881 if (session_->remote_description() &&
882 session_->remote_description()->type() !=
883 SessionDescriptionInterface::kOffer) {
884 std::string error = "CreateAnswer called without remote offer.";
885 LOG(LS_ERROR) << error;
886 PostCreateSessionDescriptionFailure(observer, error);
887 return;
888 }
889
htaa2a49d92016-03-04 02:51:39 -0800890 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -0700891 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800892
893 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000894}
895
896void PeerConnection::SetLocalDescription(
897 SetSessionDescriptionObserver* observer,
898 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100899 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -0800900 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
902 return;
903 }
904 if (!desc) {
905 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
906 return;
907 }
Steve Anton8d3444d2017-10-20 15:30:51 -0700908
909 // Takes the ownership of |desc| regardless of the result.
910 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
911
912 if (IsClosed()) {
913 std::string error = "Failed to set local " + desc->type() +
914 " sdp: Called in wrong state: STATE_CLOSED";
915 LOG(LS_ERROR) << error;
916 PostSetSessionDescriptionFailure(observer, error);
917 return;
918 }
919
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920 // Update stats here so that we have the most recent stats for tracks and
921 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000922 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923 std::string error;
Steve Anton8d3444d2017-10-20 15:30:51 -0700924 if (!session_->SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 PostSetSessionDescriptionFailure(observer, error);
926 return;
927 }
deadbeefab9b2d12015-10-14 11:33:11 -0700928
929 // If setting the description decided our SSL role, allocate any necessary
930 // SCTP sids.
931 rtc::SSLRole role;
932 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800933 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700934 AllocateSctpSids(role);
935 }
936
937 // Update state and SSRC of local MediaStreams and DataChannels based on the
938 // local session description.
939 const cricket::ContentInfo* audio_content =
940 GetFirstAudioContent(desc->description());
941 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800942 if (audio_content->rejected) {
943 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
944 } else {
945 const cricket::AudioContentDescription* audio_desc =
946 static_cast<const cricket::AudioContentDescription*>(
947 audio_content->description);
948 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
949 }
deadbeefab9b2d12015-10-14 11:33:11 -0700950 }
951
952 const cricket::ContentInfo* video_content =
953 GetFirstVideoContent(desc->description());
954 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800955 if (video_content->rejected) {
956 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
957 } else {
958 const cricket::VideoContentDescription* video_desc =
959 static_cast<const cricket::VideoContentDescription*>(
960 video_content->description);
961 UpdateLocalTracks(video_desc->streams(), video_desc->type());
962 }
deadbeefab9b2d12015-10-14 11:33:11 -0700963 }
964
965 const cricket::ContentInfo* data_content =
966 GetFirstDataContent(desc->description());
967 if (data_content) {
968 const cricket::DataContentDescription* data_desc =
969 static_cast<const cricket::DataContentDescription*>(
970 data_content->description);
971 if (rtc::starts_with(data_desc->protocol().data(),
972 cricket::kMediaProtocolRtpPrefix)) {
973 UpdateLocalRtpDataChannels(data_desc->streams());
974 }
975 }
976
977 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700978 signaling_thread()->Post(RTC_FROM_HERE, this,
979 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700980
deadbeef42a42632017-03-10 15:18:00 -0800981 // According to JSEP, after setLocalDescription, changing the candidate pool
982 // size is not allowed, and changing the set of ICE servers will not result
983 // in new candidates being gathered.
984 port_allocator_->FreezeCandidatePool();
985
deadbeefcbecd352015-09-23 11:50:27 -0700986 // MaybeStartGathering needs to be called after posting
987 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
988 // before signaling that SetLocalDescription completed.
989 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -0800990
991 if (desc->type() == SessionDescriptionInterface::kAnswer) {
992 // TODO(deadbeef): We already had to hop to the network thread for
993 // MaybeStartGathering...
994 network_thread()->Invoke<void>(
995 RTC_FROM_HERE,
996 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
997 port_allocator_.get()));
998 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999}
1000
1001void PeerConnection::SetRemoteDescription(
1002 SetSessionDescriptionObserver* observer,
1003 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001004 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001005 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001006 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1007 return;
1008 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 if (!desc) {
1010 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1011 return;
1012 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001013
1014 // Takes the ownership of |desc| regardless of the result.
1015 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1016
1017 if (IsClosed()) {
1018 std::string error = "Failed to set remote " + desc->type() +
1019 " sdp: Called in wrong state: STATE_CLOSED";
1020 LOG(LS_ERROR) << error;
1021 PostSetSessionDescriptionFailure(observer, error);
1022 return;
1023 }
1024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025 // Update stats here so that we have the most recent stats for tracks and
1026 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001027 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028 std::string error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001029 if (!session_->SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 PostSetSessionDescriptionFailure(observer, error);
1031 return;
1032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033
deadbeefab9b2d12015-10-14 11:33:11 -07001034 // If setting the description decided our SSL role, allocate any necessary
1035 // SCTP sids.
1036 rtc::SSLRole role;
1037 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001038 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001039 AllocateSctpSids(role);
1040 }
1041
1042 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001043 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1044 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1045 const cricket::AudioContentDescription* audio_desc =
1046 GetFirstAudioContentDescription(remote_desc);
1047 const cricket::VideoContentDescription* video_desc =
1048 GetFirstVideoContentDescription(remote_desc);
1049 const cricket::DataContentDescription* data_desc =
1050 GetFirstDataContentDescription(remote_desc);
1051
1052 // Check if the descriptions include streams, just in case the peer supports
1053 // MSID, but doesn't indicate so with "a=msid-semantic".
1054 if (remote_desc->msid_supported() ||
1055 (audio_desc && !audio_desc->streams().empty()) ||
1056 (video_desc && !video_desc->streams().empty())) {
1057 remote_peer_supports_msid_ = true;
1058 }
deadbeefab9b2d12015-10-14 11:33:11 -07001059
1060 // We wait to signal new streams until we finish processing the description,
1061 // since only at that point will new streams have all their tracks.
1062 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1063
Steve Anton8d3444d2017-10-20 15:30:51 -07001064 // TODO(steveanton): When removing RTP senders/receivers in response to a
1065 // rejected media section, there is some cleanup logic that expects the voice/
1066 // video channel to still be set. But in this method the voice/video channel
1067 // would have been destroyed by WebRtcSession's SetRemoteDescription method
1068 // above, so the cleanup that relies on them fails to run. This is hard to fix
1069 // with WebRtcSession and PeerConnection separated, but once the classes are
1070 // merged it will be easy to call RemoveTracks right before destroying the
1071 // voice/video channels.
1072
deadbeefab9b2d12015-10-14 11:33:11 -07001073 // Find all audio rtp streams and create corresponding remote AudioTracks
1074 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001075 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001076 if (audio_content->rejected) {
1077 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1078 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001079 bool default_audio_track_needed =
1080 !remote_peer_supports_msid_ &&
1081 MediaContentDirectionHasSend(audio_desc->direction());
1082 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1083 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001084 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001085 }
deadbeefab9b2d12015-10-14 11:33:11 -07001086 }
1087
1088 // Find all video rtp streams and create corresponding remote VideoTracks
1089 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001090 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001091 if (video_content->rejected) {
1092 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1093 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001094 bool default_video_track_needed =
1095 !remote_peer_supports_msid_ &&
1096 MediaContentDirectionHasSend(video_desc->direction());
1097 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1098 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001099 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001100 }
deadbeefab9b2d12015-10-14 11:33:11 -07001101 }
1102
1103 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001104 if (data_desc) {
1105 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001106 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001107 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001108 }
1109 }
1110
1111 // Iterate new_streams and notify the observer about new MediaStreams.
1112 for (size_t i = 0; i < new_streams->count(); ++i) {
1113 MediaStreamInterface* new_stream = new_streams->at(i);
1114 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001115 observer_->OnAddStream(
1116 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001117 }
1118
deadbeefbda7e0b2015-12-08 17:13:40 -08001119 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001120
1121 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001122 signaling_thread()->Post(RTC_FROM_HERE, this,
1123 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001124
1125 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1126 // TODO(deadbeef): We already had to hop to the network thread for
1127 // MaybeStartGathering...
1128 network_thread()->Invoke<void>(
1129 RTC_FROM_HERE,
1130 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1131 port_allocator_.get()));
1132 }
deadbeeffc648b62015-10-13 16:42:33 -07001133}
1134
deadbeef46c73892016-11-16 19:42:04 -08001135PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1136 return configuration_;
1137}
1138
deadbeef293e9262017-01-11 12:28:30 -08001139bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1140 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001141 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001142
1143 if (session_->local_description() &&
1144 configuration.ice_candidate_pool_size !=
1145 configuration_.ice_candidate_pool_size) {
1146 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1147 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001148 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001149 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001150
deadbeef293e9262017-01-11 12:28:30 -08001151 // The simplest (and most future-compatible) way to tell if the config was
1152 // modified in an invalid way is to copy each property we do support
1153 // modifying, then use operator==. There are far more properties we don't
1154 // support modifying than those we do, and more could be added.
1155 RTCConfiguration modified_config = configuration_;
1156 modified_config.servers = configuration.servers;
1157 modified_config.type = configuration.type;
1158 modified_config.ice_candidate_pool_size =
1159 configuration.ice_candidate_pool_size;
1160 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001161 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001162 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001163 if (configuration != modified_config) {
1164 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1165 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1166 }
1167
Steve Anton038834f2017-07-14 15:59:59 -07001168 // Validate the modified configuration.
1169 RTCError validate_error = ValidateConfiguration(modified_config);
1170 if (!validate_error.ok()) {
1171 return SafeSetError(std::move(validate_error), error);
1172 }
1173
deadbeef293e9262017-01-11 12:28:30 -08001174 // Note that this isn't possible through chromium, since it's an unsigned
1175 // short in WebIDL.
1176 if (configuration.ice_candidate_pool_size < 0 ||
1177 configuration.ice_candidate_pool_size > UINT16_MAX) {
1178 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1179 }
1180
1181 // Parse ICE servers before hopping to network thread.
1182 cricket::ServerAddresses stun_servers;
1183 std::vector<cricket::RelayServerConfig> turn_servers;
1184 RTCErrorType parse_error =
1185 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1186 if (parse_error != RTCErrorType::NONE) {
1187 return SafeSetError(parse_error, error);
1188 }
1189
1190 // In theory this shouldn't fail.
1191 if (!network_thread()->Invoke<bool>(
1192 RTC_FROM_HERE,
1193 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1194 stun_servers, turn_servers, modified_config.type,
1195 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001196 modified_config.prune_turn_ports,
1197 modified_config.turn_customizer))) {
deadbeef293e9262017-01-11 12:28:30 -08001198 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1199 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1200 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001201
deadbeefd1a38b52016-12-10 13:15:33 -08001202 // As described in JSEP, calling setConfiguration with new ICE servers or
1203 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1204 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001205 if (modified_config.servers != configuration_.servers ||
1206 modified_config.type != configuration_.type ||
1207 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001208 session_->SetNeedsIceRestartFlag();
1209 }
skvladd1f5fda2017-02-03 16:54:05 -08001210
1211 if (modified_config.ice_check_min_interval !=
1212 configuration_.ice_check_min_interval) {
1213 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1214 }
1215
deadbeef293e9262017-01-11 12:28:30 -08001216 configuration_ = modified_config;
1217 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001218}
1219
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220bool PeerConnection::AddIceCandidate(
1221 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001222 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001223 if (IsClosed()) {
1224 return false;
1225 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001226 return session_->ProcessIceMessage(ice_candidate);
1227}
1228
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001229bool PeerConnection::RemoveIceCandidates(
1230 const std::vector<cricket::Candidate>& candidates) {
1231 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1232 return session_->RemoveRemoteIceCandidates(candidates);
1233}
1234
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001235void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001236 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001237 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001238
1239 if (session_) {
Steve Antonba818672017-11-06 10:21:57 -08001240 session_->transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001241 }
1242
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001243 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001244 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001245 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001246 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001247 uma_observer_->IncrementEnumCounter(
1248 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1249 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001250 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001251 uma_observer_->IncrementEnumCounter(
1252 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1253 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001254 }
1255 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001256}
1257
zstein4b979802017-06-02 14:37:37 -07001258RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001259 if (!worker_thread()->IsCurrent()) {
1260 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001261 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1262 }
1263
1264 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1265 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1266 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1267 if (has_min && *bitrate.min_bitrate_bps < 0) {
1268 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1269 "min_bitrate_bps <= 0");
1270 }
1271 if (has_current) {
1272 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1274 "current_bitrate_bps < min_bitrate_bps");
1275 } else if (*bitrate.current_bitrate_bps < 0) {
1276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1277 "curent_bitrate_bps < 0");
1278 }
1279 }
1280 if (has_max) {
1281 if (has_current &&
1282 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1283 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1284 "max_bitrate_bps < current_bitrate_bps");
1285 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1286 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1287 "max_bitrate_bps < min_bitrate_bps");
1288 } else if (*bitrate.max_bitrate_bps < 0) {
1289 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1290 "max_bitrate_bps < 0");
1291 }
1292 }
1293
1294 Call::Config::BitrateConfigMask mask;
1295 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1296 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1297 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1298
1299 RTC_DCHECK(call_.get());
1300 call_->SetBitrateConfigMask(mask);
1301
1302 return RTCError::OK();
1303}
1304
Alex Narest78609d52017-10-20 10:37:47 +02001305void PeerConnection::SetBitrateAllocationStrategy(
1306 std::unique_ptr<rtc::BitrateAllocationStrategy>
1307 bitrate_allocation_strategy) {
1308 rtc::Thread* worker_thread = factory_->worker_thread();
1309 if (!worker_thread->IsCurrent()) {
1310 rtc::BitrateAllocationStrategy* strategy_raw =
1311 bitrate_allocation_strategy.release();
1312 auto functor = [this, strategy_raw]() {
1313 call_->SetBitrateAllocationStrategy(
1314 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1315 };
1316 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
1317 return;
1318 }
1319 RTC_DCHECK(call_.get());
1320 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
1321}
1322
henrika5f6bf242017-11-01 11:06:56 +01001323void PeerConnection::SetAudioPlayout(bool playout) {
1324 if (!worker_thread()->IsCurrent()) {
1325 worker_thread()->Invoke<void>(
1326 RTC_FROM_HERE,
1327 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
1328 return;
1329 }
1330 auto audio_state =
1331 factory_->channel_manager()->media_engine()->GetAudioState();
1332 audio_state->SetPlayout(playout);
1333}
1334
1335void PeerConnection::SetAudioRecording(bool recording) {
1336 if (!worker_thread()->IsCurrent()) {
1337 worker_thread()->Invoke<void>(
1338 RTC_FROM_HERE,
1339 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
1340 return;
1341 }
1342 auto audio_state =
1343 factory_->channel_manager()->media_engine()->GetAudioState();
1344 audio_state->SetRecording(recording);
1345}
1346
Steve Anton8c0f7a72017-10-03 10:03:10 -07001347std::unique_ptr<rtc::SSLCertificate>
1348PeerConnection::GetRemoteAudioSSLCertificate() {
1349 if (!session_) {
1350 return nullptr;
1351 }
1352 auto* voice_channel = session_->voice_channel();
1353 if (!voice_channel) {
1354 return nullptr;
1355 }
1356 return GetRemoteSSLCertificate(voice_channel->transport_name());
1357}
1358
ivoc14d5dbe2016-07-04 07:06:55 -07001359bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1360 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001361 // TODO(eladalon): It would be better to not allow negative values into PC.
1362 const size_t max_size = (max_size_bytes < 0)
1363 ? RtcEventLog::kUnlimitedOutput
1364 : rtc::saturated_cast<size_t>(max_size_bytes);
1365 return StartRtcEventLog(
1366 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
1367}
1368
1369bool PeerConnection::StartRtcEventLog(
1370 std::unique_ptr<RtcEventLogOutput> output) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001371 // TODO(eladalon): In C++14, this can be done with a lambda.
1372 struct Functor {
1373 bool operator()() { return pc->StartRtcEventLog_w(std::move(output)); }
1374 PeerConnection* const pc;
1375 std::unique_ptr<RtcEventLogOutput> output;
Elad Alon99c3fe52017-10-13 16:29:40 +02001376 };
Karl Wibergd6b48192017-10-16 23:01:06 +02001377 return worker_thread()->Invoke<bool>(RTC_FROM_HERE,
1378 Functor{this, std::move(output)});
ivoc14d5dbe2016-07-04 07:06:55 -07001379}
1380
1381void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001382 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001383 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1384}
1385
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386const SessionDescriptionInterface* PeerConnection::local_description() const {
1387 return session_->local_description();
1388}
1389
1390const SessionDescriptionInterface* PeerConnection::remote_description() const {
1391 return session_->remote_description();
1392}
1393
deadbeeffe4a8a42016-12-20 17:56:17 -08001394const SessionDescriptionInterface* PeerConnection::current_local_description()
1395 const {
1396 return session_->current_local_description();
1397}
1398
1399const SessionDescriptionInterface* PeerConnection::current_remote_description()
1400 const {
1401 return session_->current_remote_description();
1402}
1403
1404const SessionDescriptionInterface* PeerConnection::pending_local_description()
1405 const {
1406 return session_->pending_local_description();
1407}
1408
1409const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1410 const {
1411 return session_->pending_remote_description();
1412}
1413
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001415 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 // Update stats here so that we have the most recent stats for tracks and
1417 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001418 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001419
deadbeefd59daf82015-10-14 15:02:44 -07001420 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001421 network_thread()->Invoke<void>(
1422 RTC_FROM_HERE,
1423 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1424 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001425
Steve Anton978b8762017-09-29 12:15:02 -07001426 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001427 call_.reset();
1428 // The event log must outlive call (and any other object that uses it).
1429 event_log_.reset();
1430 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001431}
1432
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001433void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001434 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1436 SetSessionDescriptionMsg* param =
1437 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1438 param->observer->OnSuccess();
1439 delete param;
1440 break;
1441 }
1442 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1443 SetSessionDescriptionMsg* param =
1444 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1445 param->observer->OnFailure(param->error);
1446 delete param;
1447 break;
1448 }
deadbeefab9b2d12015-10-14 11:33:11 -07001449 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1450 CreateSessionDescriptionMsg* param =
1451 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1452 param->observer->OnFailure(param->error);
1453 delete param;
1454 break;
1455 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456 case MSG_GETSTATS: {
1457 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001458 StatsReports reports;
1459 stats_->GetStats(param->track, &reports);
1460 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 delete param;
1462 break;
1463 }
deadbeefbd292462015-12-14 18:15:29 -08001464 case MSG_FREE_DATACHANNELS: {
1465 sctp_data_channels_to_free_.clear();
1466 break;
1467 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001469 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470 break;
1471 }
1472}
1473
deadbeefab9b2d12015-10-14 11:33:11 -07001474void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001475 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001476 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001477 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1478 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001479 signaling_thread(),
1480 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1481 stream->AddTrack(
1482 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001483 receivers_.push_back(receiver);
1484 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1485 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1486 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487}
1488
deadbeefab9b2d12015-10-14 11:33:11 -07001489void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001490 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001491 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001492 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1493 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001494 signaling_thread(),
Steve Anton978b8762017-09-29 12:15:02 -07001495 new VideoRtpReceiver(track_id, worker_thread(), ssrc,
deadbeefe814a0d2017-02-25 18:15:09 -08001496 session_->video_channel()));
1497 stream->AddTrack(
1498 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001499 receivers_.push_back(receiver);
1500 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1501 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1502 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503}
1504
deadbeef70ab1a12015-09-28 16:53:55 -07001505// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1506// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07001507rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
1508 const std::string& track_id) {
perkjd61bf802016-03-24 03:16:19 -07001509 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001510 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001511 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001512 << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07001513 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07001514 }
Henrik Boström933d8b02017-10-10 10:05:16 -07001515 (*it)->internal()->Stop();
1516 rtc::scoped_refptr<RtpReceiverInterface> receiver = *it;
1517 receivers_.erase(it);
1518 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519}
1520
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001521void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1522 MediaStreamInterface* stream) {
1523 RTC_DCHECK(!IsClosed());
1524 auto sender = FindSenderForTrack(track);
1525 if (sender != senders_.end()) {
1526 // We already have a sender for this track, so just change the stream_id
1527 // so that it's correct in the next call to CreateOffer.
1528 (*sender)->internal()->set_stream_id(stream->label());
1529 return;
1530 }
1531
1532 // Normal case; we've never seen this track before.
1533 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1534 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1535 signaling_thread(),
Steve Anton8ffb9c32017-08-31 15:45:38 -07001536 new AudioRtpSender(track, {stream->label()},
1537 session_->voice_channel(), stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001538 senders_.push_back(new_sender);
1539 // If the sender has already been configured in SDP, we call SetSsrc,
1540 // which will connect the sender to the underlying transport. This can
1541 // occur if a local session description that contains the ID of the sender
1542 // is set before AddStream is called. It can also occur if the local
1543 // session description is not changed and RemoveStream is called, and
1544 // later AddStream is called again with the same stream.
1545 const TrackInfo* track_info =
1546 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1547 if (track_info) {
1548 new_sender->internal()->SetSsrc(track_info->ssrc);
1549 }
1550}
1551
1552// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1553// indefinitely, when we have unified plan SDP.
1554void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1555 MediaStreamInterface* stream) {
1556 RTC_DCHECK(!IsClosed());
1557 auto sender = FindSenderForTrack(track);
1558 if (sender == senders_.end()) {
1559 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1560 << " doesn't exist.";
1561 return;
1562 }
1563 (*sender)->internal()->Stop();
1564 senders_.erase(sender);
1565}
1566
1567void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1568 MediaStreamInterface* stream) {
1569 RTC_DCHECK(!IsClosed());
1570 auto sender = FindSenderForTrack(track);
1571 if (sender != senders_.end()) {
1572 // We already have a sender for this track, so just change the stream_id
1573 // so that it's correct in the next call to CreateOffer.
1574 (*sender)->internal()->set_stream_id(stream->label());
1575 return;
1576 }
1577
1578 // Normal case; we've never seen this track before.
1579 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1580 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton8ffb9c32017-08-31 15:45:38 -07001581 signaling_thread(), new VideoRtpSender(track, {stream->label()},
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001582 session_->video_channel()));
1583 senders_.push_back(new_sender);
1584 const TrackInfo* track_info =
1585 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1586 if (track_info) {
1587 new_sender->internal()->SetSsrc(track_info->ssrc);
1588 }
1589}
1590
1591void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1592 MediaStreamInterface* stream) {
1593 RTC_DCHECK(!IsClosed());
1594 auto sender = FindSenderForTrack(track);
1595 if (sender == senders_.end()) {
1596 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1597 << " doesn't exist.";
1598 return;
1599 }
1600 (*sender)->internal()->Stop();
1601 senders_.erase(sender);
1602}
1603
Steve Antonba818672017-11-06 10:21:57 -08001604void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001605 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08001606 if (ice_connection_state_ == new_state) {
1607 return;
1608 }
1609
deadbeefcbecd352015-09-23 11:50:27 -07001610 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08001611 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001612 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001613 return;
1614 }
Steve Antonba818672017-11-06 10:21:57 -08001615
1616 LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
1617 << " => " << new_state;
1618 RTC_DCHECK(ice_connection_state_ !=
1619 PeerConnectionInterface::kIceConnectionClosed);
1620
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001622 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001623}
1624
1625void PeerConnection::OnIceGatheringChange(
1626 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001627 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001628 if (IsClosed()) {
1629 return;
1630 }
1631 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001632 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001633}
1634
jbauch81bf7b02017-03-25 08:31:12 -07001635void PeerConnection::OnIceCandidate(
1636 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001637 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001638 if (IsClosed()) {
1639 return;
1640 }
jbauch81bf7b02017-03-25 08:31:12 -07001641 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001642}
1643
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001644void PeerConnection::OnIceCandidatesRemoved(
1645 const std::vector<cricket::Candidate>& candidates) {
1646 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001647 if (IsClosed()) {
1648 return;
1649 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001650 observer_->OnIceCandidatesRemoved(candidates);
1651}
1652
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001653void PeerConnection::ChangeSignalingState(
1654 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08001655 RTC_DCHECK(signaling_thread()->IsCurrent());
1656 if (signaling_state_ == signaling_state) {
1657 return;
1658 }
1659 LOG(LS_INFO) << "Session: " << session_id()
1660 << " Old state: " << GetSignalingStateString(signaling_state_)
1661 << " New state: " << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001662 signaling_state_ = signaling_state;
1663 if (signaling_state == kClosed) {
1664 ice_connection_state_ = kIceConnectionClosed;
1665 observer_->OnIceConnectionChange(ice_connection_state_);
1666 if (ice_gathering_state_ != kIceGatheringComplete) {
1667 ice_gathering_state_ = kIceGatheringComplete;
1668 observer_->OnIceGatheringChange(ice_gathering_state_);
1669 }
1670 }
1671 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672}
1673
deadbeefeb459812015-12-15 19:24:43 -08001674void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1675 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001676 if (IsClosed()) {
1677 return;
1678 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001679 AddAudioTrack(track, stream);
1680 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001681}
1682
deadbeefeb459812015-12-15 19:24:43 -08001683void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1684 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001685 if (IsClosed()) {
1686 return;
1687 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001688 RemoveAudioTrack(track, stream);
1689 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001690}
1691
1692void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1693 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001694 if (IsClosed()) {
1695 return;
1696 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001697 AddVideoTrack(track, stream);
1698 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001699}
1700
1701void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1702 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001703 if (IsClosed()) {
1704 return;
1705 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001706 RemoveVideoTrack(track, stream);
1707 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001708}
1709
deadbeefab9b2d12015-10-14 11:33:11 -07001710void PeerConnection::PostSetSessionDescriptionFailure(
1711 SetSessionDescriptionObserver* observer,
1712 const std::string& error) {
1713 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1714 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001715 signaling_thread()->Post(RTC_FROM_HERE, this,
1716 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001717}
1718
1719void PeerConnection::PostCreateSessionDescriptionFailure(
1720 CreateSessionDescriptionObserver* observer,
1721 const std::string& error) {
1722 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1723 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001724 signaling_thread()->Post(RTC_FROM_HERE, this,
1725 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001726}
1727
zhihuang1c378ed2017-08-17 14:10:50 -07001728void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001729 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1730 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001731 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1732
1733 // Figure out transceiver directional preferences.
1734 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1735 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1736
1737 // By default, generate sendrecv/recvonly m= sections.
1738 bool recv_audio = true;
1739 bool recv_video = true;
1740
1741 // By default, only offer a new m= section if we have media to send with it.
1742 bool offer_new_audio_description = send_audio;
1743 bool offer_new_video_description = send_video;
1744 bool offer_new_data_description = HasDataChannels();
1745
1746 // The "offer_to_receive_X" options allow those defaults to be overridden.
1747 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1748 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1749 offer_new_audio_description =
1750 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1751 }
1752 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1753 recv_video = (rtc_options.offer_to_receive_video > 0);
1754 offer_new_video_description =
1755 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1756 }
1757
1758 rtc::Optional<size_t> audio_index;
1759 rtc::Optional<size_t> video_index;
1760 rtc::Optional<size_t> data_index;
1761 // If a current description exists, generate m= sections in the same order,
1762 // using the first audio/video/data section that appears and rejecting
1763 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001764 if (session_->local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07001765 GenerateMediaDescriptionOptions(
1766 session_->local_description(),
1767 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1768 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1769 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001770 }
1771
zhihuang1c378ed2017-08-17 14:10:50 -07001772 // Add audio/video/data m= sections to the end if needed.
1773 if (!audio_index && offer_new_audio_description) {
1774 session_options->media_description_options.push_back(
1775 cricket::MediaDescriptionOptions(
1776 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1777 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1778 audio_index = rtc::Optional<size_t>(
1779 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001780 }
zhihuang1c378ed2017-08-17 14:10:50 -07001781 if (!video_index && offer_new_video_description) {
1782 session_options->media_description_options.push_back(
1783 cricket::MediaDescriptionOptions(
1784 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1785 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1786 video_index = rtc::Optional<size_t>(
1787 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001788 }
zhihuang1c378ed2017-08-17 14:10:50 -07001789 if (!data_index && offer_new_data_description) {
1790 session_options->media_description_options.push_back(
1791 cricket::MediaDescriptionOptions(
1792 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1793 cricket::RtpTransceiverDirection(true, true), false));
1794 data_index = rtc::Optional<size_t>(
1795 session_options->media_description_options.size() - 1);
1796 }
1797
1798 cricket::MediaDescriptionOptions* audio_media_description_options =
1799 !audio_index ? nullptr
1800 : &session_options->media_description_options[*audio_index];
1801 cricket::MediaDescriptionOptions* video_media_description_options =
1802 !video_index ? nullptr
1803 : &session_options->media_description_options[*video_index];
1804 cricket::MediaDescriptionOptions* data_media_description_options =
1805 !data_index ? nullptr
1806 : &session_options->media_description_options[*data_index];
1807
1808 // Apply ICE restart flag and renomination flag.
1809 for (auto& options : session_options->media_description_options) {
1810 options.transport_options.ice_restart = rtc_options.ice_restart;
1811 options.transport_options.enable_ice_renomination =
1812 configuration_.enable_ice_renomination;
1813 }
1814
1815 AddRtpSenderOptions(senders_, audio_media_description_options,
1816 video_media_description_options);
1817 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001818
zhihuang9763d562016-08-05 11:14:50 -07001819 // Intentionally unset the data channel type for RTP data channel with the
1820 // second condition. Otherwise the RTP data channels would be successfully
1821 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1822 // when building with chromium. We want to leave RTP data channels broken, so
1823 // people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001824 if (!rtp_data_channels_.empty() ||
1825 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001826 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001827 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001828
1829 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001830 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001831}
1832
zhihuang1c378ed2017-08-17 14:10:50 -07001833void PeerConnection::GetOptionsForAnswer(
1834 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001835 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001836 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001837
zhihuang1c378ed2017-08-17 14:10:50 -07001838 // Figure out transceiver directional preferences.
1839 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1840 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1841
1842 // By default, generate sendrecv/recvonly m= sections. The direction is also
1843 // restricted by the direction in the offer.
1844 bool recv_audio = true;
1845 bool recv_video = true;
1846
1847 // The "offer_to_receive_X" options allow those defaults to be overridden.
1848 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1849 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001850 }
zhihuang1c378ed2017-08-17 14:10:50 -07001851 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1852 recv_video = (rtc_options.offer_to_receive_video > 0);
1853 }
1854
1855 rtc::Optional<size_t> audio_index;
1856 rtc::Optional<size_t> video_index;
1857 rtc::Optional<size_t> data_index;
zhihuang141aacb2017-08-29 13:23:53 -07001858 if (session_->remote_description()) {
1859 // The pending remote description should be an offer.
1860 RTC_DCHECK(session_->remote_description()->type() ==
1861 SessionDescriptionInterface::kOffer);
1862 // Generate m= sections that match those in the offer.
1863 // Note that mediasession.cc will handle intersection our preferred
1864 // direction with the offered direction.
1865 GenerateMediaDescriptionOptions(
1866 session_->remote_description(),
1867 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1868 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1869 &video_index, &data_index, session_options);
1870 }
zhihuang1c378ed2017-08-17 14:10:50 -07001871
1872 cricket::MediaDescriptionOptions* audio_media_description_options =
1873 !audio_index ? nullptr
1874 : &session_options->media_description_options[*audio_index];
1875 cricket::MediaDescriptionOptions* video_media_description_options =
1876 !video_index ? nullptr
1877 : &session_options->media_description_options[*video_index];
1878 cricket::MediaDescriptionOptions* data_media_description_options =
1879 !data_index ? nullptr
1880 : &session_options->media_description_options[*data_index];
1881
1882 // Apply ICE renomination flag.
1883 for (auto& options : session_options->media_description_options) {
1884 options.transport_options.enable_ice_renomination =
1885 configuration_.enable_ice_renomination;
1886 }
1887
1888 AddRtpSenderOptions(senders_, audio_media_description_options,
1889 video_media_description_options);
1890 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
1891
zhihuang9763d562016-08-05 11:14:50 -07001892 // Intentionally unset the data channel type for RTP data channel. Otherwise
1893 // the RTP data channels would be successfully negotiated by default and the
1894 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1895 // We want to leave RTP data channels broken, so people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001896 if (!rtp_data_channels_.empty() ||
1897 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001898 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001899 }
zhihuangaf388472016-11-02 16:49:48 -07001900
zhihuang1c378ed2017-08-17 14:10:50 -07001901 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001902 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001903}
1904
zhihuang1c378ed2017-08-17 14:10:50 -07001905void PeerConnection::GenerateMediaDescriptionOptions(
1906 const SessionDescriptionInterface* session_desc,
1907 cricket::RtpTransceiverDirection audio_direction,
1908 cricket::RtpTransceiverDirection video_direction,
1909 rtc::Optional<size_t>* audio_index,
1910 rtc::Optional<size_t>* video_index,
1911 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08001912 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001913 for (const cricket::ContentInfo& content :
1914 session_desc->description()->contents()) {
1915 if (IsAudioContent(&content)) {
1916 // If we already have an audio m= section, reject this extra one.
1917 if (*audio_index) {
1918 session_options->media_description_options.push_back(
1919 cricket::MediaDescriptionOptions(
1920 cricket::MEDIA_TYPE_AUDIO, content.name,
1921 cricket::RtpTransceiverDirection(false, false), true));
1922 } else {
1923 session_options->media_description_options.push_back(
1924 cricket::MediaDescriptionOptions(
1925 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
1926 !audio_direction.send && !audio_direction.recv));
1927 *audio_index = rtc::Optional<size_t>(
1928 session_options->media_description_options.size() - 1);
1929 }
1930 } else if (IsVideoContent(&content)) {
1931 // If we already have an video m= section, reject this extra one.
1932 if (*video_index) {
1933 session_options->media_description_options.push_back(
1934 cricket::MediaDescriptionOptions(
1935 cricket::MEDIA_TYPE_VIDEO, content.name,
1936 cricket::RtpTransceiverDirection(false, false), true));
1937 } else {
1938 session_options->media_description_options.push_back(
1939 cricket::MediaDescriptionOptions(
1940 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1941 !video_direction.send && !video_direction.recv));
1942 *video_index = rtc::Optional<size_t>(
1943 session_options->media_description_options.size() - 1);
1944 }
1945 } else {
1946 RTC_DCHECK(IsDataContent(&content));
1947 // If we already have an data m= section, reject this extra one.
1948 if (*data_index) {
1949 session_options->media_description_options.push_back(
1950 cricket::MediaDescriptionOptions(
1951 cricket::MEDIA_TYPE_DATA, content.name,
1952 cricket::RtpTransceiverDirection(false, false), true));
1953 } else {
1954 session_options->media_description_options.push_back(
1955 cricket::MediaDescriptionOptions(
1956 cricket::MEDIA_TYPE_DATA, content.name,
1957 // Direction for data sections is meaningless, but legacy
1958 // endpoints might expect sendrecv.
1959 cricket::RtpTransceiverDirection(true, true), false));
1960 *data_index = rtc::Optional<size_t>(
1961 session_options->media_description_options.size() - 1);
1962 }
1963 }
htaa2a49d92016-03-04 02:51:39 -08001964 }
deadbeefab9b2d12015-10-14 11:33:11 -07001965}
1966
deadbeeffaac4972015-11-12 15:33:07 -08001967void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1968 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001969 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1970 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001971}
1972
deadbeefab9b2d12015-10-14 11:33:11 -07001973void PeerConnection::UpdateRemoteStreamsList(
1974 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001975 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001976 cricket::MediaType media_type,
1977 StreamCollection* new_streams) {
1978 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1979
1980 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001981 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001982 auto track_it = current_tracks->begin();
1983 while (track_it != current_tracks->end()) {
1984 const TrackInfo& info = *track_it;
1985 const cricket::StreamParams* params =
1986 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001987 bool track_exists = params && params->id == info.track_id;
1988 // If this is a default track, and we still need it, don't remove it.
1989 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1990 track_exists) {
1991 ++track_it;
1992 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001993 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1994 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001995 }
1996 }
1997
1998 // Find new and active tracks.
1999 for (const cricket::StreamParams& params : streams) {
2000 // The sync_label is the MediaStream label and the |stream.id| is the
2001 // track id.
2002 const std::string& stream_label = params.sync_label;
2003 const std::string& track_id = params.id;
2004 uint32_t ssrc = params.first_ssrc();
2005
2006 rtc::scoped_refptr<MediaStreamInterface> stream =
2007 remote_streams_->find(stream_label);
2008 if (!stream) {
2009 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002010 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2011 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002012 remote_streams_->AddStream(stream);
2013 new_streams->AddStream(stream);
2014 }
2015
2016 const TrackInfo* track_info =
2017 FindTrackInfo(*current_tracks, stream_label, track_id);
2018 if (!track_info) {
2019 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2020 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2021 }
2022 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002023
2024 // Add default track if necessary.
2025 if (default_track_needed) {
2026 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2027 remote_streams_->find(kDefaultStreamLabel);
2028 if (!default_stream) {
2029 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002030 default_stream = MediaStreamProxy::Create(
2031 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002032 remote_streams_->AddStream(default_stream);
2033 new_streams->AddStream(default_stream);
2034 }
2035 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2036 ? kDefaultAudioTrackLabel
2037 : kDefaultVideoTrackLabel;
2038 const TrackInfo* default_track_info =
2039 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2040 if (!default_track_info) {
2041 current_tracks->push_back(
2042 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2043 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2044 }
2045 }
deadbeefab9b2d12015-10-14 11:33:11 -07002046}
2047
2048void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2049 const std::string& track_id,
2050 uint32_t ssrc,
2051 cricket::MediaType media_type) {
2052 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2053
2054 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002055 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002056 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002057 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002058 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002059 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002060 }
2061}
2062
2063void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2064 const std::string& track_id,
2065 cricket::MediaType media_type) {
2066 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2067
Henrik Boström933d8b02017-10-10 10:05:16 -07002068 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002069 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002070 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2071 // will be notified which will end the AudioRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002072 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002073 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2074 stream->FindAudioTrack(track_id);
2075 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002076 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002077 }
2078 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002079 // Stopping or destroying a VideoRtpReceiver will end the
2080 // VideoRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002081 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002082 rtc::scoped_refptr<VideoTrackInterface> video_track =
2083 stream->FindVideoTrack(track_id);
2084 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002085 // There's no guarantee the track is still available, e.g. the track may
2086 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002087 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002088 }
2089 } else {
nisseede5da42017-01-12 05:15:36 -08002090 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002091 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002092 if (receiver) {
2093 observer_->OnRemoveTrack(receiver);
2094 }
deadbeefab9b2d12015-10-14 11:33:11 -07002095}
2096
2097void PeerConnection::UpdateEndedRemoteMediaStreams() {
2098 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2099 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2100 MediaStreamInterface* stream = remote_streams_->at(i);
2101 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2102 streams_to_remove.push_back(stream);
2103 }
2104 }
2105
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002106 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002107 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002108 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002109 }
2110}
2111
deadbeefab9b2d12015-10-14 11:33:11 -07002112void PeerConnection::UpdateLocalTracks(
2113 const std::vector<cricket::StreamParams>& streams,
2114 cricket::MediaType media_type) {
2115 TrackInfos* current_tracks = GetLocalTracks(media_type);
2116
2117 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2118 // don't match the new StreamParam.
2119 TrackInfos::iterator track_it = current_tracks->begin();
2120 while (track_it != current_tracks->end()) {
2121 const TrackInfo& info = *track_it;
2122 const cricket::StreamParams* params =
2123 cricket::GetStreamBySsrc(streams, info.ssrc);
2124 if (!params || params->id != info.track_id ||
2125 params->sync_label != info.stream_label) {
2126 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2127 media_type);
2128 track_it = current_tracks->erase(track_it);
2129 } else {
2130 ++track_it;
2131 }
2132 }
2133
2134 // Find new and active tracks.
2135 for (const cricket::StreamParams& params : streams) {
2136 // The sync_label is the MediaStream label and the |stream.id| is the
2137 // track id.
2138 const std::string& stream_label = params.sync_label;
2139 const std::string& track_id = params.id;
2140 uint32_t ssrc = params.first_ssrc();
2141 const TrackInfo* track_info =
2142 FindTrackInfo(*current_tracks, stream_label, track_id);
2143 if (!track_info) {
2144 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2145 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2146 }
2147 }
2148}
2149
2150void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2151 const std::string& track_id,
2152 uint32_t ssrc,
2153 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002154 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002155 if (!sender) {
2156 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2157 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002158 return;
2159 }
2160
deadbeeffac06552015-11-25 11:26:01 -08002161 if (sender->media_type() != media_type) {
2162 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2163 << " description with an unexpected media type.";
2164 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002165 }
deadbeeffac06552015-11-25 11:26:01 -08002166
2167 sender->set_stream_id(stream_label);
2168 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002169}
2170
2171void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2172 const std::string& track_id,
2173 uint32_t ssrc,
2174 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002175 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002176 if (!sender) {
2177 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002178 // SessionDescriptions has been renegotiated.
2179 return;
2180 }
deadbeeffac06552015-11-25 11:26:01 -08002181
2182 // A sender has been removed from the SessionDescription but it's still
2183 // associated with the PeerConnection. This only occurs if the SDP doesn't
2184 // match with the calls to CreateSender, AddStream and RemoveStream.
2185 if (sender->media_type() != media_type) {
2186 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2187 << " description with an unexpected media type.";
2188 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002189 }
deadbeeffac06552015-11-25 11:26:01 -08002190
2191 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002192}
2193
2194void PeerConnection::UpdateLocalRtpDataChannels(
2195 const cricket::StreamParamsVec& streams) {
2196 std::vector<std::string> existing_channels;
2197
2198 // Find new and active data channels.
2199 for (const cricket::StreamParams& params : streams) {
2200 // |it->sync_label| is actually the data channel label. The reason is that
2201 // we use the same naming of data channels as we do for
2202 // MediaStreams and Tracks.
2203 // For MediaStreams, the sync_label is the MediaStream label and the
2204 // track label is the same as |streamid|.
2205 const std::string& channel_label = params.sync_label;
2206 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002207 if (data_channel_it == rtp_data_channels_.end()) {
2208 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002209 continue;
2210 }
2211 // Set the SSRC the data channel should use for sending.
2212 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2213 existing_channels.push_back(data_channel_it->first);
2214 }
2215
2216 UpdateClosingRtpDataChannels(existing_channels, true);
2217}
2218
2219void PeerConnection::UpdateRemoteRtpDataChannels(
2220 const cricket::StreamParamsVec& streams) {
2221 std::vector<std::string> existing_channels;
2222
2223 // Find new and active data channels.
2224 for (const cricket::StreamParams& params : streams) {
2225 // The data channel label is either the mslabel or the SSRC if the mslabel
2226 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2227 std::string label = params.sync_label.empty()
2228 ? rtc::ToString(params.first_ssrc())
2229 : params.sync_label;
2230 auto data_channel_it = rtp_data_channels_.find(label);
2231 if (data_channel_it == rtp_data_channels_.end()) {
2232 // This is a new data channel.
2233 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2234 } else {
2235 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2236 }
2237 existing_channels.push_back(label);
2238 }
2239
2240 UpdateClosingRtpDataChannels(existing_channels, false);
2241}
2242
2243void PeerConnection::UpdateClosingRtpDataChannels(
2244 const std::vector<std::string>& active_channels,
2245 bool is_local_update) {
2246 auto it = rtp_data_channels_.begin();
2247 while (it != rtp_data_channels_.end()) {
2248 DataChannel* data_channel = it->second;
2249 if (std::find(active_channels.begin(), active_channels.end(),
2250 data_channel->label()) != active_channels.end()) {
2251 ++it;
2252 continue;
2253 }
2254
2255 if (is_local_update) {
2256 data_channel->SetSendSsrc(0);
2257 } else {
2258 data_channel->RemotePeerRequestClose();
2259 }
2260
2261 if (data_channel->state() == DataChannel::kClosed) {
2262 rtp_data_channels_.erase(it);
2263 it = rtp_data_channels_.begin();
2264 } else {
2265 ++it;
2266 }
2267 }
2268}
2269
2270void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2271 uint32_t remote_ssrc) {
2272 rtc::scoped_refptr<DataChannel> channel(
2273 InternalCreateDataChannel(label, nullptr));
2274 if (!channel.get()) {
2275 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2276 << "CreateDataChannel failed.";
2277 return;
2278 }
2279 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002280 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2281 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002282 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002283}
2284
2285rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2286 const std::string& label,
2287 const InternalDataChannelInit* config) {
2288 if (IsClosed()) {
2289 return nullptr;
2290 }
2291 if (session_->data_channel_type() == cricket::DCT_NONE) {
2292 LOG(LS_ERROR)
2293 << "InternalCreateDataChannel: Data is not supported in this call.";
2294 return nullptr;
2295 }
2296 InternalDataChannelInit new_config =
2297 config ? (*config) : InternalDataChannelInit();
2298 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2299 if (new_config.id < 0) {
2300 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002301 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002302 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2303 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2304 return nullptr;
2305 }
2306 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2307 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2308 << "because the id is already in use or out of range.";
2309 return nullptr;
2310 }
2311 }
2312
2313 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
Steve Anton978b8762017-09-29 12:15:02 -07002314 session_, session_->data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002315 if (!channel) {
2316 sid_allocator_.ReleaseSid(new_config.id);
2317 return nullptr;
2318 }
2319
2320 if (channel->data_channel_type() == cricket::DCT_RTP) {
2321 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2322 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2323 << " already exists.";
2324 return nullptr;
2325 }
2326 rtp_data_channels_[channel->label()] = channel;
2327 } else {
2328 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2329 sctp_data_channels_.push_back(channel);
2330 channel->SignalClosed.connect(this,
2331 &PeerConnection::OnSctpDataChannelClosed);
2332 }
2333
hbos82ebe022016-11-14 01:41:09 -08002334 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002335 return channel;
2336}
2337
2338bool PeerConnection::HasDataChannels() const {
2339 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2340}
2341
2342void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2343 for (const auto& channel : sctp_data_channels_) {
2344 if (channel->id() < 0) {
2345 int sid;
2346 if (!sid_allocator_.AllocateSid(role, &sid)) {
2347 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2348 continue;
2349 }
2350 channel->SetSctpSid(sid);
2351 }
2352 }
2353}
2354
2355void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002356 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002357 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2358 ++it) {
2359 if (it->get() == channel) {
2360 if (channel->id() >= 0) {
2361 sid_allocator_.ReleaseSid(channel->id());
2362 }
deadbeefbd292462015-12-14 18:15:29 -08002363 // Since this method is triggered by a signal from the DataChannel,
2364 // we can't free it directly here; we need to free it asynchronously.
2365 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002366 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002367 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2368 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002369 return;
2370 }
2371 }
2372}
2373
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002374void PeerConnection::OnVoiceChannelCreated() {
2375 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2376 session_->voice_channel(), senders_, receivers_,
2377 cricket::MEDIA_TYPE_AUDIO);
2378}
2379
deadbeefab9b2d12015-10-14 11:33:11 -07002380void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002381 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2382 cricket::VoiceChannel>(
2383 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2384}
2385
2386void PeerConnection::OnVideoChannelCreated() {
2387 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2388 session_->video_channel(), senders_, receivers_,
2389 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002390}
2391
2392void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002393 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2394 cricket::VideoChannel>(
2395 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002396}
2397
2398void PeerConnection::OnDataChannelCreated() {
2399 for (const auto& channel : sctp_data_channels_) {
2400 channel->OnTransportChannelCreated();
2401 }
2402}
2403
2404void PeerConnection::OnDataChannelDestroyed() {
2405 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2406 // DataChannel may callback to us and try to modify the list.
2407 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2408 temp_rtp_dcs.swap(rtp_data_channels_);
2409 for (const auto& kv : temp_rtp_dcs) {
2410 kv.second->OnTransportChannelDestroyed();
2411 }
2412
2413 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2414 temp_sctp_dcs.swap(sctp_data_channels_);
2415 for (const auto& channel : temp_sctp_dcs) {
2416 channel->OnTransportChannelDestroyed();
2417 }
2418}
2419
2420void PeerConnection::OnDataChannelOpenMessage(
2421 const std::string& label,
2422 const InternalDataChannelInit& config) {
2423 rtc::scoped_refptr<DataChannel> channel(
2424 InternalCreateDataChannel(label, &config));
2425 if (!channel.get()) {
2426 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2427 return;
2428 }
2429
deadbeefa601f5c2016-06-06 14:27:39 -07002430 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2431 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002432 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002433}
2434
zhihuang1c378ed2017-08-17 14:10:50 -07002435bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2436 return std::find_if(
2437 senders_.begin(), senders_.end(),
2438 [type](const rtc::scoped_refptr<
2439 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2440 return sender->media_type() == type;
2441 }) != senders_.end();
2442}
2443
deadbeefa601f5c2016-06-06 14:27:39 -07002444RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2445 auto it = std::find_if(
2446 senders_.begin(), senders_.end(),
2447 [id](const rtc::scoped_refptr<
2448 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2449 return sender->id() == id;
2450 });
2451 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002452}
2453
deadbeefa601f5c2016-06-06 14:27:39 -07002454std::vector<
2455 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002456PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2457 return std::find_if(
2458 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002459 [track](const rtc::scoped_refptr<
2460 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002461 return sender->track() == track;
2462 });
2463}
2464
deadbeefa601f5c2016-06-06 14:27:39 -07002465std::vector<rtc::scoped_refptr<
2466 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002467PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002468 return std::find_if(
2469 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002470 [track_id](const rtc::scoped_refptr<
2471 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002472 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002473 });
2474}
2475
deadbeefab9b2d12015-10-14 11:33:11 -07002476PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2477 cricket::MediaType media_type) {
2478 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2479 media_type == cricket::MEDIA_TYPE_VIDEO);
2480 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2481 : &remote_video_tracks_;
2482}
2483
2484PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2485 cricket::MediaType media_type) {
2486 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2487 media_type == cricket::MEDIA_TYPE_VIDEO);
2488 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2489 : &local_video_tracks_;
2490}
2491
2492const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2493 const PeerConnection::TrackInfos& infos,
2494 const std::string& stream_label,
2495 const std::string track_id) const {
2496 for (const TrackInfo& track_info : infos) {
2497 if (track_info.stream_label == stream_label &&
2498 track_info.track_id == track_id) {
2499 return &track_info;
2500 }
2501 }
2502 return nullptr;
2503}
2504
2505DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2506 for (const auto& channel : sctp_data_channels_) {
2507 if (channel->id() == sid) {
2508 return channel;
2509 }
2510 }
2511 return nullptr;
2512}
2513
deadbeef91dd5672016-05-18 16:55:30 -07002514bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002515 const RTCConfiguration& configuration) {
2516 cricket::ServerAddresses stun_servers;
2517 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002518 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2519 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002520 return false;
2521 }
2522
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002523 port_allocator_->Initialize();
2524
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002525 // To handle both internal and externally created port allocator, we will
2526 // enable BUNDLE here.
2527 int portallocator_flags = port_allocator_->flags();
2528 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002529 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2530 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002531 // If the disable-IPv6 flag was specified, we'll not override it
2532 // by experiment.
2533 if (configuration.disable_ipv6) {
2534 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002535 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2536 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002537 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2538 }
2539
zhihuangb09b3f92017-03-07 14:40:51 -08002540 if (configuration.disable_ipv6_on_wifi) {
2541 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2542 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2543 }
2544
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002545 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2546 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2547 LOG(LS_INFO) << "TCP candidates are disabled.";
2548 }
2549
honghaiz60347052016-05-31 18:29:12 -07002550 if (configuration.candidate_network_policy ==
2551 kCandidateNetworkPolicyLowCost) {
2552 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2553 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2554 }
2555
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002556 port_allocator_->set_flags(portallocator_flags);
2557 // No step delay is used while allocating ports.
2558 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2559 port_allocator_->set_candidate_filter(
2560 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002561 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002562
2563 // Call this last since it may create pooled allocator sessions using the
2564 // properties set above.
2565 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002566 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002567 configuration.prune_turn_ports,
2568 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002569 return true;
2570}
2571
deadbeef91dd5672016-05-18 16:55:30 -07002572bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002573 const cricket::ServerAddresses& stun_servers,
2574 const std::vector<cricket::RelayServerConfig>& turn_servers,
2575 IceTransportsType type,
2576 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002577 bool prune_turn_ports,
2578 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002579 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002580 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002581 // Call this last since it may create pooled allocator sessions using the
2582 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002583 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02002584 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
2585 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002586}
2587
Steve Antonba818672017-11-06 10:21:57 -08002588cricket::ChannelManager* PeerConnection::channel_manager() const {
2589 return factory_->channel_manager();
2590}
2591
2592MetricsObserverInterface* PeerConnection::metrics_observer() const {
2593 return uma_observer_;
2594}
2595
Elad Alon99c3fe52017-10-13 16:29:40 +02002596bool PeerConnection::StartRtcEventLog_w(
2597 std::unique_ptr<RtcEventLogOutput> output) {
zhihuang77985012017-02-07 15:45:16 -08002598 if (!event_log_) {
2599 return false;
2600 }
Elad Alon99c3fe52017-10-13 16:29:40 +02002601 return event_log_->StartLogging(std::move(output));
ivoc14d5dbe2016-07-04 07:06:55 -07002602}
2603
2604void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002605 if (event_log_) {
2606 event_log_->StopLogging();
2607 }
ivoc14d5dbe2016-07-04 07:06:55 -07002608}
nisseeaabdf62017-05-05 02:23:02 -07002609
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610} // namespace webrtc