blob: a38c98601bb2f66904531d8d8daf079fd3cb4e6c [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;
508 };
509 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
510 "Did you add something to RTCConfiguration and forget to "
511 "update operator==?");
512 return type == o.type && servers == o.servers &&
513 bundle_policy == o.bundle_policy &&
514 rtcp_mux_policy == o.rtcp_mux_policy &&
515 tcp_candidate_policy == o.tcp_candidate_policy &&
516 candidate_network_policy == o.candidate_network_policy &&
517 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
518 audio_jitter_buffer_fast_accelerate ==
519 o.audio_jitter_buffer_fast_accelerate &&
520 ice_connection_receiving_timeout ==
521 o.ice_connection_receiving_timeout &&
522 ice_backup_candidate_pair_ping_interval ==
523 o.ice_backup_candidate_pair_ping_interval &&
524 continual_gathering_policy == o.continual_gathering_policy &&
525 certificates == o.certificates &&
526 prioritize_most_likely_ice_candidate_pairs ==
527 o.prioritize_most_likely_ice_candidate_pairs &&
528 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
529 enable_rtp_data_channel == o.enable_rtp_data_channel &&
530 enable_quic == o.enable_quic &&
531 screencast_min_bitrate == o.screencast_min_bitrate &&
532 combined_audio_video_bwe == o.combined_audio_video_bwe &&
533 enable_dtls_srtp == o.enable_dtls_srtp &&
534 ice_candidate_pool_size == o.ice_candidate_pool_size &&
535 prune_turn_ports == o.prune_turn_ports &&
536 presume_writable_when_fully_relayed ==
537 o.presume_writable_when_fully_relayed &&
538 enable_ice_renomination == o.enable_ice_renomination &&
539 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart;
540}
541
542bool PeerConnectionInterface::RTCConfiguration::operator!=(
543 const PeerConnectionInterface::RTCConfiguration& o) const {
544 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800545}
546
zhihuang8f65cdf2016-05-06 18:40:30 -0700547// Generate a RTCP CNAME when a PeerConnection is created.
548std::string GenerateRtcpCname() {
549 std::string cname;
550 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
551 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800552 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700553 }
554 return cname;
555}
556
htaa2a49d92016-03-04 02:51:39 -0800557bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700558 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800559 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700560 cricket::MediaSessionOptions* session_options) {
561 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
562 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
563 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
564 return false;
565 }
566
htaaac2dea2016-03-10 13:35:55 -0800567 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700568 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700569 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800570 } else {
571 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700572 }
htaaac2dea2016-03-10 13:35:55 -0800573 // For offers, we only offer video if we have it or it's forced by options.
574 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700575 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700576 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800577 } else if (is_offer) {
578 session_options->recv_video = false;
579 } else {
580 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700581 }
582
583 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700584 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800585 for (auto& kv : session_options->transport_options) {
586 kv.second.ice_restart = rtc_options.ice_restart;
587 }
deadbeefab9b2d12015-10-14 11:33:11 -0700588
589 return true;
590}
591
592bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
593 cricket::MediaSessionOptions* session_options) {
594 bool value = false;
595 size_t mandatory_constraints_satisfied = 0;
596
597 // kOfferToReceiveAudio defaults to true according to spec.
598 if (!FindConstraint(constraints,
599 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
600 &mandatory_constraints_satisfied) ||
601 value) {
602 session_options->recv_audio = true;
603 }
604
605 // kOfferToReceiveVideo defaults to false according to spec. But
606 // if it is an answer and video is offered, we should still accept video
607 // per default.
608 value = false;
609 if (!FindConstraint(constraints,
610 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
611 &mandatory_constraints_satisfied) ||
612 value) {
613 session_options->recv_video = true;
614 }
615
616 if (FindConstraint(constraints,
617 MediaConstraintsInterface::kVoiceActivityDetection, &value,
618 &mandatory_constraints_satisfied)) {
619 session_options->vad_enabled = value;
620 }
621
622 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
623 &mandatory_constraints_satisfied)) {
624 session_options->bundle_enabled = value;
625 } else {
626 // kUseRtpMux defaults to true according to spec.
627 session_options->bundle_enabled = true;
628 }
deadbeefab9b2d12015-10-14 11:33:11 -0700629
deadbeef0ed85b22016-02-23 17:24:52 -0800630 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700631 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
632 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700633 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800634 ice_restart = true;
635 }
636 for (auto& kv : session_options->transport_options) {
637 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700638 }
639
640 if (!constraints) {
641 return true;
642 }
643 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
644}
645
deadbeef293e9262017-01-11 12:28:30 -0800646RTCErrorType ParseIceServers(
647 const PeerConnectionInterface::IceServers& servers,
648 cricket::ServerAddresses* stun_servers,
649 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200650 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
651 if (!server.urls.empty()) {
652 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200653 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700654 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800655 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200656 }
deadbeef293e9262017-01-11 12:28:30 -0800657 RTCErrorType err =
658 ParseIceServerUrl(server, url, stun_servers, turn_servers);
659 if (err != RTCErrorType::NONE) {
660 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200661 }
662 }
663 } else if (!server.uri.empty()) {
664 // Fallback to old .uri if new .urls isn't present.
deadbeef293e9262017-01-11 12:28:30 -0800665 RTCErrorType err =
666 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
667 if (err != RTCErrorType::NONE) {
668 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200669 }
670 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700671 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800672 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 }
674 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800675 // Candidates must have unique priorities, so that connectivity checks
676 // are performed in a well-defined order.
677 int priority = static_cast<int>(turn_servers->size() - 1);
678 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
679 // First in the list gets highest priority.
680 turn_server.priority = priority--;
681 }
deadbeef293e9262017-01-11 12:28:30 -0800682 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683}
684
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685PeerConnection::PeerConnection(PeerConnectionFactory* factory)
686 : factory_(factory),
687 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000688 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700691 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800692 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700693 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700694 local_streams_(StreamCollection::Create()),
695 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696
697PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100698 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700699 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700700 // Need to detach RTP senders/receivers from WebRtcSession,
701 // since it's about to be destroyed.
702 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700703 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700704 }
705 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700706 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700707 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700708 // Destroy stats_ because it depends on session_.
709 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800710 if (stats_collector_) {
711 stats_collector_->WaitForPendingRequest();
712 stats_collector_ = nullptr;
713 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700714 // Now destroy session_ before destroying other members,
715 // because its destruction fires signals (such as VoiceChannelDestroyed)
716 // which will trigger some final actions in PeerConnection...
717 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700718 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700719 network_thread()->Invoke<void>(RTC_FROM_HERE,
720 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721}
722
723bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000724 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700725 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200726 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800727 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100728 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800729 if (!allocator) {
730 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
731 << "This shouldn't happen if using PeerConnectionFactory.";
732 return false;
733 }
deadbeef653b8e02015-11-11 12:55:10 -0800734 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800735 // TODO(deadbeef): Why do we do this?
736 LOG(LS_ERROR) << "PeerConnection initialized without a "
737 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800738 return false;
739 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000740 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800741 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800742
deadbeef91dd5672016-05-18 16:55:30 -0700743 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700744 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700745 if (!network_thread()->Invoke<bool>(
746 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
747 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000748 return false;
749 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750
skvlad11a9cbf2016-10-07 11:53:05 -0700751 media_controller_.reset(factory_->CreateMediaController(
752 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753
zhihuang29ff8442016-07-27 11:07:25 -0700754 session_.reset(new WebRtcSession(
755 media_controller_.get(), factory_->network_thread(),
756 factory_->worker_thread(), factory_->signaling_thread(),
757 port_allocator_.get(),
758 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700759 factory_->CreateTransportController(
760 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800761 configuration.redetermine_role_on_ice_restart)),
762#ifdef HAVE_SCTP
763 std::unique_ptr<cricket::SctpTransportInternalFactory>(
764 new cricket::SctpTransportFactory(factory_->network_thread()))
765#else
766 nullptr
767#endif
768 ));
zhihuang29ff8442016-07-27 11:07:25 -0700769
deadbeefab9b2d12015-10-14 11:33:11 -0700770 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700771 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000772
773 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200774 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800775 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000776 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700777 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779 // Register PeerConnection as receiver of local ice candidates.
780 // All the callbacks will be posted to the application from PeerConnection.
781 session_->RegisterIceObserver(this);
782 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700783 session_->SignalVoiceChannelCreated.connect(
784 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700785 session_->SignalVoiceChannelDestroyed.connect(
786 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700787 session_->SignalVideoChannelCreated.connect(
788 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700789 session_->SignalVideoChannelDestroyed.connect(
790 this, &PeerConnection::OnVideoChannelDestroyed);
791 session_->SignalDataChannelCreated.connect(
792 this, &PeerConnection::OnDataChannelCreated);
793 session_->SignalDataChannelDestroyed.connect(
794 this, &PeerConnection::OnDataChannelDestroyed);
795 session_->SignalDataChannelOpenMessage.connect(
796 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800797
798 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799 return true;
800}
801
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000802rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000803PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700804 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805}
806
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000807rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700809 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810}
811
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000812bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100813 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 if (IsClosed()) {
815 return false;
816 }
deadbeefab9b2d12015-10-14 11:33:11 -0700817 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 return false;
819 }
deadbeefab9b2d12015-10-14 11:33:11 -0700820
821 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800822 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
823 observer->SignalAudioTrackAdded.connect(this,
824 &PeerConnection::OnAudioTrackAdded);
825 observer->SignalAudioTrackRemoved.connect(
826 this, &PeerConnection::OnAudioTrackRemoved);
827 observer->SignalVideoTrackAdded.connect(this,
828 &PeerConnection::OnVideoTrackAdded);
829 observer->SignalVideoTrackRemoved.connect(
830 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700831 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700832
deadbeefab9b2d12015-10-14 11:33:11 -0700833 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800834 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700835 }
836 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800837 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700838 }
839
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000840 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 observer_->OnRenegotiationNeeded();
842 return true;
843}
844
845void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100846 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700847 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800848 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700849 }
850 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800851 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700852 }
853
854 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800855 stream_observers_.erase(
856 std::remove_if(
857 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700858 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800859 return observer->stream()->label().compare(local_stream->label()) ==
860 0;
861 }),
862 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700863
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 if (IsClosed()) {
865 return;
866 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000867 observer_->OnRenegotiationNeeded();
868}
869
deadbeefe1f9d832016-01-14 15:35:42 -0800870rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
871 MediaStreamTrackInterface* track,
872 std::vector<MediaStreamInterface*> streams) {
873 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
874 if (IsClosed()) {
875 return nullptr;
876 }
877 if (streams.size() >= 2) {
878 LOG(LS_ERROR)
879 << "Adding a track with two streams is not currently supported.";
880 return nullptr;
881 }
882 // TODO(deadbeef): Support adding a track to two different senders.
883 if (FindSenderForTrack(track) != senders_.end()) {
884 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
885 return nullptr;
886 }
887
888 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700889 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800890 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700891 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800892 signaling_thread(),
893 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700894 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800895 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700896 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800897 }
898 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700899 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800900 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700901 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800902 }
903 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700904 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800905 signaling_thread(),
906 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700907 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800908 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700909 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800910 }
911 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700912 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800913 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700914 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800915 }
916 } else {
917 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
918 return rtc::scoped_refptr<RtpSenderInterface>();
919 }
920
921 senders_.push_back(new_sender);
922 observer_->OnRenegotiationNeeded();
923 return new_sender;
924}
925
926bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
927 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
928 if (IsClosed()) {
929 return false;
930 }
931
932 auto it = std::find(senders_.begin(), senders_.end(), sender);
933 if (it == senders_.end()) {
934 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
935 return false;
936 }
deadbeefa601f5c2016-06-06 14:27:39 -0700937 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800938 senders_.erase(it);
939
940 observer_->OnRenegotiationNeeded();
941 return true;
942}
943
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000944rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100946 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700947 if (IsClosed()) {
948 return nullptr;
949 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 if (!track) {
951 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800952 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953 }
deadbeef20cb0c12017-02-01 20:27:00 -0800954 auto it = FindSenderForTrack(track);
955 if (it == senders_.end()) {
956 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
957 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958 }
959
deadbeef20cb0c12017-02-01 20:27:00 -0800960 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961}
962
deadbeeffac06552015-11-25 11:26:01 -0800963rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800964 const std::string& kind,
965 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100966 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700967 if (IsClosed()) {
968 return nullptr;
969 }
deadbeefa601f5c2016-06-06 14:27:39 -0700970 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800971 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700972 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700973 signaling_thread(),
974 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800975 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700976 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700977 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800978 } else {
979 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800980 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800981 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800982 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700983 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800984 }
deadbeeffac06552015-11-25 11:26:01 -0800985 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800986 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800987}
988
deadbeef70ab1a12015-09-28 16:53:55 -0700989std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
990 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700991 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
992 for (const auto& sender : senders_) {
993 ret.push_back(sender.get());
994 }
995 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700996}
997
998std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
999PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001000 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
1001 for (const auto& receiver : receivers_) {
1002 ret.push_back(receiver.get());
1003 }
1004 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001005}
1006
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001008 MediaStreamTrackInterface* track,
1009 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001010 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001011 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001012 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1014 return false;
1015 }
1016
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001017 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001018 // The StatsCollector is used to tell if a track is valid because it may
1019 // remember tracks that the PeerConnection previously removed.
1020 if (track && !stats_->IsValidTrack(track->id())) {
1021 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1022 << track->id();
1023 return false;
1024 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001025 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001026 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027 return true;
1028}
1029
hbos74e1a4f2016-09-15 23:33:01 -07001030void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1031 RTC_DCHECK(stats_collector_);
1032 stats_collector_->GetStatsReport(callback);
1033}
1034
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1036 return signaling_state_;
1037}
1038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039PeerConnectionInterface::IceConnectionState
1040PeerConnection::ice_connection_state() {
1041 return ice_connection_state_;
1042}
1043
1044PeerConnectionInterface::IceGatheringState
1045PeerConnection::ice_gathering_state() {
1046 return ice_gathering_state_;
1047}
1048
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001049rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050PeerConnection::CreateDataChannel(
1051 const std::string& label,
1052 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001053 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001054#ifdef HAVE_QUIC
1055 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1056 // TODO(zhihuang): Handle case when config is NULL.
1057 if (!config) {
1058 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1059 return nullptr;
1060 }
1061 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1062 if (!config->reliable || config->ordered) {
1063 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1064 "ordered delivery.";
1065 return nullptr;
1066 }
1067 return session_->quic_data_transport()->CreateDataChannel(label, config);
1068 }
1069#endif // HAVE_QUIC
1070
deadbeefab9b2d12015-10-14 11:33:11 -07001071 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001072
kwibergd1fe2812016-04-27 06:47:29 -07001073 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001074 if (config) {
1075 internal_config.reset(new InternalDataChannelInit(*config));
1076 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001077 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001078 InternalCreateDataChannel(label, internal_config.get()));
1079 if (!channel.get()) {
1080 return nullptr;
1081 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001083 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1084 // the first SCTP DataChannel.
1085 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1086 observer_->OnRenegotiationNeeded();
1087 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001088
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089 return DataChannelProxy::Create(signaling_thread(), channel.get());
1090}
1091
1092void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1093 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001094 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001095 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1097 return;
1098 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001099 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001100
1101 bool value;
1102 size_t mandatory_constraints = 0;
1103
1104 if (FindConstraint(constraints,
1105 MediaConstraintsInterface::kOfferToReceiveAudio,
1106 &value,
1107 &mandatory_constraints)) {
1108 options.offer_to_receive_audio =
1109 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1110 }
1111
1112 if (FindConstraint(constraints,
1113 MediaConstraintsInterface::kOfferToReceiveVideo,
1114 &value,
1115 &mandatory_constraints)) {
1116 options.offer_to_receive_video =
1117 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1118 }
1119
1120 if (FindConstraint(constraints,
1121 MediaConstraintsInterface::kVoiceActivityDetection,
1122 &value,
1123 &mandatory_constraints)) {
1124 options.voice_activity_detection = value;
1125 }
1126
1127 if (FindConstraint(constraints,
1128 MediaConstraintsInterface::kIceRestart,
1129 &value,
1130 &mandatory_constraints)) {
1131 options.ice_restart = value;
1132 }
1133
1134 if (FindConstraint(constraints,
1135 MediaConstraintsInterface::kUseRtpMux,
1136 &value,
1137 &mandatory_constraints)) {
1138 options.use_rtp_mux = value;
1139 }
1140
1141 CreateOffer(observer, options);
1142}
1143
1144void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1145 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001146 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001147 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001148 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1149 return;
1150 }
deadbeefab9b2d12015-10-14 11:33:11 -07001151
1152 cricket::MediaSessionOptions session_options;
1153 if (!GetOptionsForOffer(options, &session_options)) {
1154 std::string error = "CreateOffer called with invalid options.";
1155 LOG(LS_ERROR) << error;
1156 PostCreateSessionDescriptionFailure(observer, error);
1157 return;
1158 }
1159
1160 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001161}
1162
1163void PeerConnection::CreateAnswer(
1164 CreateSessionDescriptionObserver* observer,
1165 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001166 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001167 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1169 return;
1170 }
deadbeefab9b2d12015-10-14 11:33:11 -07001171
1172 cricket::MediaSessionOptions session_options;
1173 if (!GetOptionsForAnswer(constraints, &session_options)) {
1174 std::string error = "CreateAnswer called with invalid constraints.";
1175 LOG(LS_ERROR) << error;
1176 PostCreateSessionDescriptionFailure(observer, error);
1177 return;
1178 }
1179
htaa2a49d92016-03-04 02:51:39 -08001180 session_->CreateAnswer(observer, session_options);
1181}
1182
1183void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1184 const RTCOfferAnswerOptions& options) {
1185 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001186 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -08001187 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1188 return;
1189 }
1190
1191 cricket::MediaSessionOptions session_options;
1192 if (!GetOptionsForAnswer(options, &session_options)) {
1193 std::string error = "CreateAnswer called with invalid options.";
1194 LOG(LS_ERROR) << error;
1195 PostCreateSessionDescriptionFailure(observer, error);
1196 return;
1197 }
1198
1199 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200}
1201
1202void PeerConnection::SetLocalDescription(
1203 SetSessionDescriptionObserver* observer,
1204 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001205 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001206 if (IsClosed()) {
1207 return;
1208 }
nisse7ce109a2017-01-31 00:57:56 -08001209 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001210 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1211 return;
1212 }
1213 if (!desc) {
1214 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1215 return;
1216 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 // Update stats here so that we have the most recent stats for tracks and
1218 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001219 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220 std::string error;
1221 if (!session_->SetLocalDescription(desc, &error)) {
1222 PostSetSessionDescriptionFailure(observer, error);
1223 return;
1224 }
deadbeefab9b2d12015-10-14 11:33:11 -07001225
1226 // If setting the description decided our SSL role, allocate any necessary
1227 // SCTP sids.
1228 rtc::SSLRole role;
1229 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001230 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001231 AllocateSctpSids(role);
1232 }
1233
1234 // Update state and SSRC of local MediaStreams and DataChannels based on the
1235 // local session description.
1236 const cricket::ContentInfo* audio_content =
1237 GetFirstAudioContent(desc->description());
1238 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001239 if (audio_content->rejected) {
1240 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1241 } else {
1242 const cricket::AudioContentDescription* audio_desc =
1243 static_cast<const cricket::AudioContentDescription*>(
1244 audio_content->description);
1245 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1246 }
deadbeefab9b2d12015-10-14 11:33:11 -07001247 }
1248
1249 const cricket::ContentInfo* video_content =
1250 GetFirstVideoContent(desc->description());
1251 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001252 if (video_content->rejected) {
1253 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1254 } else {
1255 const cricket::VideoContentDescription* video_desc =
1256 static_cast<const cricket::VideoContentDescription*>(
1257 video_content->description);
1258 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1259 }
deadbeefab9b2d12015-10-14 11:33:11 -07001260 }
1261
1262 const cricket::ContentInfo* data_content =
1263 GetFirstDataContent(desc->description());
1264 if (data_content) {
1265 const cricket::DataContentDescription* data_desc =
1266 static_cast<const cricket::DataContentDescription*>(
1267 data_content->description);
1268 if (rtc::starts_with(data_desc->protocol().data(),
1269 cricket::kMediaProtocolRtpPrefix)) {
1270 UpdateLocalRtpDataChannels(data_desc->streams());
1271 }
1272 }
1273
1274 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001275 signaling_thread()->Post(RTC_FROM_HERE, this,
1276 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001277
deadbeefcbecd352015-09-23 11:50:27 -07001278 // MaybeStartGathering needs to be called after posting
1279 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1280 // before signaling that SetLocalDescription completed.
1281 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282}
1283
1284void PeerConnection::SetRemoteDescription(
1285 SetSessionDescriptionObserver* observer,
1286 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001287 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001288 if (IsClosed()) {
1289 return;
1290 }
nisse7ce109a2017-01-31 00:57:56 -08001291 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1293 return;
1294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 if (!desc) {
1296 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1297 return;
1298 }
1299 // Update stats here so that we have the most recent stats for tracks and
1300 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001301 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 std::string error;
1303 if (!session_->SetRemoteDescription(desc, &error)) {
1304 PostSetSessionDescriptionFailure(observer, error);
1305 return;
1306 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307
deadbeefab9b2d12015-10-14 11:33:11 -07001308 // If setting the description decided our SSL role, allocate any necessary
1309 // SCTP sids.
1310 rtc::SSLRole role;
1311 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001312 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001313 AllocateSctpSids(role);
1314 }
1315
1316 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001317 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1318 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1319 const cricket::AudioContentDescription* audio_desc =
1320 GetFirstAudioContentDescription(remote_desc);
1321 const cricket::VideoContentDescription* video_desc =
1322 GetFirstVideoContentDescription(remote_desc);
1323 const cricket::DataContentDescription* data_desc =
1324 GetFirstDataContentDescription(remote_desc);
1325
1326 // Check if the descriptions include streams, just in case the peer supports
1327 // MSID, but doesn't indicate so with "a=msid-semantic".
1328 if (remote_desc->msid_supported() ||
1329 (audio_desc && !audio_desc->streams().empty()) ||
1330 (video_desc && !video_desc->streams().empty())) {
1331 remote_peer_supports_msid_ = true;
1332 }
deadbeefab9b2d12015-10-14 11:33:11 -07001333
1334 // We wait to signal new streams until we finish processing the description,
1335 // since only at that point will new streams have all their tracks.
1336 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1337
1338 // Find all audio rtp streams and create corresponding remote AudioTracks
1339 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001340 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001341 if (audio_content->rejected) {
1342 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1343 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001344 bool default_audio_track_needed =
1345 !remote_peer_supports_msid_ &&
1346 MediaContentDirectionHasSend(audio_desc->direction());
1347 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1348 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001349 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001350 }
deadbeefab9b2d12015-10-14 11:33:11 -07001351 }
1352
1353 // Find all video rtp streams and create corresponding remote VideoTracks
1354 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001355 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001356 if (video_content->rejected) {
1357 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1358 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001359 bool default_video_track_needed =
1360 !remote_peer_supports_msid_ &&
1361 MediaContentDirectionHasSend(video_desc->direction());
1362 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1363 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001364 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001365 }
deadbeefab9b2d12015-10-14 11:33:11 -07001366 }
1367
1368 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001369 if (data_desc) {
1370 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001371 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001372 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001373 }
1374 }
1375
1376 // Iterate new_streams and notify the observer about new MediaStreams.
1377 for (size_t i = 0; i < new_streams->count(); ++i) {
1378 MediaStreamInterface* new_stream = new_streams->at(i);
1379 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001380 // Call both the raw pointer and scoped_refptr versions of the method
1381 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001382 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001383 observer_->OnAddStream(
1384 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001385 }
1386
deadbeefbda7e0b2015-12-08 17:13:40 -08001387 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001388
1389 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001390 signaling_thread()->Post(RTC_FROM_HERE, this,
1391 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001392}
1393
deadbeef46c73892016-11-16 19:42:04 -08001394PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1395 return configuration_;
1396}
1397
deadbeef293e9262017-01-11 12:28:30 -08001398bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1399 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001400 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001401
1402 if (session_->local_description() &&
1403 configuration.ice_candidate_pool_size !=
1404 configuration_.ice_candidate_pool_size) {
1405 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1406 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001407 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001408 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001409
deadbeef293e9262017-01-11 12:28:30 -08001410 // The simplest (and most future-compatible) way to tell if the config was
1411 // modified in an invalid way is to copy each property we do support
1412 // modifying, then use operator==. There are far more properties we don't
1413 // support modifying than those we do, and more could be added.
1414 RTCConfiguration modified_config = configuration_;
1415 modified_config.servers = configuration.servers;
1416 modified_config.type = configuration.type;
1417 modified_config.ice_candidate_pool_size =
1418 configuration.ice_candidate_pool_size;
1419 modified_config.prune_turn_ports = configuration.prune_turn_ports;
1420 if (configuration != modified_config) {
1421 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1422 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1423 }
1424
1425 // Note that this isn't possible through chromium, since it's an unsigned
1426 // short in WebIDL.
1427 if (configuration.ice_candidate_pool_size < 0 ||
1428 configuration.ice_candidate_pool_size > UINT16_MAX) {
1429 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1430 }
1431
1432 // Parse ICE servers before hopping to network thread.
1433 cricket::ServerAddresses stun_servers;
1434 std::vector<cricket::RelayServerConfig> turn_servers;
1435 RTCErrorType parse_error =
1436 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1437 if (parse_error != RTCErrorType::NONE) {
1438 return SafeSetError(parse_error, error);
1439 }
1440
1441 // In theory this shouldn't fail.
1442 if (!network_thread()->Invoke<bool>(
1443 RTC_FROM_HERE,
1444 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1445 stun_servers, turn_servers, modified_config.type,
1446 modified_config.ice_candidate_pool_size,
1447 modified_config.prune_turn_ports))) {
1448 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1449 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1450 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001451
deadbeefd1a38b52016-12-10 13:15:33 -08001452 // As described in JSEP, calling setConfiguration with new ICE servers or
1453 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1454 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001455 if (modified_config.servers != configuration_.servers ||
1456 modified_config.type != configuration_.type ||
1457 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001458 session_->SetNeedsIceRestartFlag();
1459 }
deadbeef293e9262017-01-11 12:28:30 -08001460 configuration_ = modified_config;
1461 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001462}
1463
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464bool PeerConnection::AddIceCandidate(
1465 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001466 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001467 if (IsClosed()) {
1468 return false;
1469 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470 return session_->ProcessIceMessage(ice_candidate);
1471}
1472
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001473bool PeerConnection::RemoveIceCandidates(
1474 const std::vector<cricket::Candidate>& candidates) {
1475 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1476 return session_->RemoveRemoteIceCandidates(candidates);
1477}
1478
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001479void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001480 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001481 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001482
1483 if (session_) {
1484 session_->set_metrics_observer(uma_observer_);
1485 }
1486
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001487 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001488 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001489 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001490 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001491 uma_observer_->IncrementEnumCounter(
1492 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1493 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001494 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001495 uma_observer_->IncrementEnumCounter(
1496 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1497 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001498 }
1499 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001500}
1501
ivoc14d5dbe2016-07-04 07:06:55 -07001502bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1503 int64_t max_size_bytes) {
1504 return factory_->worker_thread()->Invoke<bool>(
1505 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1506 max_size_bytes));
1507}
1508
1509void PeerConnection::StopRtcEventLog() {
1510 factory_->worker_thread()->Invoke<void>(
1511 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1512}
1513
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514const SessionDescriptionInterface* PeerConnection::local_description() const {
1515 return session_->local_description();
1516}
1517
1518const SessionDescriptionInterface* PeerConnection::remote_description() const {
1519 return session_->remote_description();
1520}
1521
deadbeeffe4a8a42016-12-20 17:56:17 -08001522const SessionDescriptionInterface* PeerConnection::current_local_description()
1523 const {
1524 return session_->current_local_description();
1525}
1526
1527const SessionDescriptionInterface* PeerConnection::current_remote_description()
1528 const {
1529 return session_->current_remote_description();
1530}
1531
1532const SessionDescriptionInterface* PeerConnection::pending_local_description()
1533 const {
1534 return session_->pending_local_description();
1535}
1536
1537const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1538 const {
1539 return session_->pending_remote_description();
1540}
1541
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001542void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001543 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001544 // Update stats here so that we have the most recent stats for tracks and
1545 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001546 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547
deadbeefd59daf82015-10-14 15:02:44 -07001548 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549}
1550
deadbeefd59daf82015-10-14 15:02:44 -07001551void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1552 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001553 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001554 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001555 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001556 break;
deadbeefd59daf82015-10-14 15:02:44 -07001557 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1559 break;
deadbeefd59daf82015-10-14 15:02:44 -07001560 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1562 break;
deadbeefd59daf82015-10-14 15:02:44 -07001563 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001564 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1565 break;
deadbeefd59daf82015-10-14 15:02:44 -07001566 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1568 break;
deadbeefd59daf82015-10-14 15:02:44 -07001569 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 ChangeSignalingState(PeerConnectionInterface::kStable);
1571 break;
deadbeefd59daf82015-10-14 15:02:44 -07001572 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573 ChangeSignalingState(PeerConnectionInterface::kClosed);
1574 break;
1575 default:
1576 break;
1577 }
1578}
1579
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001580void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001581 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1583 SetSessionDescriptionMsg* param =
1584 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1585 param->observer->OnSuccess();
1586 delete param;
1587 break;
1588 }
1589 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1590 SetSessionDescriptionMsg* param =
1591 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1592 param->observer->OnFailure(param->error);
1593 delete param;
1594 break;
1595 }
deadbeefab9b2d12015-10-14 11:33:11 -07001596 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1597 CreateSessionDescriptionMsg* param =
1598 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1599 param->observer->OnFailure(param->error);
1600 delete param;
1601 break;
1602 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603 case MSG_GETSTATS: {
1604 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001605 StatsReports reports;
1606 stats_->GetStats(param->track, &reports);
1607 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001608 delete param;
1609 break;
1610 }
deadbeefbd292462015-12-14 18:15:29 -08001611 case MSG_FREE_DATACHANNELS: {
1612 sctp_data_channels_to_free_.clear();
1613 break;
1614 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001615 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001616 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 break;
1618 }
1619}
1620
deadbeefab9b2d12015-10-14 11:33:11 -07001621void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001622 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001623 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001624 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1625 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001626 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001627 session_->voice_channel()));
1628
1629 receivers_.push_back(receiver);
1630 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1631 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1632 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001633}
1634
deadbeefab9b2d12015-10-14 11:33:11 -07001635void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001636 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001637 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001638 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1639 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001640 signaling_thread(),
1641 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001642 ssrc, session_->video_channel()));
1643 receivers_.push_back(receiver);
1644 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1645 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1646 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001647}
1648
deadbeef70ab1a12015-09-28 16:53:55 -07001649// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1650// description.
perkjd61bf802016-03-24 03:16:19 -07001651void PeerConnection::DestroyReceiver(const std::string& track_id) {
1652 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001653 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001654 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001655 << " doesn't exist.";
1656 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001657 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001658 receivers_.erase(it);
1659 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001660}
1661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001662void PeerConnection::OnIceConnectionChange(
1663 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001664 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001665 // After transitioning to "closed", ignore any additional states from
1666 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001667 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001668 return;
1669 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001670 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001671 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672}
1673
1674void PeerConnection::OnIceGatheringChange(
1675 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001676 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001677 if (IsClosed()) {
1678 return;
1679 }
1680 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001681 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001682}
1683
1684void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001685 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001686 if (IsClosed()) {
1687 return;
1688 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001689 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690}
1691
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001692void PeerConnection::OnIceCandidatesRemoved(
1693 const std::vector<cricket::Candidate>& candidates) {
1694 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001695 if (IsClosed()) {
1696 return;
1697 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001698 observer_->OnIceCandidatesRemoved(candidates);
1699}
1700
Peter Thatcher54360512015-07-08 11:08:35 -07001701void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001702 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001703 if (IsClosed()) {
1704 return;
1705 }
Peter Thatcher54360512015-07-08 11:08:35 -07001706 observer_->OnIceConnectionReceivingChange(receiving);
1707}
1708
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709void PeerConnection::ChangeSignalingState(
1710 PeerConnectionInterface::SignalingState signaling_state) {
1711 signaling_state_ = signaling_state;
1712 if (signaling_state == kClosed) {
1713 ice_connection_state_ = kIceConnectionClosed;
1714 observer_->OnIceConnectionChange(ice_connection_state_);
1715 if (ice_gathering_state_ != kIceGatheringComplete) {
1716 ice_gathering_state_ = kIceGatheringComplete;
1717 observer_->OnIceGatheringChange(ice_gathering_state_);
1718 }
1719 }
1720 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721}
1722
deadbeefeb459812015-12-15 19:24:43 -08001723void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1724 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001725 if (IsClosed()) {
1726 return;
1727 }
deadbeefeb459812015-12-15 19:24:43 -08001728 auto sender = FindSenderForTrack(track);
1729 if (sender != senders_.end()) {
1730 // We already have a sender for this track, so just change the stream_id
1731 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001732 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001733 return;
1734 }
1735
1736 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001737 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1738 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001739 signaling_thread(),
1740 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1741 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001742 senders_.push_back(new_sender);
1743 // If the sender has already been configured in SDP, we call SetSsrc,
1744 // which will connect the sender to the underlying transport. This can
1745 // occur if a local session description that contains the ID of the sender
1746 // is set before AddStream is called. It can also occur if the local
1747 // session description is not changed and RemoveStream is called, and
1748 // later AddStream is called again with the same stream.
1749 const TrackInfo* track_info =
1750 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1751 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001752 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001753 }
1754}
1755
1756// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1757// indefinitely, when we have unified plan SDP.
1758void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1759 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001760 if (IsClosed()) {
1761 return;
1762 }
deadbeefeb459812015-12-15 19:24:43 -08001763 auto sender = FindSenderForTrack(track);
1764 if (sender == senders_.end()) {
1765 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1766 << " doesn't exist.";
1767 return;
1768 }
deadbeefa601f5c2016-06-06 14:27:39 -07001769 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001770 senders_.erase(sender);
1771}
1772
1773void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1774 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001775 if (IsClosed()) {
1776 return;
1777 }
deadbeefeb459812015-12-15 19:24:43 -08001778 auto sender = FindSenderForTrack(track);
1779 if (sender != senders_.end()) {
1780 // We already have a sender for this track, so just change the stream_id
1781 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001782 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001783 return;
1784 }
1785
1786 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001787 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1788 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001789 signaling_thread(), new VideoRtpSender(track, stream->label(),
1790 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001791 senders_.push_back(new_sender);
1792 const TrackInfo* track_info =
1793 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1794 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001795 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001796 }
1797}
1798
1799void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1800 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001801 if (IsClosed()) {
1802 return;
1803 }
deadbeefeb459812015-12-15 19:24:43 -08001804 auto sender = FindSenderForTrack(track);
1805 if (sender == senders_.end()) {
1806 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1807 << " doesn't exist.";
1808 return;
1809 }
deadbeefa601f5c2016-06-06 14:27:39 -07001810 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001811 senders_.erase(sender);
1812}
1813
deadbeefab9b2d12015-10-14 11:33:11 -07001814void PeerConnection::PostSetSessionDescriptionFailure(
1815 SetSessionDescriptionObserver* observer,
1816 const std::string& error) {
1817 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1818 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001819 signaling_thread()->Post(RTC_FROM_HERE, this,
1820 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001821}
1822
1823void PeerConnection::PostCreateSessionDescriptionFailure(
1824 CreateSessionDescriptionObserver* observer,
1825 const std::string& error) {
1826 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1827 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001828 signaling_thread()->Post(RTC_FROM_HERE, this,
1829 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001830}
1831
1832bool PeerConnection::GetOptionsForOffer(
1833 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1834 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001835 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1836 // ContentInfos.
1837 if (session_->local_description()) {
1838 for (const cricket::ContentInfo& content :
1839 session_->local_description()->description()->contents()) {
1840 session_options->transport_options[content.name] =
1841 cricket::TransportOptions();
1842 }
1843 }
deadbeef46c73892016-11-16 19:42:04 -08001844 session_options->enable_ice_renomination =
1845 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001846
htaaac2dea2016-03-10 13:35:55 -08001847 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001848 return false;
1849 }
1850
deadbeeffac06552015-11-25 11:26:01 -08001851 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001852 // Offer to receive audio/video if the constraint is not set and there are
1853 // send streams, or we're currently receiving.
1854 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1855 session_options->recv_audio =
1856 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1857 !remote_audio_tracks_.empty();
1858 }
1859 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1860 session_options->recv_video =
1861 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1862 !remote_video_tracks_.empty();
1863 }
deadbeefc80741f2015-10-22 13:14:45 -07001864
zhihuang9763d562016-08-05 11:14:50 -07001865 // Intentionally unset the data channel type for RTP data channel with the
1866 // second condition. Otherwise the RTP data channels would be successfully
1867 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1868 // when building with chromium. We want to leave RTP data channels broken, so
1869 // people won't try to use them.
1870 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1871 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001872 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001873
zhihuangaf388472016-11-02 16:49:48 -07001874 session_options->bundle_enabled =
1875 session_options->bundle_enabled &&
1876 (session_options->has_audio() || session_options->has_video() ||
1877 session_options->has_data());
1878
zhihuang8f65cdf2016-05-06 18:40:30 -07001879 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001880 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001881 return true;
1882}
1883
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001884void PeerConnection::InitializeOptionsForAnswer(
1885 cricket::MediaSessionOptions* session_options) {
1886 session_options->recv_audio = false;
1887 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001888 session_options->enable_ice_renomination =
1889 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001890}
1891
htaa2a49d92016-03-04 02:51:39 -08001892void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001893 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001894 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1895 // ContentInfos.
1896 if (session_->remote_description()) {
1897 // Initialize the transport_options map.
1898 for (const cricket::ContentInfo& content :
1899 session_->remote_description()->description()->contents()) {
1900 session_options->transport_options[content.name] =
1901 cricket::TransportOptions();
1902 }
1903 }
deadbeeffac06552015-11-25 11:26:01 -08001904 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001905 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1906 // are not signaled in the SDP so does not go through that path and must be
1907 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001908 // Intentionally unset the data channel type for RTP data channel. Otherwise
1909 // the RTP data channels would be successfully negotiated by default and the
1910 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1911 // We want to leave RTP data channels broken, so people won't try to use them.
1912 if (session_->data_channel_type() != cricket::DCT_RTP) {
1913 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001914 }
zhihuangaf388472016-11-02 16:49:48 -07001915 session_options->bundle_enabled =
1916 session_options->bundle_enabled &&
1917 (session_options->has_audio() || session_options->has_video() ||
1918 session_options->has_data());
1919
jbauchcb560652016-08-04 05:20:32 -07001920 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001921}
1922
1923bool PeerConnection::GetOptionsForAnswer(
1924 const MediaConstraintsInterface* constraints,
1925 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001926 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001927 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1928 return false;
1929 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001930 session_options->rtcp_cname = rtcp_cname_;
1931
htaa2a49d92016-03-04 02:51:39 -08001932 FinishOptionsForAnswer(session_options);
1933 return true;
1934}
1935
1936bool PeerConnection::GetOptionsForAnswer(
1937 const RTCOfferAnswerOptions& options,
1938 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001939 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001940 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001941 return false;
1942 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001943 session_options->rtcp_cname = rtcp_cname_;
1944
htaa2a49d92016-03-04 02:51:39 -08001945 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001946 return true;
1947}
1948
deadbeeffaac4972015-11-12 15:33:07 -08001949void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1950 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001951 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1952 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001953}
1954
deadbeefab9b2d12015-10-14 11:33:11 -07001955void PeerConnection::UpdateRemoteStreamsList(
1956 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001957 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001958 cricket::MediaType media_type,
1959 StreamCollection* new_streams) {
1960 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1961
1962 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001963 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001964 auto track_it = current_tracks->begin();
1965 while (track_it != current_tracks->end()) {
1966 const TrackInfo& info = *track_it;
1967 const cricket::StreamParams* params =
1968 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001969 bool track_exists = params && params->id == info.track_id;
1970 // If this is a default track, and we still need it, don't remove it.
1971 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1972 track_exists) {
1973 ++track_it;
1974 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001975 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1976 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001977 }
1978 }
1979
1980 // Find new and active tracks.
1981 for (const cricket::StreamParams& params : streams) {
1982 // The sync_label is the MediaStream label and the |stream.id| is the
1983 // track id.
1984 const std::string& stream_label = params.sync_label;
1985 const std::string& track_id = params.id;
1986 uint32_t ssrc = params.first_ssrc();
1987
1988 rtc::scoped_refptr<MediaStreamInterface> stream =
1989 remote_streams_->find(stream_label);
1990 if (!stream) {
1991 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001992 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1993 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001994 remote_streams_->AddStream(stream);
1995 new_streams->AddStream(stream);
1996 }
1997
1998 const TrackInfo* track_info =
1999 FindTrackInfo(*current_tracks, stream_label, track_id);
2000 if (!track_info) {
2001 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2002 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2003 }
2004 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002005
2006 // Add default track if necessary.
2007 if (default_track_needed) {
2008 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2009 remote_streams_->find(kDefaultStreamLabel);
2010 if (!default_stream) {
2011 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002012 default_stream = MediaStreamProxy::Create(
2013 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002014 remote_streams_->AddStream(default_stream);
2015 new_streams->AddStream(default_stream);
2016 }
2017 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2018 ? kDefaultAudioTrackLabel
2019 : kDefaultVideoTrackLabel;
2020 const TrackInfo* default_track_info =
2021 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2022 if (!default_track_info) {
2023 current_tracks->push_back(
2024 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2025 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2026 }
2027 }
deadbeefab9b2d12015-10-14 11:33:11 -07002028}
2029
2030void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2031 const std::string& track_id,
2032 uint32_t ssrc,
2033 cricket::MediaType media_type) {
2034 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2035
2036 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002037 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002038 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002039 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002040 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002041 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002042 }
2043}
2044
2045void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2046 const std::string& track_id,
2047 cricket::MediaType media_type) {
2048 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2049
2050 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002051 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2052 // will be notified which will end the AudioRtpReceiver::track().
2053 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002054 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2055 stream->FindAudioTrack(track_id);
2056 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002057 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002058 }
2059 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002060 // Stopping or destroying a VideoRtpReceiver will end the
2061 // VideoRtpReceiver::track().
2062 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002063 rtc::scoped_refptr<VideoTrackInterface> video_track =
2064 stream->FindVideoTrack(track_id);
2065 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002066 // There's no guarantee the track is still available, e.g. the track may
2067 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002068 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002069 }
2070 } else {
nisseede5da42017-01-12 05:15:36 -08002071 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002072 }
2073}
2074
2075void PeerConnection::UpdateEndedRemoteMediaStreams() {
2076 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2077 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2078 MediaStreamInterface* stream = remote_streams_->at(i);
2079 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2080 streams_to_remove.push_back(stream);
2081 }
2082 }
2083
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002084 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002085 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002086 // Call both the raw pointer and scoped_refptr versions of the method
2087 // for compatibility.
2088 observer_->OnRemoveStream(stream.get());
2089 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002090 }
2091}
2092
deadbeefab9b2d12015-10-14 11:33:11 -07002093void PeerConnection::UpdateLocalTracks(
2094 const std::vector<cricket::StreamParams>& streams,
2095 cricket::MediaType media_type) {
2096 TrackInfos* current_tracks = GetLocalTracks(media_type);
2097
2098 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2099 // don't match the new StreamParam.
2100 TrackInfos::iterator track_it = current_tracks->begin();
2101 while (track_it != current_tracks->end()) {
2102 const TrackInfo& info = *track_it;
2103 const cricket::StreamParams* params =
2104 cricket::GetStreamBySsrc(streams, info.ssrc);
2105 if (!params || params->id != info.track_id ||
2106 params->sync_label != info.stream_label) {
2107 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2108 media_type);
2109 track_it = current_tracks->erase(track_it);
2110 } else {
2111 ++track_it;
2112 }
2113 }
2114
2115 // Find new and active tracks.
2116 for (const cricket::StreamParams& params : streams) {
2117 // The sync_label is the MediaStream label and the |stream.id| is the
2118 // track id.
2119 const std::string& stream_label = params.sync_label;
2120 const std::string& track_id = params.id;
2121 uint32_t ssrc = params.first_ssrc();
2122 const TrackInfo* track_info =
2123 FindTrackInfo(*current_tracks, stream_label, track_id);
2124 if (!track_info) {
2125 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2126 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2127 }
2128 }
2129}
2130
2131void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2132 const std::string& track_id,
2133 uint32_t ssrc,
2134 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002135 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002136 if (!sender) {
2137 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2138 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002139 return;
2140 }
2141
deadbeeffac06552015-11-25 11:26:01 -08002142 if (sender->media_type() != media_type) {
2143 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2144 << " description with an unexpected media type.";
2145 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002146 }
deadbeeffac06552015-11-25 11:26:01 -08002147
2148 sender->set_stream_id(stream_label);
2149 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002150}
2151
2152void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2153 const std::string& track_id,
2154 uint32_t ssrc,
2155 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002156 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002157 if (!sender) {
2158 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002159 // SessionDescriptions has been renegotiated.
2160 return;
2161 }
deadbeeffac06552015-11-25 11:26:01 -08002162
2163 // A sender has been removed from the SessionDescription but it's still
2164 // associated with the PeerConnection. This only occurs if the SDP doesn't
2165 // match with the calls to CreateSender, AddStream and RemoveStream.
2166 if (sender->media_type() != media_type) {
2167 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2168 << " description with an unexpected media type.";
2169 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002170 }
deadbeeffac06552015-11-25 11:26:01 -08002171
2172 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002173}
2174
2175void PeerConnection::UpdateLocalRtpDataChannels(
2176 const cricket::StreamParamsVec& streams) {
2177 std::vector<std::string> existing_channels;
2178
2179 // Find new and active data channels.
2180 for (const cricket::StreamParams& params : streams) {
2181 // |it->sync_label| is actually the data channel label. The reason is that
2182 // we use the same naming of data channels as we do for
2183 // MediaStreams and Tracks.
2184 // For MediaStreams, the sync_label is the MediaStream label and the
2185 // track label is the same as |streamid|.
2186 const std::string& channel_label = params.sync_label;
2187 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002188 if (data_channel_it == rtp_data_channels_.end()) {
2189 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002190 continue;
2191 }
2192 // Set the SSRC the data channel should use for sending.
2193 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2194 existing_channels.push_back(data_channel_it->first);
2195 }
2196
2197 UpdateClosingRtpDataChannels(existing_channels, true);
2198}
2199
2200void PeerConnection::UpdateRemoteRtpDataChannels(
2201 const cricket::StreamParamsVec& streams) {
2202 std::vector<std::string> existing_channels;
2203
2204 // Find new and active data channels.
2205 for (const cricket::StreamParams& params : streams) {
2206 // The data channel label is either the mslabel or the SSRC if the mslabel
2207 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2208 std::string label = params.sync_label.empty()
2209 ? rtc::ToString(params.first_ssrc())
2210 : params.sync_label;
2211 auto data_channel_it = rtp_data_channels_.find(label);
2212 if (data_channel_it == rtp_data_channels_.end()) {
2213 // This is a new data channel.
2214 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2215 } else {
2216 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2217 }
2218 existing_channels.push_back(label);
2219 }
2220
2221 UpdateClosingRtpDataChannels(existing_channels, false);
2222}
2223
2224void PeerConnection::UpdateClosingRtpDataChannels(
2225 const std::vector<std::string>& active_channels,
2226 bool is_local_update) {
2227 auto it = rtp_data_channels_.begin();
2228 while (it != rtp_data_channels_.end()) {
2229 DataChannel* data_channel = it->second;
2230 if (std::find(active_channels.begin(), active_channels.end(),
2231 data_channel->label()) != active_channels.end()) {
2232 ++it;
2233 continue;
2234 }
2235
2236 if (is_local_update) {
2237 data_channel->SetSendSsrc(0);
2238 } else {
2239 data_channel->RemotePeerRequestClose();
2240 }
2241
2242 if (data_channel->state() == DataChannel::kClosed) {
2243 rtp_data_channels_.erase(it);
2244 it = rtp_data_channels_.begin();
2245 } else {
2246 ++it;
2247 }
2248 }
2249}
2250
2251void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2252 uint32_t remote_ssrc) {
2253 rtc::scoped_refptr<DataChannel> channel(
2254 InternalCreateDataChannel(label, nullptr));
2255 if (!channel.get()) {
2256 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2257 << "CreateDataChannel failed.";
2258 return;
2259 }
2260 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002261 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2262 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002263 // Call both the raw pointer and scoped_refptr versions of the method
2264 // for compatibility.
2265 observer_->OnDataChannel(proxy_channel.get());
2266 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002267}
2268
2269rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2270 const std::string& label,
2271 const InternalDataChannelInit* config) {
2272 if (IsClosed()) {
2273 return nullptr;
2274 }
2275 if (session_->data_channel_type() == cricket::DCT_NONE) {
2276 LOG(LS_ERROR)
2277 << "InternalCreateDataChannel: Data is not supported in this call.";
2278 return nullptr;
2279 }
2280 InternalDataChannelInit new_config =
2281 config ? (*config) : InternalDataChannelInit();
2282 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2283 if (new_config.id < 0) {
2284 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002285 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002286 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2287 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2288 return nullptr;
2289 }
2290 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2291 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2292 << "because the id is already in use or out of range.";
2293 return nullptr;
2294 }
2295 }
2296
2297 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2298 session_.get(), session_->data_channel_type(), label, new_config));
2299 if (!channel) {
2300 sid_allocator_.ReleaseSid(new_config.id);
2301 return nullptr;
2302 }
2303
2304 if (channel->data_channel_type() == cricket::DCT_RTP) {
2305 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2306 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2307 << " already exists.";
2308 return nullptr;
2309 }
2310 rtp_data_channels_[channel->label()] = channel;
2311 } else {
2312 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2313 sctp_data_channels_.push_back(channel);
2314 channel->SignalClosed.connect(this,
2315 &PeerConnection::OnSctpDataChannelClosed);
2316 }
2317
hbos82ebe022016-11-14 01:41:09 -08002318 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002319 return channel;
2320}
2321
2322bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002323#ifdef HAVE_QUIC
2324 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2325 (session_->quic_data_transport() &&
2326 session_->quic_data_transport()->HasDataChannels());
2327#else
deadbeefab9b2d12015-10-14 11:33:11 -07002328 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002329#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002330}
2331
2332void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2333 for (const auto& channel : sctp_data_channels_) {
2334 if (channel->id() < 0) {
2335 int sid;
2336 if (!sid_allocator_.AllocateSid(role, &sid)) {
2337 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2338 continue;
2339 }
2340 channel->SetSctpSid(sid);
2341 }
2342 }
2343}
2344
2345void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002346 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002347 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2348 ++it) {
2349 if (it->get() == channel) {
2350 if (channel->id() >= 0) {
2351 sid_allocator_.ReleaseSid(channel->id());
2352 }
deadbeefbd292462015-12-14 18:15:29 -08002353 // Since this method is triggered by a signal from the DataChannel,
2354 // we can't free it directly here; we need to free it asynchronously.
2355 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002356 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002357 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2358 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002359 return;
2360 }
2361 }
2362}
2363
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002364void PeerConnection::OnVoiceChannelCreated() {
2365 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2366 session_->voice_channel(), senders_, receivers_,
2367 cricket::MEDIA_TYPE_AUDIO);
2368}
2369
deadbeefab9b2d12015-10-14 11:33:11 -07002370void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002371 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2372 cricket::VoiceChannel>(
2373 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2374}
2375
2376void PeerConnection::OnVideoChannelCreated() {
2377 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2378 session_->video_channel(), senders_, receivers_,
2379 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002380}
2381
2382void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002383 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2384 cricket::VideoChannel>(
2385 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002386}
2387
2388void PeerConnection::OnDataChannelCreated() {
2389 for (const auto& channel : sctp_data_channels_) {
2390 channel->OnTransportChannelCreated();
2391 }
2392}
2393
2394void PeerConnection::OnDataChannelDestroyed() {
2395 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2396 // DataChannel may callback to us and try to modify the list.
2397 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2398 temp_rtp_dcs.swap(rtp_data_channels_);
2399 for (const auto& kv : temp_rtp_dcs) {
2400 kv.second->OnTransportChannelDestroyed();
2401 }
2402
2403 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2404 temp_sctp_dcs.swap(sctp_data_channels_);
2405 for (const auto& channel : temp_sctp_dcs) {
2406 channel->OnTransportChannelDestroyed();
2407 }
2408}
2409
2410void PeerConnection::OnDataChannelOpenMessage(
2411 const std::string& label,
2412 const InternalDataChannelInit& config) {
2413 rtc::scoped_refptr<DataChannel> channel(
2414 InternalCreateDataChannel(label, &config));
2415 if (!channel.get()) {
2416 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2417 return;
2418 }
2419
deadbeefa601f5c2016-06-06 14:27:39 -07002420 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2421 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002422 // Call both the raw pointer and scoped_refptr versions of the method
2423 // for compatibility.
2424 observer_->OnDataChannel(proxy_channel.get());
2425 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002426}
2427
deadbeefa601f5c2016-06-06 14:27:39 -07002428RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2429 auto it = std::find_if(
2430 senders_.begin(), senders_.end(),
2431 [id](const rtc::scoped_refptr<
2432 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2433 return sender->id() == id;
2434 });
2435 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002436}
2437
deadbeefa601f5c2016-06-06 14:27:39 -07002438std::vector<
2439 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002440PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2441 return std::find_if(
2442 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002443 [track](const rtc::scoped_refptr<
2444 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002445 return sender->track() == track;
2446 });
2447}
2448
deadbeefa601f5c2016-06-06 14:27:39 -07002449std::vector<rtc::scoped_refptr<
2450 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002451PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002452 return std::find_if(
2453 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002454 [track_id](const rtc::scoped_refptr<
2455 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002456 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002457 });
2458}
2459
deadbeefab9b2d12015-10-14 11:33:11 -07002460PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2461 cricket::MediaType media_type) {
2462 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2463 media_type == cricket::MEDIA_TYPE_VIDEO);
2464 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2465 : &remote_video_tracks_;
2466}
2467
2468PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2469 cricket::MediaType media_type) {
2470 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2471 media_type == cricket::MEDIA_TYPE_VIDEO);
2472 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2473 : &local_video_tracks_;
2474}
2475
2476const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2477 const PeerConnection::TrackInfos& infos,
2478 const std::string& stream_label,
2479 const std::string track_id) const {
2480 for (const TrackInfo& track_info : infos) {
2481 if (track_info.stream_label == stream_label &&
2482 track_info.track_id == track_id) {
2483 return &track_info;
2484 }
2485 }
2486 return nullptr;
2487}
2488
2489DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2490 for (const auto& channel : sctp_data_channels_) {
2491 if (channel->id() == sid) {
2492 return channel;
2493 }
2494 }
2495 return nullptr;
2496}
2497
deadbeef91dd5672016-05-18 16:55:30 -07002498bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002499 const RTCConfiguration& configuration) {
2500 cricket::ServerAddresses stun_servers;
2501 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002502 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2503 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002504 return false;
2505 }
2506
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002507 port_allocator_->Initialize();
2508
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002509 // To handle both internal and externally created port allocator, we will
2510 // enable BUNDLE here.
2511 int portallocator_flags = port_allocator_->flags();
2512 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2513 cricket::PORTALLOCATOR_ENABLE_IPV6;
2514 // If the disable-IPv6 flag was specified, we'll not override it
2515 // by experiment.
2516 if (configuration.disable_ipv6) {
2517 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2518 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2519 "Disabled") {
2520 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2521 }
2522
2523 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2524 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2525 LOG(LS_INFO) << "TCP candidates are disabled.";
2526 }
2527
honghaiz60347052016-05-31 18:29:12 -07002528 if (configuration.candidate_network_policy ==
2529 kCandidateNetworkPolicyLowCost) {
2530 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2531 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2532 }
2533
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002534 port_allocator_->set_flags(portallocator_flags);
2535 // No step delay is used while allocating ports.
2536 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2537 port_allocator_->set_candidate_filter(
2538 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2539
2540 // Call this last since it may create pooled allocator sessions using the
2541 // properties set above.
2542 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002543 configuration.ice_candidate_pool_size,
2544 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002545 return true;
2546}
2547
deadbeef91dd5672016-05-18 16:55:30 -07002548bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002549 const cricket::ServerAddresses& stun_servers,
2550 const std::vector<cricket::RelayServerConfig>& turn_servers,
2551 IceTransportsType type,
2552 int candidate_pool_size,
2553 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002554 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002555 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002556 // Call this last since it may create pooled allocator sessions using the
2557 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002558 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002559 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002560}
2561
ivoc14d5dbe2016-07-04 07:06:55 -07002562bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2563 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002564 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002565}
2566
2567void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002568 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002569}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570} // namespace webrtc