blob: 4be3c7d458339da533101df22ec192a36bc72ed2 [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
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
nissec80e7412017-01-11 05:56:46 -080035#include "webrtc/base/checks.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000036#include "webrtc/base/logging.h"
37#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070038#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010039#include "webrtc/base/trace_event.h"
ossuf515ab82016-12-07 04:52:58 -080040#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070041#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
deadbeef953c2ce2017-01-09 14:53:41 -080042#include "webrtc/media/sctp/sctptransport.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010043#include "webrtc/pc/channelmanager.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010044#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045
46namespace {
47
deadbeefab9b2d12015-10-14 11:33:11 -070048using webrtc::DataChannel;
49using webrtc::MediaConstraintsInterface;
50using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080052using webrtc::RTCError;
53using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070054using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080055using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070056using webrtc::RtpSenderProxy;
57using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070058using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059
deadbeefab9b2d12015-10-14 11:33:11 -070060static const char kDefaultStreamLabel[] = "default";
61static const char kDefaultAudioTrackLabel[] = "defaulta0";
62static const char kDefaultVideoTrackLabel[] = "defaultv0";
63
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064// The min number of tokens must present in Turn host uri.
65// e.g. user@turn.example.org
66static const size_t kTurnHostTokensNum = 2;
67// Number of tokens must be preset when TURN uri has transport param.
68static const size_t kTurnTransportTokensNum = 2;
69// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000070static const int kDefaultStunPort = 3478;
71static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073
74// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070075static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076
zhihuang8f65cdf2016-05-06 18:40:30 -070077// The length of RTCP CNAMEs.
78static const int kRtcpCnameLength = 16;
79
deadbeef0a6c4ca2015-10-06 11:38:28 -070080// NOTE: A loop below assumes that the first value of this enum is 0 and all
81// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070083 STUN = 0, // Indicates a STUN server.
84 STUNS, // Indicates a STUN server used with a TLS session.
85 TURN, // Indicates a TURN server
86 TURNS, // Indicates a TURN server used with a TLS session.
87 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088};
tfarina5237aaf2015-11-10 23:44:30 -080089static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070090 "kValidIceServiceTypes must have as many strings as ServiceType "
91 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
93enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000094 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070096 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080098 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099};
100
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000101struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102 explicit SetSessionDescriptionMsg(
103 webrtc::SetSessionDescriptionObserver* observer)
104 : observer(observer) {
105 }
106
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000107 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 std::string error;
109};
110
deadbeefab9b2d12015-10-14 11:33:11 -0700111struct CreateSessionDescriptionMsg : public rtc::MessageData {
112 explicit CreateSessionDescriptionMsg(
113 webrtc::CreateSessionDescriptionObserver* observer)
114 : observer(observer) {}
115
116 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
117 std::string error;
118};
119
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000120struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000121 GetStatsMsg(webrtc::StatsObserver* observer,
122 webrtc::MediaStreamTrackInterface* track)
123 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000125 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000126 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127};
128
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000129// |in_str| should be of format
130// stunURI = scheme ":" stun-host [ ":" stun-port ]
131// scheme = "stun" / "stuns"
132// stun-host = IP-literal / IPv4address / reg-name
133// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700134//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000135// draft-petithuguenin-behave-turn-uris-01
136// turnURI = scheme ":" turn-host [ ":" turn-port ]
137// turn-host = username@IP-literal / IPv4address / reg-name
138bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
139 ServiceType* service_type,
140 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200141 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700142 if (colonpos == std::string::npos) {
143 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000144 return false;
145 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700146 if ((colonpos + 1) == in_str.length()) {
147 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
148 return false;
149 }
150 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800151 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700152 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000153 *service_type = static_cast<ServiceType>(i);
154 break;
155 }
156 }
157 if (*service_type == INVALID) {
158 return false;
159 }
160 *hostname = in_str.substr(colonpos + 1, std::string::npos);
161 return true;
162}
163
deadbeef0a6c4ca2015-10-06 11:38:28 -0700164bool ParsePort(const std::string& in_str, int* port) {
165 // Make sure port only contains digits. FromString doesn't check this.
166 for (const char& c : in_str) {
167 if (!std::isdigit(c)) {
168 return false;
169 }
170 }
171 return rtc::FromString(in_str, port);
172}
173
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000174// This method parses IPv6 and IPv4 literal strings, along with hostnames in
175// standard hostname:port format.
176// Consider following formats as correct.
177// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700178// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000179bool ParseHostnameAndPortFromString(const std::string& in_str,
180 std::string* host,
181 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700182 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000183 if (in_str.at(0) == '[') {
184 std::string::size_type closebracket = in_str.rfind(']');
185 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000186 std::string::size_type colonpos = in_str.find(':', closebracket);
187 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700188 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
189 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000190 return false;
191 }
192 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700193 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000194 } else {
195 return false;
196 }
197 } else {
198 std::string::size_type colonpos = in_str.find(':');
199 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700200 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000201 return false;
202 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700203 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000204 } else {
205 *host = in_str;
206 }
207 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700208 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000209}
210
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800211// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700212// by parsing |url| and using the username/password in |server|.
deadbeef293e9262017-01-11 12:28:30 -0800213RTCErrorType ParseIceServerUrl(
214 const PeerConnectionInterface::IceServer& server,
215 const std::string& url,
216 cricket::ServerAddresses* stun_servers,
217 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218 // draft-nandakumar-rtcweb-stun-uri-01
219 // stunURI = scheme ":" stun-host [ ":" stun-port ]
220 // scheme = "stun" / "stuns"
221 // stun-host = IP-literal / IPv4address / reg-name
222 // stun-port = *DIGIT
223
224 // draft-petithuguenin-behave-turn-uris-01
225 // turnURI = scheme ":" turn-host [ ":" turn-port ]
226 // [ "?transport=" transport ]
227 // scheme = "turn" / "turns"
228 // transport = "udp" / "tcp" / transport-ext
229 // transport-ext = 1*unreserved
230 // turn-host = IP-literal / IPv4address / reg-name
231 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800232 RTC_DCHECK(stun_servers != nullptr);
233 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200234 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800235 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700236 RTC_DCHECK(!url.empty());
hnslbd44bb02016-12-12 03:14:30 -0800237 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200238 std::string uri_without_transport = tokens[0];
239 // Let's look into transport= param, if it exists.
240 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
241 std::string uri_transport_param = tokens[1];
hnslbd44bb02016-12-12 03:14:30 -0800242 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
243 if (tokens[0] != kTransport) {
244 LOG(LS_WARNING) << "Invalid transport parameter key.";
deadbeef293e9262017-01-11 12:28:30 -0800245 return RTCErrorType::SYNTAX_ERROR;
hnslbd44bb02016-12-12 03:14:30 -0800246 }
247 if (tokens.size() < 2 ||
248 !cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
249 (turn_transport_type != cricket::PROTO_UDP &&
250 turn_transport_type != cricket::PROTO_TCP)) {
251 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef293e9262017-01-11 12:28:30 -0800252 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000253 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200254 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200256 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700257 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200258 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
259 &service_type,
260 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
deadbeef293e9262017-01-11 12:28:30 -0800262 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200263 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000264
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
266 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200267
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200268 // Let's break hostname.
269 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
271
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200272 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700273 if (tokens.size() > kTurnHostTokensNum) {
274 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800275 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700276 }
277 if (tokens.size() == kTurnHostTokensNum) {
278 if (tokens[0].empty() || tokens[1].empty()) {
279 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800280 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700281 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200282 username.assign(rtc::s_url_decode(tokens[0]));
283 hoststring = tokens[1];
284 } else {
285 hoststring = tokens[0];
286 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000287
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200288 int port = kDefaultStunPort;
289 if (service_type == TURNS) {
290 port = kDefaultStunTlsPort;
hnsl277b2502016-12-13 05:17:23 -0800291 turn_transport_type = cricket::PROTO_TLS;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200292 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000293
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200294 std::string address;
295 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700296 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
deadbeef293e9262017-01-11 12:28:30 -0800297 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200298 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000299
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200300 if (port <= 0 || port > 0xffff) {
301 LOG(WARNING) << "Invalid port: " << port;
deadbeef293e9262017-01-11 12:28:30 -0800302 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200303 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000304
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200305 switch (service_type) {
306 case STUN:
307 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800308 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200309 break;
310 case TURN:
311 case TURNS: {
deadbeef293e9262017-01-11 12:28:30 -0800312 if (username.empty() || server.password.empty()) {
313 // The WebRTC spec requires throwing an InvalidAccessError when username
314 // or credential are ommitted; this is the native equivalent.
315 return RTCErrorType::INVALID_PARAMETER;
316 }
hnsl04833622017-01-09 08:35:45 -0800317 cricket::RelayServerConfig config = cricket::RelayServerConfig(
318 address, port, username, server.password, turn_transport_type);
319 if (server.tls_cert_policy ==
320 PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
321 config.tls_cert_policy =
322 cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
323 }
324 turn_servers->push_back(config);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200325 break;
326 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200327 default:
deadbeef293e9262017-01-11 12:28:30 -0800328 // We shouldn't get to this point with an invalid service_type, we should
329 // have returned an error already.
nisseeb4ca4e2017-01-12 02:24:27 -0800330 RTC_NOTREACHED() << "Unexpected service type";
deadbeef293e9262017-01-11 12:28:30 -0800331 return RTCErrorType::INTERNAL_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200332 }
deadbeef293e9262017-01-11 12:28:30 -0800333 return RTCErrorType::NONE;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200334}
335
deadbeefab9b2d12015-10-14 11:33:11 -0700336// Check if we can send |new_stream| on a PeerConnection.
337bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
338 webrtc::MediaStreamInterface* new_stream) {
339 if (!new_stream || !current_streams) {
340 return false;
341 }
342 if (current_streams->find(new_stream->label()) != nullptr) {
343 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
344 << " is already added.";
345 return false;
346 }
347 return true;
348}
349
350bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
351 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
352}
353
deadbeef5e97fb52015-10-15 12:49:08 -0700354// If the direction is "recvonly" or "inactive", treat the description
355// as containing no streams.
356// See: https://code.google.com/p/webrtc/issues/detail?id=5054
357std::vector<cricket::StreamParams> GetActiveStreams(
358 const cricket::MediaContentDescription* desc) {
359 return MediaContentDirectionHasSend(desc->direction())
360 ? desc->streams()
361 : std::vector<cricket::StreamParams>();
362}
363
deadbeefab9b2d12015-10-14 11:33:11 -0700364bool IsValidOfferToReceiveMedia(int value) {
365 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
366 return (value >= Options::kUndefined) &&
367 (value <= Options::kMaxOfferToReceiveMedia);
368}
369
370// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800371void AddSendStreams(
372 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700373 const std::vector<rtc::scoped_refptr<
374 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800375 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
376 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700377 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800378 for (const auto& sender : senders) {
379 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700380 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700381 }
382
383 // Check for data channels.
384 for (const auto& kv : rtp_data_channels) {
385 const DataChannel* channel = kv.second;
386 if (channel->state() == DataChannel::kConnecting ||
387 channel->state() == DataChannel::kOpen) {
388 // |streamid| and |sync_label| are both set to the DataChannel label
389 // here so they can be signaled the same way as MediaStreams and Tracks.
390 // For MediaStreams, the sync_label is the MediaStream label and the
391 // track label is the same as |streamid|.
392 const std::string& streamid = channel->label();
393 const std::string& sync_label = channel->label();
394 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
395 sync_label);
396 }
397 }
398}
399
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700400uint32_t ConvertIceTransportTypeToCandidateFilter(
401 PeerConnectionInterface::IceTransportsType type) {
402 switch (type) {
403 case PeerConnectionInterface::kNone:
404 return cricket::CF_NONE;
405 case PeerConnectionInterface::kRelay:
406 return cricket::CF_RELAY;
407 case PeerConnectionInterface::kNoHost:
408 return (cricket::CF_ALL & ~cricket::CF_HOST);
409 case PeerConnectionInterface::kAll:
410 return cricket::CF_ALL;
411 default:
nissec80e7412017-01-11 05:56:46 -0800412 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700413 }
414 return cricket::CF_NONE;
415}
416
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700417// Helper method to set a voice/video channel on all applicable senders
418// and receivers when one is created/destroyed by WebRtcSession.
419//
420// Used by On(Voice|Video)Channel(Created|Destroyed)
421template <class SENDER,
422 class RECEIVER,
423 class CHANNEL,
424 class SENDERS,
425 class RECEIVERS>
426void SetChannelOnSendersAndReceivers(CHANNEL* channel,
427 SENDERS& senders,
428 RECEIVERS& receivers,
429 cricket::MediaType media_type) {
430 for (auto& sender : senders) {
431 if (sender->media_type() == media_type) {
432 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
433 }
434 }
435 for (auto& receiver : receivers) {
436 if (receiver->media_type() == media_type) {
437 if (!channel) {
438 receiver->internal()->Stop();
439 }
440 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
441 }
442 }
443}
444
deadbeef293e9262017-01-11 12:28:30 -0800445// Helper to set an error and return from a method.
446bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
447 if (error) {
448 error->set_type(type);
449 }
450 return type == webrtc::RTCErrorType::NONE;
451}
452
deadbeef0a6c4ca2015-10-06 11:38:28 -0700453} // namespace
454
455namespace webrtc {
456
deadbeef293e9262017-01-11 12:28:30 -0800457static const char* const kRTCErrorTypeNames[] = {
deadbeef3edec7c2016-12-10 11:44:26 -0800458 "NONE",
459 "UNSUPPORTED_PARAMETER",
460 "INVALID_PARAMETER",
461 "INVALID_RANGE",
462 "SYNTAX_ERROR",
463 "INVALID_STATE",
464 "INVALID_MODIFICATION",
465 "NETWORK_ERROR",
466 "INTERNAL_ERROR",
467};
deadbeef293e9262017-01-11 12:28:30 -0800468static_assert(static_cast<int>(RTCErrorType::INTERNAL_ERROR) ==
469 (arraysize(kRTCErrorTypeNames) - 1),
470 "kRTCErrorTypeNames must have as many strings as RTCErrorType "
471 "has values.");
deadbeef3edec7c2016-12-10 11:44:26 -0800472
deadbeef293e9262017-01-11 12:28:30 -0800473std::ostream& operator<<(std::ostream& stream, RTCErrorType error) {
deadbeef3edec7c2016-12-10 11:44:26 -0800474 int index = static_cast<int>(error);
deadbeef293e9262017-01-11 12:28:30 -0800475 return stream << kRTCErrorTypeNames[index];
476}
477
478bool PeerConnectionInterface::RTCConfiguration::operator==(
479 const PeerConnectionInterface::RTCConfiguration& o) const {
480 // This static_assert prevents us from accidentally breaking operator==.
481 struct stuff_being_tested_for_equality {
482 IceTransportsType type;
483 IceServers servers;
484 BundlePolicy bundle_policy;
485 RtcpMuxPolicy rtcp_mux_policy;
486 TcpCandidatePolicy tcp_candidate_policy;
487 CandidateNetworkPolicy candidate_network_policy;
488 int audio_jitter_buffer_max_packets;
489 bool audio_jitter_buffer_fast_accelerate;
490 int ice_connection_receiving_timeout;
491 int ice_backup_candidate_pair_ping_interval;
492 ContinualGatheringPolicy continual_gathering_policy;
493 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
494 bool prioritize_most_likely_ice_candidate_pairs;
495 struct cricket::MediaConfig media_config;
496 bool disable_ipv6;
497 bool enable_rtp_data_channel;
498 bool enable_quic;
499 rtc::Optional<int> screencast_min_bitrate;
500 rtc::Optional<bool> combined_audio_video_bwe;
501 rtc::Optional<bool> enable_dtls_srtp;
502 int ice_candidate_pool_size;
503 bool prune_turn_ports;
504 bool presume_writable_when_fully_relayed;
505 bool enable_ice_renomination;
506 bool redetermine_role_on_ice_restart;
507 };
508 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
509 "Did you add something to RTCConfiguration and forget to "
510 "update operator==?");
511 return type == o.type && servers == o.servers &&
512 bundle_policy == o.bundle_policy &&
513 rtcp_mux_policy == o.rtcp_mux_policy &&
514 tcp_candidate_policy == o.tcp_candidate_policy &&
515 candidate_network_policy == o.candidate_network_policy &&
516 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
517 audio_jitter_buffer_fast_accelerate ==
518 o.audio_jitter_buffer_fast_accelerate &&
519 ice_connection_receiving_timeout ==
520 o.ice_connection_receiving_timeout &&
521 ice_backup_candidate_pair_ping_interval ==
522 o.ice_backup_candidate_pair_ping_interval &&
523 continual_gathering_policy == o.continual_gathering_policy &&
524 certificates == o.certificates &&
525 prioritize_most_likely_ice_candidate_pairs ==
526 o.prioritize_most_likely_ice_candidate_pairs &&
527 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
528 enable_rtp_data_channel == o.enable_rtp_data_channel &&
529 enable_quic == o.enable_quic &&
530 screencast_min_bitrate == o.screencast_min_bitrate &&
531 combined_audio_video_bwe == o.combined_audio_video_bwe &&
532 enable_dtls_srtp == o.enable_dtls_srtp &&
533 ice_candidate_pool_size == o.ice_candidate_pool_size &&
534 prune_turn_ports == o.prune_turn_ports &&
535 presume_writable_when_fully_relayed ==
536 o.presume_writable_when_fully_relayed &&
537 enable_ice_renomination == o.enable_ice_renomination &&
538 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart;
539}
540
541bool PeerConnectionInterface::RTCConfiguration::operator!=(
542 const PeerConnectionInterface::RTCConfiguration& o) const {
543 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800544}
545
zhihuang8f65cdf2016-05-06 18:40:30 -0700546// Generate a RTCP CNAME when a PeerConnection is created.
547std::string GenerateRtcpCname() {
548 std::string cname;
549 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
550 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800551 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700552 }
553 return cname;
554}
555
htaa2a49d92016-03-04 02:51:39 -0800556bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700557 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800558 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700559 cricket::MediaSessionOptions* session_options) {
560 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
561 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
562 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
563 return false;
564 }
565
htaaac2dea2016-03-10 13:35:55 -0800566 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700567 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700568 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800569 } else {
570 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700571 }
htaaac2dea2016-03-10 13:35:55 -0800572 // For offers, we only offer video if we have it or it's forced by options.
573 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700574 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700575 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800576 } else if (is_offer) {
577 session_options->recv_video = false;
578 } else {
579 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700580 }
581
582 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700583 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800584 for (auto& kv : session_options->transport_options) {
585 kv.second.ice_restart = rtc_options.ice_restart;
586 }
deadbeefab9b2d12015-10-14 11:33:11 -0700587
588 return true;
589}
590
591bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
592 cricket::MediaSessionOptions* session_options) {
593 bool value = false;
594 size_t mandatory_constraints_satisfied = 0;
595
596 // kOfferToReceiveAudio defaults to true according to spec.
597 if (!FindConstraint(constraints,
598 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
599 &mandatory_constraints_satisfied) ||
600 value) {
601 session_options->recv_audio = true;
602 }
603
604 // kOfferToReceiveVideo defaults to false according to spec. But
605 // if it is an answer and video is offered, we should still accept video
606 // per default.
607 value = false;
608 if (!FindConstraint(constraints,
609 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
610 &mandatory_constraints_satisfied) ||
611 value) {
612 session_options->recv_video = true;
613 }
614
615 if (FindConstraint(constraints,
616 MediaConstraintsInterface::kVoiceActivityDetection, &value,
617 &mandatory_constraints_satisfied)) {
618 session_options->vad_enabled = value;
619 }
620
621 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
622 &mandatory_constraints_satisfied)) {
623 session_options->bundle_enabled = value;
624 } else {
625 // kUseRtpMux defaults to true according to spec.
626 session_options->bundle_enabled = true;
627 }
deadbeefab9b2d12015-10-14 11:33:11 -0700628
deadbeef0ed85b22016-02-23 17:24:52 -0800629 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700630 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
631 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700632 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800633 ice_restart = true;
634 }
635 for (auto& kv : session_options->transport_options) {
636 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700637 }
638
639 if (!constraints) {
640 return true;
641 }
642 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
643}
644
deadbeef293e9262017-01-11 12:28:30 -0800645RTCErrorType ParseIceServers(
646 const PeerConnectionInterface::IceServers& servers,
647 cricket::ServerAddresses* stun_servers,
648 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200649 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
650 if (!server.urls.empty()) {
651 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200652 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700653 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800654 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200655 }
deadbeef293e9262017-01-11 12:28:30 -0800656 RTCErrorType err =
657 ParseIceServerUrl(server, url, stun_servers, turn_servers);
658 if (err != RTCErrorType::NONE) {
659 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200660 }
661 }
662 } else if (!server.uri.empty()) {
663 // Fallback to old .uri if new .urls isn't present.
deadbeef293e9262017-01-11 12:28:30 -0800664 RTCErrorType err =
665 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
666 if (err != RTCErrorType::NONE) {
667 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200668 }
669 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700670 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800671 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672 }
673 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800674 // Candidates must have unique priorities, so that connectivity checks
675 // are performed in a well-defined order.
676 int priority = static_cast<int>(turn_servers->size() - 1);
677 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
678 // First in the list gets highest priority.
679 turn_server.priority = priority--;
680 }
deadbeef293e9262017-01-11 12:28:30 -0800681 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682}
683
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684PeerConnection::PeerConnection(PeerConnectionFactory* factory)
685 : factory_(factory),
686 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000687 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700690 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800691 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700692 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700693 local_streams_(StreamCollection::Create()),
694 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695
696PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100697 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700698 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700699 // Need to detach RTP senders/receivers from WebRtcSession,
700 // since it's about to be destroyed.
701 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700702 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700703 }
704 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700705 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700706 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700707 // Destroy stats_ because it depends on session_.
708 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800709 if (stats_collector_) {
710 stats_collector_->WaitForPendingRequest();
711 stats_collector_ = nullptr;
712 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700713 // Now destroy session_ before destroying other members,
714 // because its destruction fires signals (such as VoiceChannelDestroyed)
715 // which will trigger some final actions in PeerConnection...
716 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700717 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700718 network_thread()->Invoke<void>(RTC_FROM_HERE,
719 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720}
721
722bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000723 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700724 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200725 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800726 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100727 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800728 if (!allocator) {
729 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
730 << "This shouldn't happen if using PeerConnectionFactory.";
731 return false;
732 }
deadbeef653b8e02015-11-11 12:55:10 -0800733 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800734 // TODO(deadbeef): Why do we do this?
735 LOG(LS_ERROR) << "PeerConnection initialized without a "
736 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800737 return false;
738 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000739 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800740 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800741
deadbeef91dd5672016-05-18 16:55:30 -0700742 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700743 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700744 if (!network_thread()->Invoke<bool>(
745 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
746 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747 return false;
748 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749
skvlad11a9cbf2016-10-07 11:53:05 -0700750 media_controller_.reset(factory_->CreateMediaController(
751 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752
zhihuang29ff8442016-07-27 11:07:25 -0700753 session_.reset(new WebRtcSession(
754 media_controller_.get(), factory_->network_thread(),
755 factory_->worker_thread(), factory_->signaling_thread(),
756 port_allocator_.get(),
757 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700758 factory_->CreateTransportController(
759 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800760 configuration.redetermine_role_on_ice_restart)),
761#ifdef HAVE_SCTP
762 std::unique_ptr<cricket::SctpTransportInternalFactory>(
763 new cricket::SctpTransportFactory(factory_->network_thread()))
764#else
765 nullptr
766#endif
767 ));
zhihuang29ff8442016-07-27 11:07:25 -0700768
deadbeefab9b2d12015-10-14 11:33:11 -0700769 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700770 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771
772 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200773 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800774 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000775 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700776 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000777
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778 // Register PeerConnection as receiver of local ice candidates.
779 // All the callbacks will be posted to the application from PeerConnection.
780 session_->RegisterIceObserver(this);
781 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700782 session_->SignalVoiceChannelCreated.connect(
783 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700784 session_->SignalVoiceChannelDestroyed.connect(
785 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700786 session_->SignalVideoChannelCreated.connect(
787 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700788 session_->SignalVideoChannelDestroyed.connect(
789 this, &PeerConnection::OnVideoChannelDestroyed);
790 session_->SignalDataChannelCreated.connect(
791 this, &PeerConnection::OnDataChannelCreated);
792 session_->SignalDataChannelDestroyed.connect(
793 this, &PeerConnection::OnDataChannelDestroyed);
794 session_->SignalDataChannelOpenMessage.connect(
795 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800796
797 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000798 return true;
799}
800
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000801rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700803 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804}
805
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000806rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700808 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809}
810
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000811bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100812 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 if (IsClosed()) {
814 return false;
815 }
deadbeefab9b2d12015-10-14 11:33:11 -0700816 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817 return false;
818 }
deadbeefab9b2d12015-10-14 11:33:11 -0700819
820 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800821 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
822 observer->SignalAudioTrackAdded.connect(this,
823 &PeerConnection::OnAudioTrackAdded);
824 observer->SignalAudioTrackRemoved.connect(
825 this, &PeerConnection::OnAudioTrackRemoved);
826 observer->SignalVideoTrackAdded.connect(this,
827 &PeerConnection::OnVideoTrackAdded);
828 observer->SignalVideoTrackRemoved.connect(
829 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700830 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700831
deadbeefab9b2d12015-10-14 11:33:11 -0700832 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800833 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700834 }
835 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800836 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700837 }
838
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000839 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 observer_->OnRenegotiationNeeded();
841 return true;
842}
843
844void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100845 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700846 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800847 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700848 }
849 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800850 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700851 }
852
853 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800854 stream_observers_.erase(
855 std::remove_if(
856 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700857 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800858 return observer->stream()->label().compare(local_stream->label()) ==
859 0;
860 }),
861 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700862
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000863 if (IsClosed()) {
864 return;
865 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866 observer_->OnRenegotiationNeeded();
867}
868
deadbeefe1f9d832016-01-14 15:35:42 -0800869rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
870 MediaStreamTrackInterface* track,
871 std::vector<MediaStreamInterface*> streams) {
872 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
873 if (IsClosed()) {
874 return nullptr;
875 }
876 if (streams.size() >= 2) {
877 LOG(LS_ERROR)
878 << "Adding a track with two streams is not currently supported.";
879 return nullptr;
880 }
881 // TODO(deadbeef): Support adding a track to two different senders.
882 if (FindSenderForTrack(track) != senders_.end()) {
883 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
884 return nullptr;
885 }
886
887 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700888 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800889 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700890 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800891 signaling_thread(),
892 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700893 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800894 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700895 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800896 }
897 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700898 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800899 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700900 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800901 }
902 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700903 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800904 signaling_thread(),
905 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700906 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800907 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700908 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800909 }
910 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700911 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800912 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700913 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800914 }
915 } else {
916 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
917 return rtc::scoped_refptr<RtpSenderInterface>();
918 }
919
920 senders_.push_back(new_sender);
921 observer_->OnRenegotiationNeeded();
922 return new_sender;
923}
924
925bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
926 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
927 if (IsClosed()) {
928 return false;
929 }
930
931 auto it = std::find(senders_.begin(), senders_.end(), sender);
932 if (it == senders_.end()) {
933 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
934 return false;
935 }
deadbeefa601f5c2016-06-06 14:27:39 -0700936 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800937 senders_.erase(it);
938
939 observer_->OnRenegotiationNeeded();
940 return true;
941}
942
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000943rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100945 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700946 if (IsClosed()) {
947 return nullptr;
948 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 if (!track) {
950 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
951 return NULL;
952 }
deadbeefab9b2d12015-10-14 11:33:11 -0700953 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
955 return NULL;
956 }
957
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000958 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 DtmfSender::Create(track, signaling_thread(), session_.get()));
960 if (!sender.get()) {
961 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
962 return NULL;
963 }
964 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
965}
966
deadbeeffac06552015-11-25 11:26:01 -0800967rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800968 const std::string& kind,
969 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100970 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700971 if (IsClosed()) {
972 return nullptr;
973 }
deadbeefa601f5c2016-06-06 14:27:39 -0700974 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800975 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700976 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700977 signaling_thread(),
978 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800979 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700980 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700981 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800982 } else {
983 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800984 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800985 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800986 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700987 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800988 }
deadbeeffac06552015-11-25 11:26:01 -0800989 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800990 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800991}
992
deadbeef70ab1a12015-09-28 16:53:55 -0700993std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
994 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700995 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
996 for (const auto& sender : senders_) {
997 ret.push_back(sender.get());
998 }
999 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001000}
1001
1002std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1003PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001004 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
1005 for (const auto& receiver : receivers_) {
1006 ret.push_back(receiver.get());
1007 }
1008 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001009}
1010
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001012 MediaStreamTrackInterface* track,
1013 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001014 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001015 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 if (!VERIFY(observer != NULL)) {
1017 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1018 return false;
1019 }
1020
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001021 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001022 // The StatsCollector is used to tell if a track is valid because it may
1023 // remember tracks that the PeerConnection previously removed.
1024 if (track && !stats_->IsValidTrack(track->id())) {
1025 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1026 << track->id();
1027 return false;
1028 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001029 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001030 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031 return true;
1032}
1033
hbos74e1a4f2016-09-15 23:33:01 -07001034void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1035 RTC_DCHECK(stats_collector_);
1036 stats_collector_->GetStatsReport(callback);
1037}
1038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1040 return signaling_state_;
1041}
1042
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001043PeerConnectionInterface::IceConnectionState
1044PeerConnection::ice_connection_state() {
1045 return ice_connection_state_;
1046}
1047
1048PeerConnectionInterface::IceGatheringState
1049PeerConnection::ice_gathering_state() {
1050 return ice_gathering_state_;
1051}
1052
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001053rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054PeerConnection::CreateDataChannel(
1055 const std::string& label,
1056 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001057 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001058#ifdef HAVE_QUIC
1059 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1060 // TODO(zhihuang): Handle case when config is NULL.
1061 if (!config) {
1062 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1063 return nullptr;
1064 }
1065 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1066 if (!config->reliable || config->ordered) {
1067 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1068 "ordered delivery.";
1069 return nullptr;
1070 }
1071 return session_->quic_data_transport()->CreateDataChannel(label, config);
1072 }
1073#endif // HAVE_QUIC
1074
deadbeefab9b2d12015-10-14 11:33:11 -07001075 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001076
kwibergd1fe2812016-04-27 06:47:29 -07001077 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001078 if (config) {
1079 internal_config.reset(new InternalDataChannelInit(*config));
1080 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001081 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001082 InternalCreateDataChannel(label, internal_config.get()));
1083 if (!channel.get()) {
1084 return nullptr;
1085 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001087 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1088 // the first SCTP DataChannel.
1089 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1090 observer_->OnRenegotiationNeeded();
1091 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001092
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 return DataChannelProxy::Create(signaling_thread(), channel.get());
1094}
1095
1096void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1097 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001098 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001099 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1101 return;
1102 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001103 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001104
1105 bool value;
1106 size_t mandatory_constraints = 0;
1107
1108 if (FindConstraint(constraints,
1109 MediaConstraintsInterface::kOfferToReceiveAudio,
1110 &value,
1111 &mandatory_constraints)) {
1112 options.offer_to_receive_audio =
1113 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1114 }
1115
1116 if (FindConstraint(constraints,
1117 MediaConstraintsInterface::kOfferToReceiveVideo,
1118 &value,
1119 &mandatory_constraints)) {
1120 options.offer_to_receive_video =
1121 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1122 }
1123
1124 if (FindConstraint(constraints,
1125 MediaConstraintsInterface::kVoiceActivityDetection,
1126 &value,
1127 &mandatory_constraints)) {
1128 options.voice_activity_detection = value;
1129 }
1130
1131 if (FindConstraint(constraints,
1132 MediaConstraintsInterface::kIceRestart,
1133 &value,
1134 &mandatory_constraints)) {
1135 options.ice_restart = value;
1136 }
1137
1138 if (FindConstraint(constraints,
1139 MediaConstraintsInterface::kUseRtpMux,
1140 &value,
1141 &mandatory_constraints)) {
1142 options.use_rtp_mux = value;
1143 }
1144
1145 CreateOffer(observer, options);
1146}
1147
1148void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1149 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001150 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001151 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001152 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1153 return;
1154 }
deadbeefab9b2d12015-10-14 11:33:11 -07001155
1156 cricket::MediaSessionOptions session_options;
1157 if (!GetOptionsForOffer(options, &session_options)) {
1158 std::string error = "CreateOffer called with invalid options.";
1159 LOG(LS_ERROR) << error;
1160 PostCreateSessionDescriptionFailure(observer, error);
1161 return;
1162 }
1163
1164 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165}
1166
1167void PeerConnection::CreateAnswer(
1168 CreateSessionDescriptionObserver* observer,
1169 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001170 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001171 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1173 return;
1174 }
deadbeefab9b2d12015-10-14 11:33:11 -07001175
1176 cricket::MediaSessionOptions session_options;
1177 if (!GetOptionsForAnswer(constraints, &session_options)) {
1178 std::string error = "CreateAnswer called with invalid constraints.";
1179 LOG(LS_ERROR) << error;
1180 PostCreateSessionDescriptionFailure(observer, error);
1181 return;
1182 }
1183
htaa2a49d92016-03-04 02:51:39 -08001184 session_->CreateAnswer(observer, session_options);
1185}
1186
1187void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1188 const RTCOfferAnswerOptions& options) {
1189 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1190 if (!VERIFY(observer != nullptr)) {
1191 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1192 return;
1193 }
1194
1195 cricket::MediaSessionOptions session_options;
1196 if (!GetOptionsForAnswer(options, &session_options)) {
1197 std::string error = "CreateAnswer called with invalid options.";
1198 LOG(LS_ERROR) << error;
1199 PostCreateSessionDescriptionFailure(observer, error);
1200 return;
1201 }
1202
1203 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001204}
1205
1206void PeerConnection::SetLocalDescription(
1207 SetSessionDescriptionObserver* observer,
1208 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001209 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001210 if (IsClosed()) {
1211 return;
1212 }
deadbeefab9b2d12015-10-14 11:33:11 -07001213 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1215 return;
1216 }
1217 if (!desc) {
1218 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1219 return;
1220 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221 // Update stats here so that we have the most recent stats for tracks and
1222 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001223 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001224 std::string error;
1225 if (!session_->SetLocalDescription(desc, &error)) {
1226 PostSetSessionDescriptionFailure(observer, error);
1227 return;
1228 }
deadbeefab9b2d12015-10-14 11:33:11 -07001229
1230 // If setting the description decided our SSL role, allocate any necessary
1231 // SCTP sids.
1232 rtc::SSLRole role;
1233 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001234 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001235 AllocateSctpSids(role);
1236 }
1237
1238 // Update state and SSRC of local MediaStreams and DataChannels based on the
1239 // local session description.
1240 const cricket::ContentInfo* audio_content =
1241 GetFirstAudioContent(desc->description());
1242 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001243 if (audio_content->rejected) {
1244 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1245 } else {
1246 const cricket::AudioContentDescription* audio_desc =
1247 static_cast<const cricket::AudioContentDescription*>(
1248 audio_content->description);
1249 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1250 }
deadbeefab9b2d12015-10-14 11:33:11 -07001251 }
1252
1253 const cricket::ContentInfo* video_content =
1254 GetFirstVideoContent(desc->description());
1255 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001256 if (video_content->rejected) {
1257 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1258 } else {
1259 const cricket::VideoContentDescription* video_desc =
1260 static_cast<const cricket::VideoContentDescription*>(
1261 video_content->description);
1262 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1263 }
deadbeefab9b2d12015-10-14 11:33:11 -07001264 }
1265
1266 const cricket::ContentInfo* data_content =
1267 GetFirstDataContent(desc->description());
1268 if (data_content) {
1269 const cricket::DataContentDescription* data_desc =
1270 static_cast<const cricket::DataContentDescription*>(
1271 data_content->description);
1272 if (rtc::starts_with(data_desc->protocol().data(),
1273 cricket::kMediaProtocolRtpPrefix)) {
1274 UpdateLocalRtpDataChannels(data_desc->streams());
1275 }
1276 }
1277
1278 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001279 signaling_thread()->Post(RTC_FROM_HERE, this,
1280 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001281
deadbeefcbecd352015-09-23 11:50:27 -07001282 // MaybeStartGathering needs to be called after posting
1283 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1284 // before signaling that SetLocalDescription completed.
1285 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286}
1287
1288void PeerConnection::SetRemoteDescription(
1289 SetSessionDescriptionObserver* observer,
1290 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001291 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001292 if (IsClosed()) {
1293 return;
1294 }
deadbeefab9b2d12015-10-14 11:33:11 -07001295 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1297 return;
1298 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 if (!desc) {
1300 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1301 return;
1302 }
1303 // Update stats here so that we have the most recent stats for tracks and
1304 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001305 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306 std::string error;
1307 if (!session_->SetRemoteDescription(desc, &error)) {
1308 PostSetSessionDescriptionFailure(observer, error);
1309 return;
1310 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311
deadbeefab9b2d12015-10-14 11:33:11 -07001312 // If setting the description decided our SSL role, allocate any necessary
1313 // SCTP sids.
1314 rtc::SSLRole role;
1315 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001316 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001317 AllocateSctpSids(role);
1318 }
1319
1320 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001321 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1322 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1323 const cricket::AudioContentDescription* audio_desc =
1324 GetFirstAudioContentDescription(remote_desc);
1325 const cricket::VideoContentDescription* video_desc =
1326 GetFirstVideoContentDescription(remote_desc);
1327 const cricket::DataContentDescription* data_desc =
1328 GetFirstDataContentDescription(remote_desc);
1329
1330 // Check if the descriptions include streams, just in case the peer supports
1331 // MSID, but doesn't indicate so with "a=msid-semantic".
1332 if (remote_desc->msid_supported() ||
1333 (audio_desc && !audio_desc->streams().empty()) ||
1334 (video_desc && !video_desc->streams().empty())) {
1335 remote_peer_supports_msid_ = true;
1336 }
deadbeefab9b2d12015-10-14 11:33:11 -07001337
1338 // We wait to signal new streams until we finish processing the description,
1339 // since only at that point will new streams have all their tracks.
1340 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1341
1342 // Find all audio rtp streams and create corresponding remote AudioTracks
1343 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001344 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001345 if (audio_content->rejected) {
1346 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1347 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001348 bool default_audio_track_needed =
1349 !remote_peer_supports_msid_ &&
1350 MediaContentDirectionHasSend(audio_desc->direction());
1351 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1352 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001353 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001354 }
deadbeefab9b2d12015-10-14 11:33:11 -07001355 }
1356
1357 // Find all video rtp streams and create corresponding remote VideoTracks
1358 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001359 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001360 if (video_content->rejected) {
1361 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1362 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001363 bool default_video_track_needed =
1364 !remote_peer_supports_msid_ &&
1365 MediaContentDirectionHasSend(video_desc->direction());
1366 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1367 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001368 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001369 }
deadbeefab9b2d12015-10-14 11:33:11 -07001370 }
1371
1372 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001373 if (data_desc) {
1374 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001375 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001376 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001377 }
1378 }
1379
1380 // Iterate new_streams and notify the observer about new MediaStreams.
1381 for (size_t i = 0; i < new_streams->count(); ++i) {
1382 MediaStreamInterface* new_stream = new_streams->at(i);
1383 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001384 // Call both the raw pointer and scoped_refptr versions of the method
1385 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001386 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001387 observer_->OnAddStream(
1388 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001389 }
1390
deadbeefbda7e0b2015-12-08 17:13:40 -08001391 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001392
1393 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001394 signaling_thread()->Post(RTC_FROM_HERE, this,
1395 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001396}
1397
deadbeef46c73892016-11-16 19:42:04 -08001398PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1399 return configuration_;
1400}
1401
deadbeef293e9262017-01-11 12:28:30 -08001402bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1403 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001404 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001405
1406 if (session_->local_description() &&
1407 configuration.ice_candidate_pool_size !=
1408 configuration_.ice_candidate_pool_size) {
1409 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1410 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001411 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001412 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001413
deadbeef293e9262017-01-11 12:28:30 -08001414 // The simplest (and most future-compatible) way to tell if the config was
1415 // modified in an invalid way is to copy each property we do support
1416 // modifying, then use operator==. There are far more properties we don't
1417 // support modifying than those we do, and more could be added.
1418 RTCConfiguration modified_config = configuration_;
1419 modified_config.servers = configuration.servers;
1420 modified_config.type = configuration.type;
1421 modified_config.ice_candidate_pool_size =
1422 configuration.ice_candidate_pool_size;
1423 modified_config.prune_turn_ports = configuration.prune_turn_ports;
1424 if (configuration != modified_config) {
1425 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1426 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1427 }
1428
1429 // Note that this isn't possible through chromium, since it's an unsigned
1430 // short in WebIDL.
1431 if (configuration.ice_candidate_pool_size < 0 ||
1432 configuration.ice_candidate_pool_size > UINT16_MAX) {
1433 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1434 }
1435
1436 // Parse ICE servers before hopping to network thread.
1437 cricket::ServerAddresses stun_servers;
1438 std::vector<cricket::RelayServerConfig> turn_servers;
1439 RTCErrorType parse_error =
1440 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1441 if (parse_error != RTCErrorType::NONE) {
1442 return SafeSetError(parse_error, error);
1443 }
1444
1445 // In theory this shouldn't fail.
1446 if (!network_thread()->Invoke<bool>(
1447 RTC_FROM_HERE,
1448 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1449 stun_servers, turn_servers, modified_config.type,
1450 modified_config.ice_candidate_pool_size,
1451 modified_config.prune_turn_ports))) {
1452 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1453 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1454 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001455
deadbeefd1a38b52016-12-10 13:15:33 -08001456 // As described in JSEP, calling setConfiguration with new ICE servers or
1457 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1458 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001459 if (modified_config.servers != configuration_.servers ||
1460 modified_config.type != configuration_.type ||
1461 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001462 session_->SetNeedsIceRestartFlag();
1463 }
deadbeef293e9262017-01-11 12:28:30 -08001464 configuration_ = modified_config;
1465 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001466}
1467
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468bool PeerConnection::AddIceCandidate(
1469 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001470 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001471 if (IsClosed()) {
1472 return false;
1473 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474 return session_->ProcessIceMessage(ice_candidate);
1475}
1476
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001477bool PeerConnection::RemoveIceCandidates(
1478 const std::vector<cricket::Candidate>& candidates) {
1479 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1480 return session_->RemoveRemoteIceCandidates(candidates);
1481}
1482
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001483void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001484 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001485 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001486
1487 if (session_) {
1488 session_->set_metrics_observer(uma_observer_);
1489 }
1490
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001491 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001492 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001493 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001494 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001495 uma_observer_->IncrementEnumCounter(
1496 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1497 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001498 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001499 uma_observer_->IncrementEnumCounter(
1500 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1501 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001502 }
1503 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001504}
1505
ivoc14d5dbe2016-07-04 07:06:55 -07001506bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1507 int64_t max_size_bytes) {
1508 return factory_->worker_thread()->Invoke<bool>(
1509 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1510 max_size_bytes));
1511}
1512
1513void PeerConnection::StopRtcEventLog() {
1514 factory_->worker_thread()->Invoke<void>(
1515 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1516}
1517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001518const SessionDescriptionInterface* PeerConnection::local_description() const {
1519 return session_->local_description();
1520}
1521
1522const SessionDescriptionInterface* PeerConnection::remote_description() const {
1523 return session_->remote_description();
1524}
1525
deadbeeffe4a8a42016-12-20 17:56:17 -08001526const SessionDescriptionInterface* PeerConnection::current_local_description()
1527 const {
1528 return session_->current_local_description();
1529}
1530
1531const SessionDescriptionInterface* PeerConnection::current_remote_description()
1532 const {
1533 return session_->current_remote_description();
1534}
1535
1536const SessionDescriptionInterface* PeerConnection::pending_local_description()
1537 const {
1538 return session_->pending_local_description();
1539}
1540
1541const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1542 const {
1543 return session_->pending_remote_description();
1544}
1545
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001546void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001547 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001548 // Update stats here so that we have the most recent stats for tracks and
1549 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001550 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551
deadbeefd59daf82015-10-14 15:02:44 -07001552 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001553}
1554
deadbeefd59daf82015-10-14 15:02:44 -07001555void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1556 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001557 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001558 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001560 break;
deadbeefd59daf82015-10-14 15:02:44 -07001561 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1563 break;
deadbeefd59daf82015-10-14 15:02:44 -07001564 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1566 break;
deadbeefd59daf82015-10-14 15:02:44 -07001567 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1569 break;
deadbeefd59daf82015-10-14 15:02:44 -07001570 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1572 break;
deadbeefd59daf82015-10-14 15:02:44 -07001573 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574 ChangeSignalingState(PeerConnectionInterface::kStable);
1575 break;
deadbeefd59daf82015-10-14 15:02:44 -07001576 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001577 ChangeSignalingState(PeerConnectionInterface::kClosed);
1578 break;
1579 default:
1580 break;
1581 }
1582}
1583
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001584void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1587 SetSessionDescriptionMsg* param =
1588 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1589 param->observer->OnSuccess();
1590 delete param;
1591 break;
1592 }
1593 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1594 SetSessionDescriptionMsg* param =
1595 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1596 param->observer->OnFailure(param->error);
1597 delete param;
1598 break;
1599 }
deadbeefab9b2d12015-10-14 11:33:11 -07001600 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1601 CreateSessionDescriptionMsg* param =
1602 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1603 param->observer->OnFailure(param->error);
1604 delete param;
1605 break;
1606 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607 case MSG_GETSTATS: {
1608 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nisseb36ee8d2016-12-20 03:30:00 -08001609 std::unique_ptr<StatsReports> reports(new StatsReports);
1610 stats_->GetStats(param->track, reports.get());
1611 param->observer->OnCompleteReports(std::move(reports));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612 delete param;
1613 break;
1614 }
deadbeefbd292462015-12-14 18:15:29 -08001615 case MSG_FREE_DATACHANNELS: {
1616 sctp_data_channels_to_free_.clear();
1617 break;
1618 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001620 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 break;
1622 }
1623}
1624
deadbeefab9b2d12015-10-14 11:33:11 -07001625void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001626 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001627 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001628 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1629 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001630 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001631 session_->voice_channel()));
1632
1633 receivers_.push_back(receiver);
1634 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1635 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1636 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001637}
1638
deadbeefab9b2d12015-10-14 11:33:11 -07001639void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001640 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001641 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001642 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1643 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001644 signaling_thread(),
1645 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001646 ssrc, session_->video_channel()));
1647 receivers_.push_back(receiver);
1648 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1649 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1650 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001651}
1652
deadbeef70ab1a12015-09-28 16:53:55 -07001653// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1654// description.
perkjd61bf802016-03-24 03:16:19 -07001655void PeerConnection::DestroyReceiver(const std::string& track_id) {
1656 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001657 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001658 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001659 << " doesn't exist.";
1660 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001661 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001662 receivers_.erase(it);
1663 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001664}
1665
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001666void PeerConnection::OnIceConnectionChange(
1667 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001668 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001669 // After transitioning to "closed", ignore any additional states from
1670 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001671 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001672 return;
1673 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001675 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676}
1677
1678void PeerConnection::OnIceGatheringChange(
1679 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001680 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681 if (IsClosed()) {
1682 return;
1683 }
1684 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001685 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686}
1687
1688void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001689 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001690 if (IsClosed()) {
1691 return;
1692 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001693 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694}
1695
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001696void PeerConnection::OnIceCandidatesRemoved(
1697 const std::vector<cricket::Candidate>& candidates) {
1698 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001699 if (IsClosed()) {
1700 return;
1701 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001702 observer_->OnIceCandidatesRemoved(candidates);
1703}
1704
Peter Thatcher54360512015-07-08 11:08:35 -07001705void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001706 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001707 if (IsClosed()) {
1708 return;
1709 }
Peter Thatcher54360512015-07-08 11:08:35 -07001710 observer_->OnIceConnectionReceivingChange(receiving);
1711}
1712
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713void PeerConnection::ChangeSignalingState(
1714 PeerConnectionInterface::SignalingState signaling_state) {
1715 signaling_state_ = signaling_state;
1716 if (signaling_state == kClosed) {
1717 ice_connection_state_ = kIceConnectionClosed;
1718 observer_->OnIceConnectionChange(ice_connection_state_);
1719 if (ice_gathering_state_ != kIceGatheringComplete) {
1720 ice_gathering_state_ = kIceGatheringComplete;
1721 observer_->OnIceGatheringChange(ice_gathering_state_);
1722 }
1723 }
1724 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001725}
1726
deadbeefeb459812015-12-15 19:24:43 -08001727void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1728 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001729 if (IsClosed()) {
1730 return;
1731 }
deadbeefeb459812015-12-15 19:24:43 -08001732 auto sender = FindSenderForTrack(track);
1733 if (sender != senders_.end()) {
1734 // We already have a sender for this track, so just change the stream_id
1735 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001736 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001737 return;
1738 }
1739
1740 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001741 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1742 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001743 signaling_thread(),
1744 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1745 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001746 senders_.push_back(new_sender);
1747 // If the sender has already been configured in SDP, we call SetSsrc,
1748 // which will connect the sender to the underlying transport. This can
1749 // occur if a local session description that contains the ID of the sender
1750 // is set before AddStream is called. It can also occur if the local
1751 // session description is not changed and RemoveStream is called, and
1752 // later AddStream is called again with the same stream.
1753 const TrackInfo* track_info =
1754 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1755 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001756 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001757 }
1758}
1759
1760// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1761// indefinitely, when we have unified plan SDP.
1762void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1763 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001764 if (IsClosed()) {
1765 return;
1766 }
deadbeefeb459812015-12-15 19:24:43 -08001767 auto sender = FindSenderForTrack(track);
1768 if (sender == senders_.end()) {
1769 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1770 << " doesn't exist.";
1771 return;
1772 }
deadbeefa601f5c2016-06-06 14:27:39 -07001773 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001774 senders_.erase(sender);
1775}
1776
1777void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1778 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001779 if (IsClosed()) {
1780 return;
1781 }
deadbeefeb459812015-12-15 19:24:43 -08001782 auto sender = FindSenderForTrack(track);
1783 if (sender != senders_.end()) {
1784 // We already have a sender for this track, so just change the stream_id
1785 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001786 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001787 return;
1788 }
1789
1790 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001791 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1792 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001793 signaling_thread(), new VideoRtpSender(track, stream->label(),
1794 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001795 senders_.push_back(new_sender);
1796 const TrackInfo* track_info =
1797 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1798 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001799 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001800 }
1801}
1802
1803void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1804 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001805 if (IsClosed()) {
1806 return;
1807 }
deadbeefeb459812015-12-15 19:24:43 -08001808 auto sender = FindSenderForTrack(track);
1809 if (sender == senders_.end()) {
1810 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1811 << " doesn't exist.";
1812 return;
1813 }
deadbeefa601f5c2016-06-06 14:27:39 -07001814 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001815 senders_.erase(sender);
1816}
1817
deadbeefab9b2d12015-10-14 11:33:11 -07001818void PeerConnection::PostSetSessionDescriptionFailure(
1819 SetSessionDescriptionObserver* observer,
1820 const std::string& error) {
1821 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1822 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001823 signaling_thread()->Post(RTC_FROM_HERE, this,
1824 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001825}
1826
1827void PeerConnection::PostCreateSessionDescriptionFailure(
1828 CreateSessionDescriptionObserver* observer,
1829 const std::string& error) {
1830 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1831 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001832 signaling_thread()->Post(RTC_FROM_HERE, this,
1833 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001834}
1835
1836bool PeerConnection::GetOptionsForOffer(
1837 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1838 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001839 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1840 // ContentInfos.
1841 if (session_->local_description()) {
1842 for (const cricket::ContentInfo& content :
1843 session_->local_description()->description()->contents()) {
1844 session_options->transport_options[content.name] =
1845 cricket::TransportOptions();
1846 }
1847 }
deadbeef46c73892016-11-16 19:42:04 -08001848 session_options->enable_ice_renomination =
1849 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001850
htaaac2dea2016-03-10 13:35:55 -08001851 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001852 return false;
1853 }
1854
deadbeeffac06552015-11-25 11:26:01 -08001855 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001856 // Offer to receive audio/video if the constraint is not set and there are
1857 // send streams, or we're currently receiving.
1858 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1859 session_options->recv_audio =
1860 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1861 !remote_audio_tracks_.empty();
1862 }
1863 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1864 session_options->recv_video =
1865 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1866 !remote_video_tracks_.empty();
1867 }
deadbeefc80741f2015-10-22 13:14:45 -07001868
zhihuang9763d562016-08-05 11:14:50 -07001869 // Intentionally unset the data channel type for RTP data channel with the
1870 // second condition. Otherwise the RTP data channels would be successfully
1871 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1872 // when building with chromium. We want to leave RTP data channels broken, so
1873 // people won't try to use them.
1874 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1875 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001876 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001877
zhihuangaf388472016-11-02 16:49:48 -07001878 session_options->bundle_enabled =
1879 session_options->bundle_enabled &&
1880 (session_options->has_audio() || session_options->has_video() ||
1881 session_options->has_data());
1882
zhihuang8f65cdf2016-05-06 18:40:30 -07001883 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001884 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001885 return true;
1886}
1887
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001888void PeerConnection::InitializeOptionsForAnswer(
1889 cricket::MediaSessionOptions* session_options) {
1890 session_options->recv_audio = false;
1891 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001892 session_options->enable_ice_renomination =
1893 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001894}
1895
htaa2a49d92016-03-04 02:51:39 -08001896void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001897 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001898 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1899 // ContentInfos.
1900 if (session_->remote_description()) {
1901 // Initialize the transport_options map.
1902 for (const cricket::ContentInfo& content :
1903 session_->remote_description()->description()->contents()) {
1904 session_options->transport_options[content.name] =
1905 cricket::TransportOptions();
1906 }
1907 }
deadbeeffac06552015-11-25 11:26:01 -08001908 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001909 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1910 // are not signaled in the SDP so does not go through that path and must be
1911 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001912 // Intentionally unset the data channel type for RTP data channel. Otherwise
1913 // the RTP data channels would be successfully negotiated by default and the
1914 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1915 // We want to leave RTP data channels broken, so people won't try to use them.
1916 if (session_->data_channel_type() != cricket::DCT_RTP) {
1917 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001918 }
zhihuangaf388472016-11-02 16:49:48 -07001919 session_options->bundle_enabled =
1920 session_options->bundle_enabled &&
1921 (session_options->has_audio() || session_options->has_video() ||
1922 session_options->has_data());
1923
jbauchcb560652016-08-04 05:20:32 -07001924 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001925}
1926
1927bool PeerConnection::GetOptionsForAnswer(
1928 const MediaConstraintsInterface* constraints,
1929 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001930 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001931 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1932 return false;
1933 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001934 session_options->rtcp_cname = rtcp_cname_;
1935
htaa2a49d92016-03-04 02:51:39 -08001936 FinishOptionsForAnswer(session_options);
1937 return true;
1938}
1939
1940bool PeerConnection::GetOptionsForAnswer(
1941 const RTCOfferAnswerOptions& options,
1942 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001943 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001944 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001945 return false;
1946 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001947 session_options->rtcp_cname = rtcp_cname_;
1948
htaa2a49d92016-03-04 02:51:39 -08001949 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001950 return true;
1951}
1952
deadbeeffaac4972015-11-12 15:33:07 -08001953void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1954 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001955 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1956 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001957}
1958
deadbeefab9b2d12015-10-14 11:33:11 -07001959void PeerConnection::UpdateRemoteStreamsList(
1960 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001961 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001962 cricket::MediaType media_type,
1963 StreamCollection* new_streams) {
1964 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1965
1966 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001967 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001968 auto track_it = current_tracks->begin();
1969 while (track_it != current_tracks->end()) {
1970 const TrackInfo& info = *track_it;
1971 const cricket::StreamParams* params =
1972 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001973 bool track_exists = params && params->id == info.track_id;
1974 // If this is a default track, and we still need it, don't remove it.
1975 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1976 track_exists) {
1977 ++track_it;
1978 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001979 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1980 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001981 }
1982 }
1983
1984 // Find new and active tracks.
1985 for (const cricket::StreamParams& params : streams) {
1986 // The sync_label is the MediaStream label and the |stream.id| is the
1987 // track id.
1988 const std::string& stream_label = params.sync_label;
1989 const std::string& track_id = params.id;
1990 uint32_t ssrc = params.first_ssrc();
1991
1992 rtc::scoped_refptr<MediaStreamInterface> stream =
1993 remote_streams_->find(stream_label);
1994 if (!stream) {
1995 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001996 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1997 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001998 remote_streams_->AddStream(stream);
1999 new_streams->AddStream(stream);
2000 }
2001
2002 const TrackInfo* track_info =
2003 FindTrackInfo(*current_tracks, stream_label, track_id);
2004 if (!track_info) {
2005 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2006 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2007 }
2008 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002009
2010 // Add default track if necessary.
2011 if (default_track_needed) {
2012 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2013 remote_streams_->find(kDefaultStreamLabel);
2014 if (!default_stream) {
2015 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002016 default_stream = MediaStreamProxy::Create(
2017 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002018 remote_streams_->AddStream(default_stream);
2019 new_streams->AddStream(default_stream);
2020 }
2021 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2022 ? kDefaultAudioTrackLabel
2023 : kDefaultVideoTrackLabel;
2024 const TrackInfo* default_track_info =
2025 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2026 if (!default_track_info) {
2027 current_tracks->push_back(
2028 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2029 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2030 }
2031 }
deadbeefab9b2d12015-10-14 11:33:11 -07002032}
2033
2034void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2035 const std::string& track_id,
2036 uint32_t ssrc,
2037 cricket::MediaType media_type) {
2038 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2039
2040 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002041 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002042 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002043 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002044 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002045 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002046 }
2047}
2048
2049void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2050 const std::string& track_id,
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 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2056 // will be notified which will end the AudioRtpReceiver::track().
2057 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002058 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2059 stream->FindAudioTrack(track_id);
2060 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002061 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002062 }
2063 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002064 // Stopping or destroying a VideoRtpReceiver will end the
2065 // VideoRtpReceiver::track().
2066 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002067 rtc::scoped_refptr<VideoTrackInterface> video_track =
2068 stream->FindVideoTrack(track_id);
2069 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002070 // There's no guarantee the track is still available, e.g. the track may
2071 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002072 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002073 }
2074 } else {
nisseede5da42017-01-12 05:15:36 -08002075 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002076 }
2077}
2078
2079void PeerConnection::UpdateEndedRemoteMediaStreams() {
2080 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2081 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2082 MediaStreamInterface* stream = remote_streams_->at(i);
2083 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2084 streams_to_remove.push_back(stream);
2085 }
2086 }
2087
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002088 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002089 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002090 // Call both the raw pointer and scoped_refptr versions of the method
2091 // for compatibility.
2092 observer_->OnRemoveStream(stream.get());
2093 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002094 }
2095}
2096
deadbeefab9b2d12015-10-14 11:33:11 -07002097void PeerConnection::UpdateLocalTracks(
2098 const std::vector<cricket::StreamParams>& streams,
2099 cricket::MediaType media_type) {
2100 TrackInfos* current_tracks = GetLocalTracks(media_type);
2101
2102 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2103 // don't match the new StreamParam.
2104 TrackInfos::iterator track_it = current_tracks->begin();
2105 while (track_it != current_tracks->end()) {
2106 const TrackInfo& info = *track_it;
2107 const cricket::StreamParams* params =
2108 cricket::GetStreamBySsrc(streams, info.ssrc);
2109 if (!params || params->id != info.track_id ||
2110 params->sync_label != info.stream_label) {
2111 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2112 media_type);
2113 track_it = current_tracks->erase(track_it);
2114 } else {
2115 ++track_it;
2116 }
2117 }
2118
2119 // Find new and active tracks.
2120 for (const cricket::StreamParams& params : streams) {
2121 // The sync_label is the MediaStream label and the |stream.id| is the
2122 // track id.
2123 const std::string& stream_label = params.sync_label;
2124 const std::string& track_id = params.id;
2125 uint32_t ssrc = params.first_ssrc();
2126 const TrackInfo* track_info =
2127 FindTrackInfo(*current_tracks, stream_label, track_id);
2128 if (!track_info) {
2129 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2130 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2131 }
2132 }
2133}
2134
2135void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2136 const std::string& track_id,
2137 uint32_t ssrc,
2138 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002139 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002140 if (!sender) {
2141 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2142 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002143 return;
2144 }
2145
deadbeeffac06552015-11-25 11:26:01 -08002146 if (sender->media_type() != media_type) {
2147 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2148 << " description with an unexpected media type.";
2149 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002150 }
deadbeeffac06552015-11-25 11:26:01 -08002151
2152 sender->set_stream_id(stream_label);
2153 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002154}
2155
2156void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2157 const std::string& track_id,
2158 uint32_t ssrc,
2159 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002160 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002161 if (!sender) {
2162 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002163 // SessionDescriptions has been renegotiated.
2164 return;
2165 }
deadbeeffac06552015-11-25 11:26:01 -08002166
2167 // A sender has been removed from the SessionDescription but it's still
2168 // associated with the PeerConnection. This only occurs if the SDP doesn't
2169 // match with the calls to CreateSender, AddStream and RemoveStream.
2170 if (sender->media_type() != media_type) {
2171 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2172 << " description with an unexpected media type.";
2173 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002174 }
deadbeeffac06552015-11-25 11:26:01 -08002175
2176 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002177}
2178
2179void PeerConnection::UpdateLocalRtpDataChannels(
2180 const cricket::StreamParamsVec& streams) {
2181 std::vector<std::string> existing_channels;
2182
2183 // Find new and active data channels.
2184 for (const cricket::StreamParams& params : streams) {
2185 // |it->sync_label| is actually the data channel label. The reason is that
2186 // we use the same naming of data channels as we do for
2187 // MediaStreams and Tracks.
2188 // For MediaStreams, the sync_label is the MediaStream label and the
2189 // track label is the same as |streamid|.
2190 const std::string& channel_label = params.sync_label;
2191 auto data_channel_it = rtp_data_channels_.find(channel_label);
2192 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
2193 continue;
2194 }
2195 // Set the SSRC the data channel should use for sending.
2196 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2197 existing_channels.push_back(data_channel_it->first);
2198 }
2199
2200 UpdateClosingRtpDataChannels(existing_channels, true);
2201}
2202
2203void PeerConnection::UpdateRemoteRtpDataChannels(
2204 const cricket::StreamParamsVec& streams) {
2205 std::vector<std::string> existing_channels;
2206
2207 // Find new and active data channels.
2208 for (const cricket::StreamParams& params : streams) {
2209 // The data channel label is either the mslabel or the SSRC if the mslabel
2210 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2211 std::string label = params.sync_label.empty()
2212 ? rtc::ToString(params.first_ssrc())
2213 : params.sync_label;
2214 auto data_channel_it = rtp_data_channels_.find(label);
2215 if (data_channel_it == rtp_data_channels_.end()) {
2216 // This is a new data channel.
2217 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2218 } else {
2219 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2220 }
2221 existing_channels.push_back(label);
2222 }
2223
2224 UpdateClosingRtpDataChannels(existing_channels, false);
2225}
2226
2227void PeerConnection::UpdateClosingRtpDataChannels(
2228 const std::vector<std::string>& active_channels,
2229 bool is_local_update) {
2230 auto it = rtp_data_channels_.begin();
2231 while (it != rtp_data_channels_.end()) {
2232 DataChannel* data_channel = it->second;
2233 if (std::find(active_channels.begin(), active_channels.end(),
2234 data_channel->label()) != active_channels.end()) {
2235 ++it;
2236 continue;
2237 }
2238
2239 if (is_local_update) {
2240 data_channel->SetSendSsrc(0);
2241 } else {
2242 data_channel->RemotePeerRequestClose();
2243 }
2244
2245 if (data_channel->state() == DataChannel::kClosed) {
2246 rtp_data_channels_.erase(it);
2247 it = rtp_data_channels_.begin();
2248 } else {
2249 ++it;
2250 }
2251 }
2252}
2253
2254void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2255 uint32_t remote_ssrc) {
2256 rtc::scoped_refptr<DataChannel> channel(
2257 InternalCreateDataChannel(label, nullptr));
2258 if (!channel.get()) {
2259 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2260 << "CreateDataChannel failed.";
2261 return;
2262 }
2263 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002264 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2265 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002266 // Call both the raw pointer and scoped_refptr versions of the method
2267 // for compatibility.
2268 observer_->OnDataChannel(proxy_channel.get());
2269 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002270}
2271
2272rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2273 const std::string& label,
2274 const InternalDataChannelInit* config) {
2275 if (IsClosed()) {
2276 return nullptr;
2277 }
2278 if (session_->data_channel_type() == cricket::DCT_NONE) {
2279 LOG(LS_ERROR)
2280 << "InternalCreateDataChannel: Data is not supported in this call.";
2281 return nullptr;
2282 }
2283 InternalDataChannelInit new_config =
2284 config ? (*config) : InternalDataChannelInit();
2285 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2286 if (new_config.id < 0) {
2287 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002288 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002289 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2290 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2291 return nullptr;
2292 }
2293 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2294 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2295 << "because the id is already in use or out of range.";
2296 return nullptr;
2297 }
2298 }
2299
2300 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2301 session_.get(), session_->data_channel_type(), label, new_config));
2302 if (!channel) {
2303 sid_allocator_.ReleaseSid(new_config.id);
2304 return nullptr;
2305 }
2306
2307 if (channel->data_channel_type() == cricket::DCT_RTP) {
2308 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2309 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2310 << " already exists.";
2311 return nullptr;
2312 }
2313 rtp_data_channels_[channel->label()] = channel;
2314 } else {
2315 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2316 sctp_data_channels_.push_back(channel);
2317 channel->SignalClosed.connect(this,
2318 &PeerConnection::OnSctpDataChannelClosed);
2319 }
2320
hbos82ebe022016-11-14 01:41:09 -08002321 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002322 return channel;
2323}
2324
2325bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002326#ifdef HAVE_QUIC
2327 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2328 (session_->quic_data_transport() &&
2329 session_->quic_data_transport()->HasDataChannels());
2330#else
deadbeefab9b2d12015-10-14 11:33:11 -07002331 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002332#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002333}
2334
2335void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2336 for (const auto& channel : sctp_data_channels_) {
2337 if (channel->id() < 0) {
2338 int sid;
2339 if (!sid_allocator_.AllocateSid(role, &sid)) {
2340 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2341 continue;
2342 }
2343 channel->SetSctpSid(sid);
2344 }
2345 }
2346}
2347
2348void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002349 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002350 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2351 ++it) {
2352 if (it->get() == channel) {
2353 if (channel->id() >= 0) {
2354 sid_allocator_.ReleaseSid(channel->id());
2355 }
deadbeefbd292462015-12-14 18:15:29 -08002356 // Since this method is triggered by a signal from the DataChannel,
2357 // we can't free it directly here; we need to free it asynchronously.
2358 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002359 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002360 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2361 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002362 return;
2363 }
2364 }
2365}
2366
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002367void PeerConnection::OnVoiceChannelCreated() {
2368 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2369 session_->voice_channel(), senders_, receivers_,
2370 cricket::MEDIA_TYPE_AUDIO);
2371}
2372
deadbeefab9b2d12015-10-14 11:33:11 -07002373void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002374 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2375 cricket::VoiceChannel>(
2376 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2377}
2378
2379void PeerConnection::OnVideoChannelCreated() {
2380 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2381 session_->video_channel(), senders_, receivers_,
2382 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002383}
2384
2385void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002386 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2387 cricket::VideoChannel>(
2388 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002389}
2390
2391void PeerConnection::OnDataChannelCreated() {
2392 for (const auto& channel : sctp_data_channels_) {
2393 channel->OnTransportChannelCreated();
2394 }
2395}
2396
2397void PeerConnection::OnDataChannelDestroyed() {
2398 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2399 // DataChannel may callback to us and try to modify the list.
2400 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2401 temp_rtp_dcs.swap(rtp_data_channels_);
2402 for (const auto& kv : temp_rtp_dcs) {
2403 kv.second->OnTransportChannelDestroyed();
2404 }
2405
2406 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2407 temp_sctp_dcs.swap(sctp_data_channels_);
2408 for (const auto& channel : temp_sctp_dcs) {
2409 channel->OnTransportChannelDestroyed();
2410 }
2411}
2412
2413void PeerConnection::OnDataChannelOpenMessage(
2414 const std::string& label,
2415 const InternalDataChannelInit& config) {
2416 rtc::scoped_refptr<DataChannel> channel(
2417 InternalCreateDataChannel(label, &config));
2418 if (!channel.get()) {
2419 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2420 return;
2421 }
2422
deadbeefa601f5c2016-06-06 14:27:39 -07002423 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2424 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002425 // Call both the raw pointer and scoped_refptr versions of the method
2426 // for compatibility.
2427 observer_->OnDataChannel(proxy_channel.get());
2428 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002429}
2430
deadbeefa601f5c2016-06-06 14:27:39 -07002431RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2432 auto it = std::find_if(
2433 senders_.begin(), senders_.end(),
2434 [id](const rtc::scoped_refptr<
2435 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2436 return sender->id() == id;
2437 });
2438 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002439}
2440
deadbeefa601f5c2016-06-06 14:27:39 -07002441std::vector<
2442 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002443PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2444 return std::find_if(
2445 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002446 [track](const rtc::scoped_refptr<
2447 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002448 return sender->track() == track;
2449 });
2450}
2451
deadbeefa601f5c2016-06-06 14:27:39 -07002452std::vector<rtc::scoped_refptr<
2453 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002454PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002455 return std::find_if(
2456 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002457 [track_id](const rtc::scoped_refptr<
2458 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002459 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002460 });
2461}
2462
deadbeefab9b2d12015-10-14 11:33:11 -07002463PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2464 cricket::MediaType media_type) {
2465 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2466 media_type == cricket::MEDIA_TYPE_VIDEO);
2467 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2468 : &remote_video_tracks_;
2469}
2470
2471PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2472 cricket::MediaType media_type) {
2473 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2474 media_type == cricket::MEDIA_TYPE_VIDEO);
2475 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2476 : &local_video_tracks_;
2477}
2478
2479const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2480 const PeerConnection::TrackInfos& infos,
2481 const std::string& stream_label,
2482 const std::string track_id) const {
2483 for (const TrackInfo& track_info : infos) {
2484 if (track_info.stream_label == stream_label &&
2485 track_info.track_id == track_id) {
2486 return &track_info;
2487 }
2488 }
2489 return nullptr;
2490}
2491
2492DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2493 for (const auto& channel : sctp_data_channels_) {
2494 if (channel->id() == sid) {
2495 return channel;
2496 }
2497 }
2498 return nullptr;
2499}
2500
deadbeef91dd5672016-05-18 16:55:30 -07002501bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002502 const RTCConfiguration& configuration) {
2503 cricket::ServerAddresses stun_servers;
2504 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002505 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2506 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002507 return false;
2508 }
2509
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002510 port_allocator_->Initialize();
2511
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002512 // To handle both internal and externally created port allocator, we will
2513 // enable BUNDLE here.
2514 int portallocator_flags = port_allocator_->flags();
2515 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2516 cricket::PORTALLOCATOR_ENABLE_IPV6;
2517 // If the disable-IPv6 flag was specified, we'll not override it
2518 // by experiment.
2519 if (configuration.disable_ipv6) {
2520 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2521 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2522 "Disabled") {
2523 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2524 }
2525
2526 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2527 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2528 LOG(LS_INFO) << "TCP candidates are disabled.";
2529 }
2530
honghaiz60347052016-05-31 18:29:12 -07002531 if (configuration.candidate_network_policy ==
2532 kCandidateNetworkPolicyLowCost) {
2533 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2534 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2535 }
2536
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002537 port_allocator_->set_flags(portallocator_flags);
2538 // No step delay is used while allocating ports.
2539 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2540 port_allocator_->set_candidate_filter(
2541 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2542
2543 // Call this last since it may create pooled allocator sessions using the
2544 // properties set above.
2545 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002546 configuration.ice_candidate_pool_size,
2547 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002548 return true;
2549}
2550
deadbeef91dd5672016-05-18 16:55:30 -07002551bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002552 const cricket::ServerAddresses& stun_servers,
2553 const std::vector<cricket::RelayServerConfig>& turn_servers,
2554 IceTransportsType type,
2555 int candidate_pool_size,
2556 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002557 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002558 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002559 // Call this last since it may create pooled allocator sessions using the
2560 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002561 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002562 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002563}
2564
ivoc14d5dbe2016-07-04 07:06:55 -07002565bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2566 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002567 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002568}
2569
2570void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002571 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002572}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573} // namespace webrtc