blob: ba21429d8585fe1d43fe68b0f478c0a623eef89e [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
ossu7bb87ee2017-01-23 04:56:25 -080011#include "webrtc/pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
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/jsepicecandidate.h"
19#include "webrtc/api/jsepsessiondescription.h"
20#include "webrtc/api/mediaconstraintsinterface.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010021#include "webrtc/api/mediastreamproxy.h"
22#include "webrtc/api/mediastreamtrackproxy.h"
tfarina5237aaf2015-11-10 23:44:30 -080023#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070024#include "webrtc/base/bind.h"
nissec80e7412017-01-11 05:56:46 -080025#include "webrtc/base/checks.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000026#include "webrtc/base/logging.h"
27#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070028#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010029#include "webrtc/base/trace_event.h"
ossuf515ab82016-12-07 04:52:58 -080030#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070031#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
deadbeef953c2ce2017-01-09 14:53:41 -080032#include "webrtc/media/sctp/sctptransport.h"
ossu7bb87ee2017-01-23 04:56:25 -080033#include "webrtc/pc/audiotrack.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010034#include "webrtc/pc/channelmanager.h"
ossu7bb87ee2017-01-23 04:56:25 -080035#include "webrtc/pc/dtmfsender.h"
36#include "webrtc/pc/mediastream.h"
37#include "webrtc/pc/mediastreamobserver.h"
38#include "webrtc/pc/remoteaudiosource.h"
39#include "webrtc/pc/rtpreceiver.h"
40#include "webrtc/pc/rtpsender.h"
41#include "webrtc/pc/streamcollection.h"
42#include "webrtc/pc/videocapturertracksource.h"
43#include "webrtc/pc/videotrack.h"
44#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010045#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046
47namespace {
48
deadbeefab9b2d12015-10-14 11:33:11 -070049using webrtc::DataChannel;
50using webrtc::MediaConstraintsInterface;
51using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080053using webrtc::RTCError;
54using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070055using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080056using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070057using webrtc::RtpSenderProxy;
58using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070059using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
deadbeefab9b2d12015-10-14 11:33:11 -070061static const char kDefaultStreamLabel[] = "default";
62static const char kDefaultAudioTrackLabel[] = "defaulta0";
63static const char kDefaultVideoTrackLabel[] = "defaultv0";
64
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065// The min number of tokens must present in Turn host uri.
66// e.g. user@turn.example.org
67static const size_t kTurnHostTokensNum = 2;
68// Number of tokens must be preset when TURN uri has transport param.
69static const size_t kTurnTransportTokensNum = 2;
70// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000071static const int kDefaultStunPort = 3478;
72static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
75// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070076static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077
zhihuang8f65cdf2016-05-06 18:40:30 -070078// The length of RTCP CNAMEs.
79static const int kRtcpCnameLength = 16;
80
deadbeef0a6c4ca2015-10-06 11:38:28 -070081// NOTE: A loop below assumes that the first value of this enum is 0 and all
82// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070084 STUN = 0, // Indicates a STUN server.
85 STUNS, // Indicates a STUN server used with a TLS session.
86 TURN, // Indicates a TURN server
87 TURNS, // Indicates a TURN server used with a TLS session.
88 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089};
tfarina5237aaf2015-11-10 23:44:30 -080090static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070091 "kValidIceServiceTypes must have as many strings as ServiceType "
92 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
94enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000095 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070097 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080099 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100};
101
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000102struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103 explicit SetSessionDescriptionMsg(
104 webrtc::SetSessionDescriptionObserver* observer)
105 : observer(observer) {
106 }
107
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000108 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 std::string error;
110};
111
deadbeefab9b2d12015-10-14 11:33:11 -0700112struct CreateSessionDescriptionMsg : public rtc::MessageData {
113 explicit CreateSessionDescriptionMsg(
114 webrtc::CreateSessionDescriptionObserver* observer)
115 : observer(observer) {}
116
117 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
118 std::string error;
119};
120
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000121struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000122 GetStatsMsg(webrtc::StatsObserver* observer,
123 webrtc::MediaStreamTrackInterface* track)
124 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000126 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000127 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000128};
129
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000130// |in_str| should be of format
131// stunURI = scheme ":" stun-host [ ":" stun-port ]
132// scheme = "stun" / "stuns"
133// stun-host = IP-literal / IPv4address / reg-name
134// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700135//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000136// draft-petithuguenin-behave-turn-uris-01
137// turnURI = scheme ":" turn-host [ ":" turn-port ]
138// turn-host = username@IP-literal / IPv4address / reg-name
139bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
140 ServiceType* service_type,
141 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200142 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700143 if (colonpos == std::string::npos) {
144 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000145 return false;
146 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700147 if ((colonpos + 1) == in_str.length()) {
148 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
149 return false;
150 }
151 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800152 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700153 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000154 *service_type = static_cast<ServiceType>(i);
155 break;
156 }
157 }
158 if (*service_type == INVALID) {
159 return false;
160 }
161 *hostname = in_str.substr(colonpos + 1, std::string::npos);
162 return true;
163}
164
deadbeef0a6c4ca2015-10-06 11:38:28 -0700165bool ParsePort(const std::string& in_str, int* port) {
166 // Make sure port only contains digits. FromString doesn't check this.
167 for (const char& c : in_str) {
168 if (!std::isdigit(c)) {
169 return false;
170 }
171 }
172 return rtc::FromString(in_str, port);
173}
174
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000175// This method parses IPv6 and IPv4 literal strings, along with hostnames in
176// standard hostname:port format.
177// Consider following formats as correct.
178// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700179// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000180bool ParseHostnameAndPortFromString(const std::string& in_str,
181 std::string* host,
182 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700183 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 if (in_str.at(0) == '[') {
185 std::string::size_type closebracket = in_str.rfind(']');
186 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000187 std::string::size_type colonpos = in_str.find(':', closebracket);
188 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700189 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
190 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000191 return false;
192 }
193 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700194 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000195 } else {
196 return false;
197 }
198 } else {
199 std::string::size_type colonpos = in_str.find(':');
200 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 return false;
203 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700204 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000205 } else {
206 *host = in_str;
207 }
208 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700209 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000210}
211
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800212// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700213// by parsing |url| and using the username/password in |server|.
deadbeef293e9262017-01-11 12:28:30 -0800214RTCErrorType ParseIceServerUrl(
215 const PeerConnectionInterface::IceServer& server,
216 const std::string& url,
217 cricket::ServerAddresses* stun_servers,
218 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219 // draft-nandakumar-rtcweb-stun-uri-01
220 // stunURI = scheme ":" stun-host [ ":" stun-port ]
221 // scheme = "stun" / "stuns"
222 // stun-host = IP-literal / IPv4address / reg-name
223 // stun-port = *DIGIT
224
225 // draft-petithuguenin-behave-turn-uris-01
226 // turnURI = scheme ":" turn-host [ ":" turn-port ]
227 // [ "?transport=" transport ]
228 // scheme = "turn" / "turns"
229 // transport = "udp" / "tcp" / transport-ext
230 // transport-ext = 1*unreserved
231 // turn-host = IP-literal / IPv4address / reg-name
232 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800233 RTC_DCHECK(stun_servers != nullptr);
234 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200235 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800236 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700237 RTC_DCHECK(!url.empty());
hnslbd44bb02016-12-12 03:14:30 -0800238 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200239 std::string uri_without_transport = tokens[0];
240 // Let's look into transport= param, if it exists.
241 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
242 std::string uri_transport_param = tokens[1];
hnslbd44bb02016-12-12 03:14:30 -0800243 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
244 if (tokens[0] != kTransport) {
245 LOG(LS_WARNING) << "Invalid transport parameter key.";
deadbeef293e9262017-01-11 12:28:30 -0800246 return RTCErrorType::SYNTAX_ERROR;
hnslbd44bb02016-12-12 03:14:30 -0800247 }
248 if (tokens.size() < 2 ||
249 !cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
250 (turn_transport_type != cricket::PROTO_UDP &&
251 turn_transport_type != cricket::PROTO_TCP)) {
252 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef293e9262017-01-11 12:28:30 -0800253 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200255 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200257 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700258 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200259 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
260 &service_type,
261 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
deadbeef293e9262017-01-11 12:28:30 -0800263 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200264 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000265
deadbeef0a6c4ca2015-10-06 11:38:28 -0700266 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
267 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200268
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200269 // Let's break hostname.
270 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700271 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
272
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200273 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700274 if (tokens.size() > kTurnHostTokensNum) {
275 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800276 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700277 }
278 if (tokens.size() == kTurnHostTokensNum) {
279 if (tokens[0].empty() || tokens[1].empty()) {
280 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800281 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200283 username.assign(rtc::s_url_decode(tokens[0]));
284 hoststring = tokens[1];
285 } else {
286 hoststring = tokens[0];
287 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000288
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200289 int port = kDefaultStunPort;
290 if (service_type == TURNS) {
291 port = kDefaultStunTlsPort;
hnsl277b2502016-12-13 05:17:23 -0800292 turn_transport_type = cricket::PROTO_TLS;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200293 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000294
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200295 std::string address;
296 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700297 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
deadbeef293e9262017-01-11 12:28:30 -0800298 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000300
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200301 if (port <= 0 || port > 0xffff) {
302 LOG(WARNING) << "Invalid port: " << port;
deadbeef293e9262017-01-11 12:28:30 -0800303 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200304 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000305
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200306 switch (service_type) {
307 case STUN:
308 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800309 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200310 break;
311 case TURN:
312 case TURNS: {
deadbeef293e9262017-01-11 12:28:30 -0800313 if (username.empty() || server.password.empty()) {
314 // The WebRTC spec requires throwing an InvalidAccessError when username
315 // or credential are ommitted; this is the native equivalent.
316 return RTCErrorType::INVALID_PARAMETER;
317 }
hnsl04833622017-01-09 08:35:45 -0800318 cricket::RelayServerConfig config = cricket::RelayServerConfig(
319 address, port, username, server.password, turn_transport_type);
320 if (server.tls_cert_policy ==
321 PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
322 config.tls_cert_policy =
323 cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
324 }
325 turn_servers->push_back(config);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200326 break;
327 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200328 default:
deadbeef293e9262017-01-11 12:28:30 -0800329 // We shouldn't get to this point with an invalid service_type, we should
330 // have returned an error already.
nisseeb4ca4e2017-01-12 02:24:27 -0800331 RTC_NOTREACHED() << "Unexpected service type";
deadbeef293e9262017-01-11 12:28:30 -0800332 return RTCErrorType::INTERNAL_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200333 }
deadbeef293e9262017-01-11 12:28:30 -0800334 return RTCErrorType::NONE;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200335}
336
deadbeefab9b2d12015-10-14 11:33:11 -0700337// Check if we can send |new_stream| on a PeerConnection.
338bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
339 webrtc::MediaStreamInterface* new_stream) {
340 if (!new_stream || !current_streams) {
341 return false;
342 }
343 if (current_streams->find(new_stream->label()) != nullptr) {
344 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
345 << " is already added.";
346 return false;
347 }
348 return true;
349}
350
351bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
352 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
353}
354
deadbeef5e97fb52015-10-15 12:49:08 -0700355// If the direction is "recvonly" or "inactive", treat the description
356// as containing no streams.
357// See: https://code.google.com/p/webrtc/issues/detail?id=5054
358std::vector<cricket::StreamParams> GetActiveStreams(
359 const cricket::MediaContentDescription* desc) {
360 return MediaContentDirectionHasSend(desc->direction())
361 ? desc->streams()
362 : std::vector<cricket::StreamParams>();
363}
364
deadbeefab9b2d12015-10-14 11:33:11 -0700365bool IsValidOfferToReceiveMedia(int value) {
366 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
367 return (value >= Options::kUndefined) &&
368 (value <= Options::kMaxOfferToReceiveMedia);
369}
370
371// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800372void AddSendStreams(
373 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700374 const std::vector<rtc::scoped_refptr<
375 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800376 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
377 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700378 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800379 for (const auto& sender : senders) {
380 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700381 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700382 }
383
384 // Check for data channels.
385 for (const auto& kv : rtp_data_channels) {
386 const DataChannel* channel = kv.second;
387 if (channel->state() == DataChannel::kConnecting ||
388 channel->state() == DataChannel::kOpen) {
389 // |streamid| and |sync_label| are both set to the DataChannel label
390 // here so they can be signaled the same way as MediaStreams and Tracks.
391 // For MediaStreams, the sync_label is the MediaStream label and the
392 // track label is the same as |streamid|.
393 const std::string& streamid = channel->label();
394 const std::string& sync_label = channel->label();
395 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
396 sync_label);
397 }
398 }
399}
400
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700401uint32_t ConvertIceTransportTypeToCandidateFilter(
402 PeerConnectionInterface::IceTransportsType type) {
403 switch (type) {
404 case PeerConnectionInterface::kNone:
405 return cricket::CF_NONE;
406 case PeerConnectionInterface::kRelay:
407 return cricket::CF_RELAY;
408 case PeerConnectionInterface::kNoHost:
409 return (cricket::CF_ALL & ~cricket::CF_HOST);
410 case PeerConnectionInterface::kAll:
411 return cricket::CF_ALL;
412 default:
nissec80e7412017-01-11 05:56:46 -0800413 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700414 }
415 return cricket::CF_NONE;
416}
417
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700418// Helper method to set a voice/video channel on all applicable senders
419// and receivers when one is created/destroyed by WebRtcSession.
420//
421// Used by On(Voice|Video)Channel(Created|Destroyed)
422template <class SENDER,
423 class RECEIVER,
424 class CHANNEL,
425 class SENDERS,
426 class RECEIVERS>
427void SetChannelOnSendersAndReceivers(CHANNEL* channel,
428 SENDERS& senders,
429 RECEIVERS& receivers,
430 cricket::MediaType media_type) {
431 for (auto& sender : senders) {
432 if (sender->media_type() == media_type) {
433 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
434 }
435 }
436 for (auto& receiver : receivers) {
437 if (receiver->media_type() == media_type) {
438 if (!channel) {
439 receiver->internal()->Stop();
440 }
441 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
442 }
443 }
444}
445
deadbeef293e9262017-01-11 12:28:30 -0800446// Helper to set an error and return from a method.
447bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
448 if (error) {
449 error->set_type(type);
450 }
451 return type == webrtc::RTCErrorType::NONE;
452}
453
deadbeef0a6c4ca2015-10-06 11:38:28 -0700454} // namespace
455
456namespace webrtc {
457
deadbeef293e9262017-01-11 12:28:30 -0800458static const char* const kRTCErrorTypeNames[] = {
deadbeef3edec7c2016-12-10 11:44:26 -0800459 "NONE",
460 "UNSUPPORTED_PARAMETER",
461 "INVALID_PARAMETER",
462 "INVALID_RANGE",
463 "SYNTAX_ERROR",
464 "INVALID_STATE",
465 "INVALID_MODIFICATION",
466 "NETWORK_ERROR",
467 "INTERNAL_ERROR",
468};
deadbeef293e9262017-01-11 12:28:30 -0800469static_assert(static_cast<int>(RTCErrorType::INTERNAL_ERROR) ==
470 (arraysize(kRTCErrorTypeNames) - 1),
471 "kRTCErrorTypeNames must have as many strings as RTCErrorType "
472 "has values.");
deadbeef3edec7c2016-12-10 11:44:26 -0800473
deadbeef293e9262017-01-11 12:28:30 -0800474std::ostream& operator<<(std::ostream& stream, RTCErrorType error) {
deadbeef3edec7c2016-12-10 11:44:26 -0800475 int index = static_cast<int>(error);
deadbeef293e9262017-01-11 12:28:30 -0800476 return stream << kRTCErrorTypeNames[index];
477}
478
479bool PeerConnectionInterface::RTCConfiguration::operator==(
480 const PeerConnectionInterface::RTCConfiguration& o) const {
481 // This static_assert prevents us from accidentally breaking operator==.
482 struct stuff_being_tested_for_equality {
483 IceTransportsType type;
484 IceServers servers;
485 BundlePolicy bundle_policy;
486 RtcpMuxPolicy rtcp_mux_policy;
487 TcpCandidatePolicy tcp_candidate_policy;
488 CandidateNetworkPolicy candidate_network_policy;
489 int audio_jitter_buffer_max_packets;
490 bool audio_jitter_buffer_fast_accelerate;
491 int ice_connection_receiving_timeout;
492 int ice_backup_candidate_pair_ping_interval;
493 ContinualGatheringPolicy continual_gathering_policy;
494 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
495 bool prioritize_most_likely_ice_candidate_pairs;
496 struct cricket::MediaConfig media_config;
497 bool disable_ipv6;
498 bool enable_rtp_data_channel;
499 bool enable_quic;
500 rtc::Optional<int> screencast_min_bitrate;
501 rtc::Optional<bool> combined_audio_video_bwe;
502 rtc::Optional<bool> enable_dtls_srtp;
503 int ice_candidate_pool_size;
504 bool prune_turn_ports;
505 bool presume_writable_when_fully_relayed;
506 bool enable_ice_renomination;
507 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800508 rtc::Optional<int> ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800509 };
510 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
511 "Did you add something to RTCConfiguration and forget to "
512 "update operator==?");
513 return type == o.type && servers == o.servers &&
514 bundle_policy == o.bundle_policy &&
515 rtcp_mux_policy == o.rtcp_mux_policy &&
516 tcp_candidate_policy == o.tcp_candidate_policy &&
517 candidate_network_policy == o.candidate_network_policy &&
518 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
519 audio_jitter_buffer_fast_accelerate ==
520 o.audio_jitter_buffer_fast_accelerate &&
521 ice_connection_receiving_timeout ==
522 o.ice_connection_receiving_timeout &&
523 ice_backup_candidate_pair_ping_interval ==
524 o.ice_backup_candidate_pair_ping_interval &&
525 continual_gathering_policy == o.continual_gathering_policy &&
526 certificates == o.certificates &&
527 prioritize_most_likely_ice_candidate_pairs ==
528 o.prioritize_most_likely_ice_candidate_pairs &&
529 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
530 enable_rtp_data_channel == o.enable_rtp_data_channel &&
531 enable_quic == o.enable_quic &&
532 screencast_min_bitrate == o.screencast_min_bitrate &&
533 combined_audio_video_bwe == o.combined_audio_video_bwe &&
534 enable_dtls_srtp == o.enable_dtls_srtp &&
535 ice_candidate_pool_size == o.ice_candidate_pool_size &&
536 prune_turn_ports == o.prune_turn_ports &&
537 presume_writable_when_fully_relayed ==
538 o.presume_writable_when_fully_relayed &&
539 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800540 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
541 ice_check_min_interval == o.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800542}
543
544bool PeerConnectionInterface::RTCConfiguration::operator!=(
545 const PeerConnectionInterface::RTCConfiguration& o) const {
546 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800547}
548
zhihuang8f65cdf2016-05-06 18:40:30 -0700549// Generate a RTCP CNAME when a PeerConnection is created.
550std::string GenerateRtcpCname() {
551 std::string cname;
552 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
553 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800554 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700555 }
556 return cname;
557}
558
htaa2a49d92016-03-04 02:51:39 -0800559bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700560 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800561 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700562 cricket::MediaSessionOptions* session_options) {
563 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
564 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
565 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
566 return false;
567 }
568
htaaac2dea2016-03-10 13:35:55 -0800569 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700570 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700571 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800572 } else {
573 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700574 }
htaaac2dea2016-03-10 13:35:55 -0800575 // For offers, we only offer video if we have it or it's forced by options.
576 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700577 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700578 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800579 } else if (is_offer) {
580 session_options->recv_video = false;
581 } else {
582 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700583 }
584
585 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700586 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800587 for (auto& kv : session_options->transport_options) {
588 kv.second.ice_restart = rtc_options.ice_restart;
589 }
deadbeefab9b2d12015-10-14 11:33:11 -0700590
591 return true;
592}
593
594bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
595 cricket::MediaSessionOptions* session_options) {
596 bool value = false;
597 size_t mandatory_constraints_satisfied = 0;
598
599 // kOfferToReceiveAudio defaults to true according to spec.
600 if (!FindConstraint(constraints,
601 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
602 &mandatory_constraints_satisfied) ||
603 value) {
604 session_options->recv_audio = true;
605 }
606
607 // kOfferToReceiveVideo defaults to false according to spec. But
608 // if it is an answer and video is offered, we should still accept video
609 // per default.
610 value = false;
611 if (!FindConstraint(constraints,
612 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
613 &mandatory_constraints_satisfied) ||
614 value) {
615 session_options->recv_video = true;
616 }
617
618 if (FindConstraint(constraints,
619 MediaConstraintsInterface::kVoiceActivityDetection, &value,
620 &mandatory_constraints_satisfied)) {
621 session_options->vad_enabled = value;
622 }
623
624 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
625 &mandatory_constraints_satisfied)) {
626 session_options->bundle_enabled = value;
627 } else {
628 // kUseRtpMux defaults to true according to spec.
629 session_options->bundle_enabled = true;
630 }
deadbeefab9b2d12015-10-14 11:33:11 -0700631
deadbeef0ed85b22016-02-23 17:24:52 -0800632 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700633 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
634 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700635 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800636 ice_restart = true;
637 }
638 for (auto& kv : session_options->transport_options) {
639 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700640 }
641
642 if (!constraints) {
643 return true;
644 }
645 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
646}
647
deadbeef293e9262017-01-11 12:28:30 -0800648RTCErrorType ParseIceServers(
649 const PeerConnectionInterface::IceServers& servers,
650 cricket::ServerAddresses* stun_servers,
651 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200652 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
653 if (!server.urls.empty()) {
654 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200655 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700656 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800657 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200658 }
deadbeef293e9262017-01-11 12:28:30 -0800659 RTCErrorType err =
660 ParseIceServerUrl(server, url, stun_servers, turn_servers);
661 if (err != RTCErrorType::NONE) {
662 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200663 }
664 }
665 } else if (!server.uri.empty()) {
666 // Fallback to old .uri if new .urls isn't present.
deadbeef293e9262017-01-11 12:28:30 -0800667 RTCErrorType err =
668 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
669 if (err != RTCErrorType::NONE) {
670 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200671 }
672 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700673 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800674 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675 }
676 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800677 // Candidates must have unique priorities, so that connectivity checks
678 // are performed in a well-defined order.
679 int priority = static_cast<int>(turn_servers->size() - 1);
680 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
681 // First in the list gets highest priority.
682 turn_server.priority = priority--;
683 }
deadbeef293e9262017-01-11 12:28:30 -0800684 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685}
686
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000687PeerConnection::PeerConnection(PeerConnectionFactory* factory)
688 : factory_(factory),
689 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000690 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700693 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800694 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700695 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700696 local_streams_(StreamCollection::Create()),
697 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698
699PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100700 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700701 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700702 // Need to detach RTP senders/receivers from WebRtcSession,
703 // since it's about to be destroyed.
704 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700705 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700706 }
707 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700708 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700709 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700710 // Destroy stats_ because it depends on session_.
711 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800712 if (stats_collector_) {
713 stats_collector_->WaitForPendingRequest();
714 stats_collector_ = nullptr;
715 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700716 // Now destroy session_ before destroying other members,
717 // because its destruction fires signals (such as VoiceChannelDestroyed)
718 // which will trigger some final actions in PeerConnection...
719 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700720 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700721 network_thread()->Invoke<void>(RTC_FROM_HERE,
722 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723}
724
725bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000726 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700727 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200728 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800729 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100730 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800731 if (!allocator) {
732 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
733 << "This shouldn't happen if using PeerConnectionFactory.";
734 return false;
735 }
deadbeef653b8e02015-11-11 12:55:10 -0800736 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800737 // TODO(deadbeef): Why do we do this?
738 LOG(LS_ERROR) << "PeerConnection initialized without a "
739 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800740 return false;
741 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000742 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800743 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800744
deadbeef91dd5672016-05-18 16:55:30 -0700745 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700746 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700747 if (!network_thread()->Invoke<bool>(
748 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
749 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750 return false;
751 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752
skvlad11a9cbf2016-10-07 11:53:05 -0700753 media_controller_.reset(factory_->CreateMediaController(
754 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000755
zhihuang29ff8442016-07-27 11:07:25 -0700756 session_.reset(new WebRtcSession(
757 media_controller_.get(), factory_->network_thread(),
758 factory_->worker_thread(), factory_->signaling_thread(),
759 port_allocator_.get(),
760 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700761 factory_->CreateTransportController(
762 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800763 configuration.redetermine_role_on_ice_restart)),
764#ifdef HAVE_SCTP
765 std::unique_ptr<cricket::SctpTransportInternalFactory>(
766 new cricket::SctpTransportFactory(factory_->network_thread()))
767#else
768 nullptr
769#endif
770 ));
zhihuang29ff8442016-07-27 11:07:25 -0700771
deadbeefab9b2d12015-10-14 11:33:11 -0700772 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700773 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000774
775 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200776 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800777 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700779 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000781 // Register PeerConnection as receiver of local ice candidates.
782 // All the callbacks will be posted to the application from PeerConnection.
783 session_->RegisterIceObserver(this);
784 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700785 session_->SignalVoiceChannelCreated.connect(
786 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700787 session_->SignalVoiceChannelDestroyed.connect(
788 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700789 session_->SignalVideoChannelCreated.connect(
790 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700791 session_->SignalVideoChannelDestroyed.connect(
792 this, &PeerConnection::OnVideoChannelDestroyed);
793 session_->SignalDataChannelCreated.connect(
794 this, &PeerConnection::OnDataChannelCreated);
795 session_->SignalDataChannelDestroyed.connect(
796 this, &PeerConnection::OnDataChannelDestroyed);
797 session_->SignalDataChannelOpenMessage.connect(
798 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800799
800 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801 return true;
802}
803
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000804rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700806 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807}
808
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000809rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700811 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812}
813
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000814bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100815 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000816 if (IsClosed()) {
817 return false;
818 }
deadbeefab9b2d12015-10-14 11:33:11 -0700819 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000820 return false;
821 }
deadbeefab9b2d12015-10-14 11:33:11 -0700822
823 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800824 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
825 observer->SignalAudioTrackAdded.connect(this,
826 &PeerConnection::OnAudioTrackAdded);
827 observer->SignalAudioTrackRemoved.connect(
828 this, &PeerConnection::OnAudioTrackRemoved);
829 observer->SignalVideoTrackAdded.connect(this,
830 &PeerConnection::OnVideoTrackAdded);
831 observer->SignalVideoTrackRemoved.connect(
832 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700833 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700834
deadbeefab9b2d12015-10-14 11:33:11 -0700835 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800836 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700837 }
838 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800839 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700840 }
841
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000842 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 observer_->OnRenegotiationNeeded();
844 return true;
845}
846
847void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100848 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700849 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800850 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700851 }
852 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800853 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700854 }
855
856 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800857 stream_observers_.erase(
858 std::remove_if(
859 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700860 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800861 return observer->stream()->label().compare(local_stream->label()) ==
862 0;
863 }),
864 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700865
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866 if (IsClosed()) {
867 return;
868 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869 observer_->OnRenegotiationNeeded();
870}
871
deadbeefe1f9d832016-01-14 15:35:42 -0800872rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
873 MediaStreamTrackInterface* track,
874 std::vector<MediaStreamInterface*> streams) {
875 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
876 if (IsClosed()) {
877 return nullptr;
878 }
879 if (streams.size() >= 2) {
880 LOG(LS_ERROR)
881 << "Adding a track with two streams is not currently supported.";
882 return nullptr;
883 }
884 // TODO(deadbeef): Support adding a track to two different senders.
885 if (FindSenderForTrack(track) != senders_.end()) {
886 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
887 return nullptr;
888 }
889
890 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700891 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800892 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700893 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800894 signaling_thread(),
895 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700896 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800897 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700898 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800899 }
900 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700901 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800902 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700903 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800904 }
905 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700906 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800907 signaling_thread(),
908 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700909 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800910 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700911 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800912 }
913 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700914 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800915 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700916 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800917 }
918 } else {
919 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
920 return rtc::scoped_refptr<RtpSenderInterface>();
921 }
922
923 senders_.push_back(new_sender);
924 observer_->OnRenegotiationNeeded();
925 return new_sender;
926}
927
928bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
929 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
930 if (IsClosed()) {
931 return false;
932 }
933
934 auto it = std::find(senders_.begin(), senders_.end(), sender);
935 if (it == senders_.end()) {
936 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
937 return false;
938 }
deadbeefa601f5c2016-06-06 14:27:39 -0700939 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800940 senders_.erase(it);
941
942 observer_->OnRenegotiationNeeded();
943 return true;
944}
945
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000946rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100948 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700949 if (IsClosed()) {
950 return nullptr;
951 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 if (!track) {
953 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800954 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 }
deadbeef20cb0c12017-02-01 20:27:00 -0800956 auto it = FindSenderForTrack(track);
957 if (it == senders_.end()) {
958 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
959 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 }
961
deadbeef20cb0c12017-02-01 20:27:00 -0800962 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963}
964
deadbeeffac06552015-11-25 11:26:01 -0800965rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800966 const std::string& kind,
967 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100968 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700969 if (IsClosed()) {
970 return nullptr;
971 }
deadbeefa601f5c2016-06-06 14:27:39 -0700972 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800973 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700974 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700975 signaling_thread(),
976 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800977 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700978 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700979 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800980 } else {
981 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800982 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800983 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800984 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700985 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800986 }
deadbeeffac06552015-11-25 11:26:01 -0800987 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800988 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800989}
990
deadbeef70ab1a12015-09-28 16:53:55 -0700991std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
992 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700993 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
994 for (const auto& sender : senders_) {
995 ret.push_back(sender.get());
996 }
997 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700998}
999
1000std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1001PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001002 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
1003 for (const auto& receiver : receivers_) {
1004 ret.push_back(receiver.get());
1005 }
1006 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001007}
1008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001010 MediaStreamTrackInterface* track,
1011 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001012 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001013 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001014 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1016 return false;
1017 }
1018
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001019 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001020 // The StatsCollector is used to tell if a track is valid because it may
1021 // remember tracks that the PeerConnection previously removed.
1022 if (track && !stats_->IsValidTrack(track->id())) {
1023 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1024 << track->id();
1025 return false;
1026 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001027 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001028 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001029 return true;
1030}
1031
hbos74e1a4f2016-09-15 23:33:01 -07001032void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1033 RTC_DCHECK(stats_collector_);
1034 stats_collector_->GetStatsReport(callback);
1035}
1036
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1038 return signaling_state_;
1039}
1040
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041PeerConnectionInterface::IceConnectionState
1042PeerConnection::ice_connection_state() {
1043 return ice_connection_state_;
1044}
1045
1046PeerConnectionInterface::IceGatheringState
1047PeerConnection::ice_gathering_state() {
1048 return ice_gathering_state_;
1049}
1050
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001051rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052PeerConnection::CreateDataChannel(
1053 const std::string& label,
1054 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001055 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001056#ifdef HAVE_QUIC
1057 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1058 // TODO(zhihuang): Handle case when config is NULL.
1059 if (!config) {
1060 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1061 return nullptr;
1062 }
1063 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1064 if (!config->reliable || config->ordered) {
1065 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1066 "ordered delivery.";
1067 return nullptr;
1068 }
1069 return session_->quic_data_transport()->CreateDataChannel(label, config);
1070 }
1071#endif // HAVE_QUIC
1072
deadbeefab9b2d12015-10-14 11:33:11 -07001073 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001074
kwibergd1fe2812016-04-27 06:47:29 -07001075 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001076 if (config) {
1077 internal_config.reset(new InternalDataChannelInit(*config));
1078 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001079 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001080 InternalCreateDataChannel(label, internal_config.get()));
1081 if (!channel.get()) {
1082 return nullptr;
1083 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001084
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001085 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1086 // the first SCTP DataChannel.
1087 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1088 observer_->OnRenegotiationNeeded();
1089 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001090
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 return DataChannelProxy::Create(signaling_thread(), channel.get());
1092}
1093
1094void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1095 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001096 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001097 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1099 return;
1100 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001101 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001102
1103 bool value;
1104 size_t mandatory_constraints = 0;
1105
1106 if (FindConstraint(constraints,
1107 MediaConstraintsInterface::kOfferToReceiveAudio,
1108 &value,
1109 &mandatory_constraints)) {
1110 options.offer_to_receive_audio =
1111 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1112 }
1113
1114 if (FindConstraint(constraints,
1115 MediaConstraintsInterface::kOfferToReceiveVideo,
1116 &value,
1117 &mandatory_constraints)) {
1118 options.offer_to_receive_video =
1119 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1120 }
1121
1122 if (FindConstraint(constraints,
1123 MediaConstraintsInterface::kVoiceActivityDetection,
1124 &value,
1125 &mandatory_constraints)) {
1126 options.voice_activity_detection = value;
1127 }
1128
1129 if (FindConstraint(constraints,
1130 MediaConstraintsInterface::kIceRestart,
1131 &value,
1132 &mandatory_constraints)) {
1133 options.ice_restart = value;
1134 }
1135
1136 if (FindConstraint(constraints,
1137 MediaConstraintsInterface::kUseRtpMux,
1138 &value,
1139 &mandatory_constraints)) {
1140 options.use_rtp_mux = value;
1141 }
1142
1143 CreateOffer(observer, options);
1144}
1145
1146void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1147 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001148 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001149 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001150 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1151 return;
1152 }
deadbeefab9b2d12015-10-14 11:33:11 -07001153
1154 cricket::MediaSessionOptions session_options;
1155 if (!GetOptionsForOffer(options, &session_options)) {
1156 std::string error = "CreateOffer called with invalid options.";
1157 LOG(LS_ERROR) << error;
1158 PostCreateSessionDescriptionFailure(observer, error);
1159 return;
1160 }
1161
1162 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163}
1164
1165void PeerConnection::CreateAnswer(
1166 CreateSessionDescriptionObserver* observer,
1167 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001168 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001169 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1171 return;
1172 }
deadbeefab9b2d12015-10-14 11:33:11 -07001173
1174 cricket::MediaSessionOptions session_options;
1175 if (!GetOptionsForAnswer(constraints, &session_options)) {
1176 std::string error = "CreateAnswer called with invalid constraints.";
1177 LOG(LS_ERROR) << error;
1178 PostCreateSessionDescriptionFailure(observer, error);
1179 return;
1180 }
1181
htaa2a49d92016-03-04 02:51:39 -08001182 session_->CreateAnswer(observer, session_options);
1183}
1184
1185void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1186 const RTCOfferAnswerOptions& options) {
1187 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001188 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -08001189 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1190 return;
1191 }
1192
1193 cricket::MediaSessionOptions session_options;
1194 if (!GetOptionsForAnswer(options, &session_options)) {
1195 std::string error = "CreateAnswer called with invalid options.";
1196 LOG(LS_ERROR) << error;
1197 PostCreateSessionDescriptionFailure(observer, error);
1198 return;
1199 }
1200
1201 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202}
1203
1204void PeerConnection::SetLocalDescription(
1205 SetSessionDescriptionObserver* observer,
1206 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001207 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001208 if (IsClosed()) {
1209 return;
1210 }
nisse7ce109a2017-01-31 00:57:56 -08001211 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1213 return;
1214 }
1215 if (!desc) {
1216 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1217 return;
1218 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001219 // Update stats here so that we have the most recent stats for tracks and
1220 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001221 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222 std::string error;
1223 if (!session_->SetLocalDescription(desc, &error)) {
1224 PostSetSessionDescriptionFailure(observer, error);
1225 return;
1226 }
deadbeefab9b2d12015-10-14 11:33:11 -07001227
1228 // If setting the description decided our SSL role, allocate any necessary
1229 // SCTP sids.
1230 rtc::SSLRole role;
1231 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001232 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001233 AllocateSctpSids(role);
1234 }
1235
1236 // Update state and SSRC of local MediaStreams and DataChannels based on the
1237 // local session description.
1238 const cricket::ContentInfo* audio_content =
1239 GetFirstAudioContent(desc->description());
1240 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001241 if (audio_content->rejected) {
1242 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1243 } else {
1244 const cricket::AudioContentDescription* audio_desc =
1245 static_cast<const cricket::AudioContentDescription*>(
1246 audio_content->description);
1247 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1248 }
deadbeefab9b2d12015-10-14 11:33:11 -07001249 }
1250
1251 const cricket::ContentInfo* video_content =
1252 GetFirstVideoContent(desc->description());
1253 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001254 if (video_content->rejected) {
1255 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1256 } else {
1257 const cricket::VideoContentDescription* video_desc =
1258 static_cast<const cricket::VideoContentDescription*>(
1259 video_content->description);
1260 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1261 }
deadbeefab9b2d12015-10-14 11:33:11 -07001262 }
1263
1264 const cricket::ContentInfo* data_content =
1265 GetFirstDataContent(desc->description());
1266 if (data_content) {
1267 const cricket::DataContentDescription* data_desc =
1268 static_cast<const cricket::DataContentDescription*>(
1269 data_content->description);
1270 if (rtc::starts_with(data_desc->protocol().data(),
1271 cricket::kMediaProtocolRtpPrefix)) {
1272 UpdateLocalRtpDataChannels(data_desc->streams());
1273 }
1274 }
1275
1276 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001277 signaling_thread()->Post(RTC_FROM_HERE, this,
1278 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001279
deadbeefcbecd352015-09-23 11:50:27 -07001280 // MaybeStartGathering needs to be called after posting
1281 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1282 // before signaling that SetLocalDescription completed.
1283 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284}
1285
1286void PeerConnection::SetRemoteDescription(
1287 SetSessionDescriptionObserver* observer,
1288 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001289 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001290 if (IsClosed()) {
1291 return;
1292 }
nisse7ce109a2017-01-31 00:57:56 -08001293 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001294 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1295 return;
1296 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 if (!desc) {
1298 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1299 return;
1300 }
1301 // Update stats here so that we have the most recent stats for tracks and
1302 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001303 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304 std::string error;
1305 if (!session_->SetRemoteDescription(desc, &error)) {
1306 PostSetSessionDescriptionFailure(observer, error);
1307 return;
1308 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309
deadbeefab9b2d12015-10-14 11:33:11 -07001310 // If setting the description decided our SSL role, allocate any necessary
1311 // SCTP sids.
1312 rtc::SSLRole role;
1313 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001314 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001315 AllocateSctpSids(role);
1316 }
1317
1318 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001319 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1320 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1321 const cricket::AudioContentDescription* audio_desc =
1322 GetFirstAudioContentDescription(remote_desc);
1323 const cricket::VideoContentDescription* video_desc =
1324 GetFirstVideoContentDescription(remote_desc);
1325 const cricket::DataContentDescription* data_desc =
1326 GetFirstDataContentDescription(remote_desc);
1327
1328 // Check if the descriptions include streams, just in case the peer supports
1329 // MSID, but doesn't indicate so with "a=msid-semantic".
1330 if (remote_desc->msid_supported() ||
1331 (audio_desc && !audio_desc->streams().empty()) ||
1332 (video_desc && !video_desc->streams().empty())) {
1333 remote_peer_supports_msid_ = true;
1334 }
deadbeefab9b2d12015-10-14 11:33:11 -07001335
1336 // We wait to signal new streams until we finish processing the description,
1337 // since only at that point will new streams have all their tracks.
1338 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1339
1340 // Find all audio rtp streams and create corresponding remote AudioTracks
1341 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001342 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001343 if (audio_content->rejected) {
1344 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1345 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001346 bool default_audio_track_needed =
1347 !remote_peer_supports_msid_ &&
1348 MediaContentDirectionHasSend(audio_desc->direction());
1349 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1350 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001351 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001352 }
deadbeefab9b2d12015-10-14 11:33:11 -07001353 }
1354
1355 // Find all video rtp streams and create corresponding remote VideoTracks
1356 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001357 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001358 if (video_content->rejected) {
1359 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1360 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001361 bool default_video_track_needed =
1362 !remote_peer_supports_msid_ &&
1363 MediaContentDirectionHasSend(video_desc->direction());
1364 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1365 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001366 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001367 }
deadbeefab9b2d12015-10-14 11:33:11 -07001368 }
1369
1370 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001371 if (data_desc) {
1372 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001373 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001374 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001375 }
1376 }
1377
1378 // Iterate new_streams and notify the observer about new MediaStreams.
1379 for (size_t i = 0; i < new_streams->count(); ++i) {
1380 MediaStreamInterface* new_stream = new_streams->at(i);
1381 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001382 // Call both the raw pointer and scoped_refptr versions of the method
1383 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001384 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001385 observer_->OnAddStream(
1386 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001387 }
1388
deadbeefbda7e0b2015-12-08 17:13:40 -08001389 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001390
1391 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001392 signaling_thread()->Post(RTC_FROM_HERE, this,
1393 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001394}
1395
deadbeef46c73892016-11-16 19:42:04 -08001396PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1397 return configuration_;
1398}
1399
deadbeef293e9262017-01-11 12:28:30 -08001400bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1401 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001402 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001403
1404 if (session_->local_description() &&
1405 configuration.ice_candidate_pool_size !=
1406 configuration_.ice_candidate_pool_size) {
1407 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1408 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001409 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001410 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001411
deadbeef293e9262017-01-11 12:28:30 -08001412 // The simplest (and most future-compatible) way to tell if the config was
1413 // modified in an invalid way is to copy each property we do support
1414 // modifying, then use operator==. There are far more properties we don't
1415 // support modifying than those we do, and more could be added.
1416 RTCConfiguration modified_config = configuration_;
1417 modified_config.servers = configuration.servers;
1418 modified_config.type = configuration.type;
1419 modified_config.ice_candidate_pool_size =
1420 configuration.ice_candidate_pool_size;
1421 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001422 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001423 if (configuration != modified_config) {
1424 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1425 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1426 }
1427
1428 // Note that this isn't possible through chromium, since it's an unsigned
1429 // short in WebIDL.
1430 if (configuration.ice_candidate_pool_size < 0 ||
1431 configuration.ice_candidate_pool_size > UINT16_MAX) {
1432 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1433 }
1434
1435 // Parse ICE servers before hopping to network thread.
1436 cricket::ServerAddresses stun_servers;
1437 std::vector<cricket::RelayServerConfig> turn_servers;
1438 RTCErrorType parse_error =
1439 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1440 if (parse_error != RTCErrorType::NONE) {
1441 return SafeSetError(parse_error, error);
1442 }
1443
1444 // In theory this shouldn't fail.
1445 if (!network_thread()->Invoke<bool>(
1446 RTC_FROM_HERE,
1447 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1448 stun_servers, turn_servers, modified_config.type,
1449 modified_config.ice_candidate_pool_size,
1450 modified_config.prune_turn_ports))) {
1451 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1452 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1453 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001454
deadbeefd1a38b52016-12-10 13:15:33 -08001455 // As described in JSEP, calling setConfiguration with new ICE servers or
1456 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1457 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001458 if (modified_config.servers != configuration_.servers ||
1459 modified_config.type != configuration_.type ||
1460 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001461 session_->SetNeedsIceRestartFlag();
1462 }
skvladd1f5fda2017-02-03 16:54:05 -08001463
1464 if (modified_config.ice_check_min_interval !=
1465 configuration_.ice_check_min_interval) {
1466 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1467 }
1468
deadbeef293e9262017-01-11 12:28:30 -08001469 configuration_ = modified_config;
1470 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001471}
1472
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473bool PeerConnection::AddIceCandidate(
1474 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001475 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001476 if (IsClosed()) {
1477 return false;
1478 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479 return session_->ProcessIceMessage(ice_candidate);
1480}
1481
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001482bool PeerConnection::RemoveIceCandidates(
1483 const std::vector<cricket::Candidate>& candidates) {
1484 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1485 return session_->RemoveRemoteIceCandidates(candidates);
1486}
1487
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001488void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001489 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001490 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001491
1492 if (session_) {
1493 session_->set_metrics_observer(uma_observer_);
1494 }
1495
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001496 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001497 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001498 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001499 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001500 uma_observer_->IncrementEnumCounter(
1501 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1502 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001503 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001504 uma_observer_->IncrementEnumCounter(
1505 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1506 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001507 }
1508 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001509}
1510
ivoc14d5dbe2016-07-04 07:06:55 -07001511bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1512 int64_t max_size_bytes) {
1513 return factory_->worker_thread()->Invoke<bool>(
1514 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1515 max_size_bytes));
1516}
1517
1518void PeerConnection::StopRtcEventLog() {
1519 factory_->worker_thread()->Invoke<void>(
1520 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1521}
1522
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001523const SessionDescriptionInterface* PeerConnection::local_description() const {
1524 return session_->local_description();
1525}
1526
1527const SessionDescriptionInterface* PeerConnection::remote_description() const {
1528 return session_->remote_description();
1529}
1530
deadbeeffe4a8a42016-12-20 17:56:17 -08001531const SessionDescriptionInterface* PeerConnection::current_local_description()
1532 const {
1533 return session_->current_local_description();
1534}
1535
1536const SessionDescriptionInterface* PeerConnection::current_remote_description()
1537 const {
1538 return session_->current_remote_description();
1539}
1540
1541const SessionDescriptionInterface* PeerConnection::pending_local_description()
1542 const {
1543 return session_->pending_local_description();
1544}
1545
1546const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1547 const {
1548 return session_->pending_remote_description();
1549}
1550
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001552 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001553 // Update stats here so that we have the most recent stats for tracks and
1554 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001555 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556
deadbeefd59daf82015-10-14 15:02:44 -07001557 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558}
1559
deadbeefd59daf82015-10-14 15:02:44 -07001560void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1561 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001563 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001564 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001565 break;
deadbeefd59daf82015-10-14 15:02:44 -07001566 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1568 break;
deadbeefd59daf82015-10-14 15:02:44 -07001569 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1571 break;
deadbeefd59daf82015-10-14 15:02:44 -07001572 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1574 break;
deadbeefd59daf82015-10-14 15:02:44 -07001575 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1577 break;
deadbeefd59daf82015-10-14 15:02:44 -07001578 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 ChangeSignalingState(PeerConnectionInterface::kStable);
1580 break;
deadbeefd59daf82015-10-14 15:02:44 -07001581 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582 ChangeSignalingState(PeerConnectionInterface::kClosed);
1583 break;
1584 default:
1585 break;
1586 }
1587}
1588
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001589void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001590 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1592 SetSessionDescriptionMsg* param =
1593 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1594 param->observer->OnSuccess();
1595 delete param;
1596 break;
1597 }
1598 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1599 SetSessionDescriptionMsg* param =
1600 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1601 param->observer->OnFailure(param->error);
1602 delete param;
1603 break;
1604 }
deadbeefab9b2d12015-10-14 11:33:11 -07001605 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1606 CreateSessionDescriptionMsg* param =
1607 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1608 param->observer->OnFailure(param->error);
1609 delete param;
1610 break;
1611 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612 case MSG_GETSTATS: {
1613 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001614 StatsReports reports;
1615 stats_->GetStats(param->track, &reports);
1616 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 delete param;
1618 break;
1619 }
deadbeefbd292462015-12-14 18:15:29 -08001620 case MSG_FREE_DATACHANNELS: {
1621 sctp_data_channels_to_free_.clear();
1622 break;
1623 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001624 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001625 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626 break;
1627 }
1628}
1629
deadbeefab9b2d12015-10-14 11:33:11 -07001630void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001631 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001632 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001633 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1634 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001635 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001636 session_->voice_channel()));
1637
1638 receivers_.push_back(receiver);
1639 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1640 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1641 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001642}
1643
deadbeefab9b2d12015-10-14 11:33:11 -07001644void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001645 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001646 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001647 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1648 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001649 signaling_thread(),
1650 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001651 ssrc, session_->video_channel()));
1652 receivers_.push_back(receiver);
1653 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1654 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1655 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001656}
1657
deadbeef70ab1a12015-09-28 16:53:55 -07001658// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1659// description.
perkjd61bf802016-03-24 03:16:19 -07001660void PeerConnection::DestroyReceiver(const std::string& track_id) {
1661 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001662 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001663 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001664 << " doesn't exist.";
1665 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001666 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001667 receivers_.erase(it);
1668 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001669}
1670
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001671void PeerConnection::OnIceConnectionChange(
1672 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001673 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001674 // After transitioning to "closed", ignore any additional states from
1675 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001676 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001677 return;
1678 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001679 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001680 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681}
1682
1683void PeerConnection::OnIceGatheringChange(
1684 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001685 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686 if (IsClosed()) {
1687 return;
1688 }
1689 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001690 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001691}
1692
1693void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001694 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001695 if (IsClosed()) {
1696 return;
1697 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001698 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699}
1700
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001701void PeerConnection::OnIceCandidatesRemoved(
1702 const std::vector<cricket::Candidate>& candidates) {
1703 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001704 if (IsClosed()) {
1705 return;
1706 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001707 observer_->OnIceCandidatesRemoved(candidates);
1708}
1709
Peter Thatcher54360512015-07-08 11:08:35 -07001710void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001711 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001712 if (IsClosed()) {
1713 return;
1714 }
Peter Thatcher54360512015-07-08 11:08:35 -07001715 observer_->OnIceConnectionReceivingChange(receiving);
1716}
1717
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718void PeerConnection::ChangeSignalingState(
1719 PeerConnectionInterface::SignalingState signaling_state) {
1720 signaling_state_ = signaling_state;
1721 if (signaling_state == kClosed) {
1722 ice_connection_state_ = kIceConnectionClosed;
1723 observer_->OnIceConnectionChange(ice_connection_state_);
1724 if (ice_gathering_state_ != kIceGatheringComplete) {
1725 ice_gathering_state_ = kIceGatheringComplete;
1726 observer_->OnIceGatheringChange(ice_gathering_state_);
1727 }
1728 }
1729 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001730}
1731
deadbeefeb459812015-12-15 19:24:43 -08001732void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1733 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001734 if (IsClosed()) {
1735 return;
1736 }
deadbeefeb459812015-12-15 19:24:43 -08001737 auto sender = FindSenderForTrack(track);
1738 if (sender != senders_.end()) {
1739 // We already have a sender for this track, so just change the stream_id
1740 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001741 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001742 return;
1743 }
1744
1745 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001746 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1747 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001748 signaling_thread(),
1749 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1750 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001751 senders_.push_back(new_sender);
1752 // If the sender has already been configured in SDP, we call SetSsrc,
1753 // which will connect the sender to the underlying transport. This can
1754 // occur if a local session description that contains the ID of the sender
1755 // is set before AddStream is called. It can also occur if the local
1756 // session description is not changed and RemoveStream is called, and
1757 // later AddStream is called again with the same stream.
1758 const TrackInfo* track_info =
1759 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1760 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001761 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001762 }
1763}
1764
1765// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1766// indefinitely, when we have unified plan SDP.
1767void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1768 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001769 if (IsClosed()) {
1770 return;
1771 }
deadbeefeb459812015-12-15 19:24:43 -08001772 auto sender = FindSenderForTrack(track);
1773 if (sender == senders_.end()) {
1774 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1775 << " doesn't exist.";
1776 return;
1777 }
deadbeefa601f5c2016-06-06 14:27:39 -07001778 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001779 senders_.erase(sender);
1780}
1781
1782void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1783 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001784 if (IsClosed()) {
1785 return;
1786 }
deadbeefeb459812015-12-15 19:24:43 -08001787 auto sender = FindSenderForTrack(track);
1788 if (sender != senders_.end()) {
1789 // We already have a sender for this track, so just change the stream_id
1790 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001791 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001792 return;
1793 }
1794
1795 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001796 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1797 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001798 signaling_thread(), new VideoRtpSender(track, stream->label(),
1799 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001800 senders_.push_back(new_sender);
1801 const TrackInfo* track_info =
1802 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1803 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001804 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001805 }
1806}
1807
1808void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1809 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001810 if (IsClosed()) {
1811 return;
1812 }
deadbeefeb459812015-12-15 19:24:43 -08001813 auto sender = FindSenderForTrack(track);
1814 if (sender == senders_.end()) {
1815 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1816 << " doesn't exist.";
1817 return;
1818 }
deadbeefa601f5c2016-06-06 14:27:39 -07001819 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001820 senders_.erase(sender);
1821}
1822
deadbeefab9b2d12015-10-14 11:33:11 -07001823void PeerConnection::PostSetSessionDescriptionFailure(
1824 SetSessionDescriptionObserver* observer,
1825 const std::string& error) {
1826 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1827 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001828 signaling_thread()->Post(RTC_FROM_HERE, this,
1829 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001830}
1831
1832void PeerConnection::PostCreateSessionDescriptionFailure(
1833 CreateSessionDescriptionObserver* observer,
1834 const std::string& error) {
1835 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1836 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001837 signaling_thread()->Post(RTC_FROM_HERE, this,
1838 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001839}
1840
1841bool PeerConnection::GetOptionsForOffer(
1842 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1843 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001844 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1845 // ContentInfos.
1846 if (session_->local_description()) {
1847 for (const cricket::ContentInfo& content :
1848 session_->local_description()->description()->contents()) {
1849 session_options->transport_options[content.name] =
1850 cricket::TransportOptions();
1851 }
1852 }
deadbeef46c73892016-11-16 19:42:04 -08001853 session_options->enable_ice_renomination =
1854 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001855
htaaac2dea2016-03-10 13:35:55 -08001856 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001857 return false;
1858 }
1859
deadbeeffac06552015-11-25 11:26:01 -08001860 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001861 // Offer to receive audio/video if the constraint is not set and there are
1862 // send streams, or we're currently receiving.
1863 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1864 session_options->recv_audio =
1865 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1866 !remote_audio_tracks_.empty();
1867 }
1868 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1869 session_options->recv_video =
1870 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1871 !remote_video_tracks_.empty();
1872 }
deadbeefc80741f2015-10-22 13:14:45 -07001873
zhihuang9763d562016-08-05 11:14:50 -07001874 // Intentionally unset the data channel type for RTP data channel with the
1875 // second condition. Otherwise the RTP data channels would be successfully
1876 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1877 // when building with chromium. We want to leave RTP data channels broken, so
1878 // people won't try to use them.
1879 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1880 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001881 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001882
zhihuangaf388472016-11-02 16:49:48 -07001883 session_options->bundle_enabled =
1884 session_options->bundle_enabled &&
1885 (session_options->has_audio() || session_options->has_video() ||
1886 session_options->has_data());
1887
zhihuang8f65cdf2016-05-06 18:40:30 -07001888 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001889 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001890 return true;
1891}
1892
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001893void PeerConnection::InitializeOptionsForAnswer(
1894 cricket::MediaSessionOptions* session_options) {
1895 session_options->recv_audio = false;
1896 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001897 session_options->enable_ice_renomination =
1898 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001899}
1900
htaa2a49d92016-03-04 02:51:39 -08001901void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001902 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001903 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1904 // ContentInfos.
1905 if (session_->remote_description()) {
1906 // Initialize the transport_options map.
1907 for (const cricket::ContentInfo& content :
1908 session_->remote_description()->description()->contents()) {
1909 session_options->transport_options[content.name] =
1910 cricket::TransportOptions();
1911 }
1912 }
deadbeeffac06552015-11-25 11:26:01 -08001913 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001914 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1915 // are not signaled in the SDP so does not go through that path and must be
1916 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001917 // Intentionally unset the data channel type for RTP data channel. Otherwise
1918 // the RTP data channels would be successfully negotiated by default and the
1919 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1920 // We want to leave RTP data channels broken, so people won't try to use them.
1921 if (session_->data_channel_type() != cricket::DCT_RTP) {
1922 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001923 }
zhihuangaf388472016-11-02 16:49:48 -07001924 session_options->bundle_enabled =
1925 session_options->bundle_enabled &&
1926 (session_options->has_audio() || session_options->has_video() ||
1927 session_options->has_data());
1928
jbauchcb560652016-08-04 05:20:32 -07001929 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001930}
1931
1932bool PeerConnection::GetOptionsForAnswer(
1933 const MediaConstraintsInterface* constraints,
1934 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001935 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001936 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1937 return false;
1938 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001939 session_options->rtcp_cname = rtcp_cname_;
1940
htaa2a49d92016-03-04 02:51:39 -08001941 FinishOptionsForAnswer(session_options);
1942 return true;
1943}
1944
1945bool PeerConnection::GetOptionsForAnswer(
1946 const RTCOfferAnswerOptions& options,
1947 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001948 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001949 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001950 return false;
1951 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001952 session_options->rtcp_cname = rtcp_cname_;
1953
htaa2a49d92016-03-04 02:51:39 -08001954 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001955 return true;
1956}
1957
deadbeeffaac4972015-11-12 15:33:07 -08001958void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1959 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001960 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1961 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001962}
1963
deadbeefab9b2d12015-10-14 11:33:11 -07001964void PeerConnection::UpdateRemoteStreamsList(
1965 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001966 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001967 cricket::MediaType media_type,
1968 StreamCollection* new_streams) {
1969 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1970
1971 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001972 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001973 auto track_it = current_tracks->begin();
1974 while (track_it != current_tracks->end()) {
1975 const TrackInfo& info = *track_it;
1976 const cricket::StreamParams* params =
1977 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001978 bool track_exists = params && params->id == info.track_id;
1979 // If this is a default track, and we still need it, don't remove it.
1980 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1981 track_exists) {
1982 ++track_it;
1983 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001984 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1985 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001986 }
1987 }
1988
1989 // Find new and active tracks.
1990 for (const cricket::StreamParams& params : streams) {
1991 // The sync_label is the MediaStream label and the |stream.id| is the
1992 // track id.
1993 const std::string& stream_label = params.sync_label;
1994 const std::string& track_id = params.id;
1995 uint32_t ssrc = params.first_ssrc();
1996
1997 rtc::scoped_refptr<MediaStreamInterface> stream =
1998 remote_streams_->find(stream_label);
1999 if (!stream) {
2000 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002001 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2002 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002003 remote_streams_->AddStream(stream);
2004 new_streams->AddStream(stream);
2005 }
2006
2007 const TrackInfo* track_info =
2008 FindTrackInfo(*current_tracks, stream_label, track_id);
2009 if (!track_info) {
2010 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2011 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2012 }
2013 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002014
2015 // Add default track if necessary.
2016 if (default_track_needed) {
2017 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2018 remote_streams_->find(kDefaultStreamLabel);
2019 if (!default_stream) {
2020 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002021 default_stream = MediaStreamProxy::Create(
2022 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002023 remote_streams_->AddStream(default_stream);
2024 new_streams->AddStream(default_stream);
2025 }
2026 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2027 ? kDefaultAudioTrackLabel
2028 : kDefaultVideoTrackLabel;
2029 const TrackInfo* default_track_info =
2030 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2031 if (!default_track_info) {
2032 current_tracks->push_back(
2033 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2034 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2035 }
2036 }
deadbeefab9b2d12015-10-14 11:33:11 -07002037}
2038
2039void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2040 const std::string& track_id,
2041 uint32_t ssrc,
2042 cricket::MediaType media_type) {
2043 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2044
2045 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002046 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002047 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002048 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002049 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002050 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002051 }
2052}
2053
2054void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2055 const std::string& track_id,
2056 cricket::MediaType media_type) {
2057 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2058
2059 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002060 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2061 // will be notified which will end the AudioRtpReceiver::track().
2062 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002063 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2064 stream->FindAudioTrack(track_id);
2065 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002066 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002067 }
2068 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002069 // Stopping or destroying a VideoRtpReceiver will end the
2070 // VideoRtpReceiver::track().
2071 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002072 rtc::scoped_refptr<VideoTrackInterface> video_track =
2073 stream->FindVideoTrack(track_id);
2074 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002075 // There's no guarantee the track is still available, e.g. the track may
2076 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002077 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002078 }
2079 } else {
nisseede5da42017-01-12 05:15:36 -08002080 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002081 }
2082}
2083
2084void PeerConnection::UpdateEndedRemoteMediaStreams() {
2085 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2086 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2087 MediaStreamInterface* stream = remote_streams_->at(i);
2088 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2089 streams_to_remove.push_back(stream);
2090 }
2091 }
2092
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002093 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002094 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002095 // Call both the raw pointer and scoped_refptr versions of the method
2096 // for compatibility.
2097 observer_->OnRemoveStream(stream.get());
2098 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002099 }
2100}
2101
deadbeefab9b2d12015-10-14 11:33:11 -07002102void PeerConnection::UpdateLocalTracks(
2103 const std::vector<cricket::StreamParams>& streams,
2104 cricket::MediaType media_type) {
2105 TrackInfos* current_tracks = GetLocalTracks(media_type);
2106
2107 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2108 // don't match the new StreamParam.
2109 TrackInfos::iterator track_it = current_tracks->begin();
2110 while (track_it != current_tracks->end()) {
2111 const TrackInfo& info = *track_it;
2112 const cricket::StreamParams* params =
2113 cricket::GetStreamBySsrc(streams, info.ssrc);
2114 if (!params || params->id != info.track_id ||
2115 params->sync_label != info.stream_label) {
2116 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2117 media_type);
2118 track_it = current_tracks->erase(track_it);
2119 } else {
2120 ++track_it;
2121 }
2122 }
2123
2124 // Find new and active tracks.
2125 for (const cricket::StreamParams& params : streams) {
2126 // The sync_label is the MediaStream label and the |stream.id| is the
2127 // track id.
2128 const std::string& stream_label = params.sync_label;
2129 const std::string& track_id = params.id;
2130 uint32_t ssrc = params.first_ssrc();
2131 const TrackInfo* track_info =
2132 FindTrackInfo(*current_tracks, stream_label, track_id);
2133 if (!track_info) {
2134 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2135 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2136 }
2137 }
2138}
2139
2140void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2141 const std::string& track_id,
2142 uint32_t ssrc,
2143 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002144 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002145 if (!sender) {
2146 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2147 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002148 return;
2149 }
2150
deadbeeffac06552015-11-25 11:26:01 -08002151 if (sender->media_type() != media_type) {
2152 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2153 << " description with an unexpected media type.";
2154 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002155 }
deadbeeffac06552015-11-25 11:26:01 -08002156
2157 sender->set_stream_id(stream_label);
2158 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002159}
2160
2161void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2162 const std::string& track_id,
2163 uint32_t ssrc,
2164 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002165 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002166 if (!sender) {
2167 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002168 // SessionDescriptions has been renegotiated.
2169 return;
2170 }
deadbeeffac06552015-11-25 11:26:01 -08002171
2172 // A sender has been removed from the SessionDescription but it's still
2173 // associated with the PeerConnection. This only occurs if the SDP doesn't
2174 // match with the calls to CreateSender, AddStream and RemoveStream.
2175 if (sender->media_type() != media_type) {
2176 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2177 << " description with an unexpected media type.";
2178 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002179 }
deadbeeffac06552015-11-25 11:26:01 -08002180
2181 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002182}
2183
2184void PeerConnection::UpdateLocalRtpDataChannels(
2185 const cricket::StreamParamsVec& streams) {
2186 std::vector<std::string> existing_channels;
2187
2188 // Find new and active data channels.
2189 for (const cricket::StreamParams& params : streams) {
2190 // |it->sync_label| is actually the data channel label. The reason is that
2191 // we use the same naming of data channels as we do for
2192 // MediaStreams and Tracks.
2193 // For MediaStreams, the sync_label is the MediaStream label and the
2194 // track label is the same as |streamid|.
2195 const std::string& channel_label = params.sync_label;
2196 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002197 if (data_channel_it == rtp_data_channels_.end()) {
2198 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002199 continue;
2200 }
2201 // Set the SSRC the data channel should use for sending.
2202 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2203 existing_channels.push_back(data_channel_it->first);
2204 }
2205
2206 UpdateClosingRtpDataChannels(existing_channels, true);
2207}
2208
2209void PeerConnection::UpdateRemoteRtpDataChannels(
2210 const cricket::StreamParamsVec& streams) {
2211 std::vector<std::string> existing_channels;
2212
2213 // Find new and active data channels.
2214 for (const cricket::StreamParams& params : streams) {
2215 // The data channel label is either the mslabel or the SSRC if the mslabel
2216 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2217 std::string label = params.sync_label.empty()
2218 ? rtc::ToString(params.first_ssrc())
2219 : params.sync_label;
2220 auto data_channel_it = rtp_data_channels_.find(label);
2221 if (data_channel_it == rtp_data_channels_.end()) {
2222 // This is a new data channel.
2223 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2224 } else {
2225 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2226 }
2227 existing_channels.push_back(label);
2228 }
2229
2230 UpdateClosingRtpDataChannels(existing_channels, false);
2231}
2232
2233void PeerConnection::UpdateClosingRtpDataChannels(
2234 const std::vector<std::string>& active_channels,
2235 bool is_local_update) {
2236 auto it = rtp_data_channels_.begin();
2237 while (it != rtp_data_channels_.end()) {
2238 DataChannel* data_channel = it->second;
2239 if (std::find(active_channels.begin(), active_channels.end(),
2240 data_channel->label()) != active_channels.end()) {
2241 ++it;
2242 continue;
2243 }
2244
2245 if (is_local_update) {
2246 data_channel->SetSendSsrc(0);
2247 } else {
2248 data_channel->RemotePeerRequestClose();
2249 }
2250
2251 if (data_channel->state() == DataChannel::kClosed) {
2252 rtp_data_channels_.erase(it);
2253 it = rtp_data_channels_.begin();
2254 } else {
2255 ++it;
2256 }
2257 }
2258}
2259
2260void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2261 uint32_t remote_ssrc) {
2262 rtc::scoped_refptr<DataChannel> channel(
2263 InternalCreateDataChannel(label, nullptr));
2264 if (!channel.get()) {
2265 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2266 << "CreateDataChannel failed.";
2267 return;
2268 }
2269 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002270 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2271 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002272 // Call both the raw pointer and scoped_refptr versions of the method
2273 // for compatibility.
2274 observer_->OnDataChannel(proxy_channel.get());
2275 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002276}
2277
2278rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2279 const std::string& label,
2280 const InternalDataChannelInit* config) {
2281 if (IsClosed()) {
2282 return nullptr;
2283 }
2284 if (session_->data_channel_type() == cricket::DCT_NONE) {
2285 LOG(LS_ERROR)
2286 << "InternalCreateDataChannel: Data is not supported in this call.";
2287 return nullptr;
2288 }
2289 InternalDataChannelInit new_config =
2290 config ? (*config) : InternalDataChannelInit();
2291 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2292 if (new_config.id < 0) {
2293 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002294 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002295 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2296 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2297 return nullptr;
2298 }
2299 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2300 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2301 << "because the id is already in use or out of range.";
2302 return nullptr;
2303 }
2304 }
2305
2306 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2307 session_.get(), session_->data_channel_type(), label, new_config));
2308 if (!channel) {
2309 sid_allocator_.ReleaseSid(new_config.id);
2310 return nullptr;
2311 }
2312
2313 if (channel->data_channel_type() == cricket::DCT_RTP) {
2314 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2315 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2316 << " already exists.";
2317 return nullptr;
2318 }
2319 rtp_data_channels_[channel->label()] = channel;
2320 } else {
2321 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2322 sctp_data_channels_.push_back(channel);
2323 channel->SignalClosed.connect(this,
2324 &PeerConnection::OnSctpDataChannelClosed);
2325 }
2326
hbos82ebe022016-11-14 01:41:09 -08002327 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002328 return channel;
2329}
2330
2331bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002332#ifdef HAVE_QUIC
2333 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2334 (session_->quic_data_transport() &&
2335 session_->quic_data_transport()->HasDataChannels());
2336#else
deadbeefab9b2d12015-10-14 11:33:11 -07002337 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002338#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002339}
2340
2341void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2342 for (const auto& channel : sctp_data_channels_) {
2343 if (channel->id() < 0) {
2344 int sid;
2345 if (!sid_allocator_.AllocateSid(role, &sid)) {
2346 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2347 continue;
2348 }
2349 channel->SetSctpSid(sid);
2350 }
2351 }
2352}
2353
2354void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002355 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002356 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2357 ++it) {
2358 if (it->get() == channel) {
2359 if (channel->id() >= 0) {
2360 sid_allocator_.ReleaseSid(channel->id());
2361 }
deadbeefbd292462015-12-14 18:15:29 -08002362 // Since this method is triggered by a signal from the DataChannel,
2363 // we can't free it directly here; we need to free it asynchronously.
2364 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002365 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002366 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2367 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002368 return;
2369 }
2370 }
2371}
2372
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002373void PeerConnection::OnVoiceChannelCreated() {
2374 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2375 session_->voice_channel(), senders_, receivers_,
2376 cricket::MEDIA_TYPE_AUDIO);
2377}
2378
deadbeefab9b2d12015-10-14 11:33:11 -07002379void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002380 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2381 cricket::VoiceChannel>(
2382 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2383}
2384
2385void PeerConnection::OnVideoChannelCreated() {
2386 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2387 session_->video_channel(), senders_, receivers_,
2388 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002389}
2390
2391void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002392 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2393 cricket::VideoChannel>(
2394 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002395}
2396
2397void PeerConnection::OnDataChannelCreated() {
2398 for (const auto& channel : sctp_data_channels_) {
2399 channel->OnTransportChannelCreated();
2400 }
2401}
2402
2403void PeerConnection::OnDataChannelDestroyed() {
2404 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2405 // DataChannel may callback to us and try to modify the list.
2406 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2407 temp_rtp_dcs.swap(rtp_data_channels_);
2408 for (const auto& kv : temp_rtp_dcs) {
2409 kv.second->OnTransportChannelDestroyed();
2410 }
2411
2412 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2413 temp_sctp_dcs.swap(sctp_data_channels_);
2414 for (const auto& channel : temp_sctp_dcs) {
2415 channel->OnTransportChannelDestroyed();
2416 }
2417}
2418
2419void PeerConnection::OnDataChannelOpenMessage(
2420 const std::string& label,
2421 const InternalDataChannelInit& config) {
2422 rtc::scoped_refptr<DataChannel> channel(
2423 InternalCreateDataChannel(label, &config));
2424 if (!channel.get()) {
2425 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2426 return;
2427 }
2428
deadbeefa601f5c2016-06-06 14:27:39 -07002429 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2430 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002431 // Call both the raw pointer and scoped_refptr versions of the method
2432 // for compatibility.
2433 observer_->OnDataChannel(proxy_channel.get());
2434 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002435}
2436
deadbeefa601f5c2016-06-06 14:27:39 -07002437RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2438 auto it = std::find_if(
2439 senders_.begin(), senders_.end(),
2440 [id](const rtc::scoped_refptr<
2441 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2442 return sender->id() == id;
2443 });
2444 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002445}
2446
deadbeefa601f5c2016-06-06 14:27:39 -07002447std::vector<
2448 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002449PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2450 return std::find_if(
2451 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002452 [track](const rtc::scoped_refptr<
2453 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002454 return sender->track() == track;
2455 });
2456}
2457
deadbeefa601f5c2016-06-06 14:27:39 -07002458std::vector<rtc::scoped_refptr<
2459 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002460PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002461 return std::find_if(
2462 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002463 [track_id](const rtc::scoped_refptr<
2464 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002465 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002466 });
2467}
2468
deadbeefab9b2d12015-10-14 11:33:11 -07002469PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2470 cricket::MediaType media_type) {
2471 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2472 media_type == cricket::MEDIA_TYPE_VIDEO);
2473 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2474 : &remote_video_tracks_;
2475}
2476
2477PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2478 cricket::MediaType media_type) {
2479 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2480 media_type == cricket::MEDIA_TYPE_VIDEO);
2481 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2482 : &local_video_tracks_;
2483}
2484
2485const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2486 const PeerConnection::TrackInfos& infos,
2487 const std::string& stream_label,
2488 const std::string track_id) const {
2489 for (const TrackInfo& track_info : infos) {
2490 if (track_info.stream_label == stream_label &&
2491 track_info.track_id == track_id) {
2492 return &track_info;
2493 }
2494 }
2495 return nullptr;
2496}
2497
2498DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2499 for (const auto& channel : sctp_data_channels_) {
2500 if (channel->id() == sid) {
2501 return channel;
2502 }
2503 }
2504 return nullptr;
2505}
2506
deadbeef91dd5672016-05-18 16:55:30 -07002507bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002508 const RTCConfiguration& configuration) {
2509 cricket::ServerAddresses stun_servers;
2510 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002511 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2512 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002513 return false;
2514 }
2515
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002516 port_allocator_->Initialize();
2517
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002518 // To handle both internal and externally created port allocator, we will
2519 // enable BUNDLE here.
2520 int portallocator_flags = port_allocator_->flags();
2521 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2522 cricket::PORTALLOCATOR_ENABLE_IPV6;
2523 // If the disable-IPv6 flag was specified, we'll not override it
2524 // by experiment.
2525 if (configuration.disable_ipv6) {
2526 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2527 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2528 "Disabled") {
2529 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2530 }
2531
2532 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2533 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2534 LOG(LS_INFO) << "TCP candidates are disabled.";
2535 }
2536
honghaiz60347052016-05-31 18:29:12 -07002537 if (configuration.candidate_network_policy ==
2538 kCandidateNetworkPolicyLowCost) {
2539 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2540 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2541 }
2542
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002543 port_allocator_->set_flags(portallocator_flags);
2544 // No step delay is used while allocating ports.
2545 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2546 port_allocator_->set_candidate_filter(
2547 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2548
2549 // Call this last since it may create pooled allocator sessions using the
2550 // properties set above.
2551 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002552 configuration.ice_candidate_pool_size,
2553 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002554 return true;
2555}
2556
deadbeef91dd5672016-05-18 16:55:30 -07002557bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002558 const cricket::ServerAddresses& stun_servers,
2559 const std::vector<cricket::RelayServerConfig>& turn_servers,
2560 IceTransportsType type,
2561 int candidate_pool_size,
2562 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002563 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002564 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002565 // Call this last since it may create pooled allocator sessions using the
2566 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002567 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002568 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002569}
2570
ivoc14d5dbe2016-07-04 07:06:55 -07002571bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2572 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002573 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002574}
2575
2576void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002577 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002578}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002579} // namespace webrtc