blob: 3f01d69edffd6cee081e33a7d1613aca2f4af18d [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 }
zstein9dd77ba2017-02-07 15:09:50 -0800248 if (tokens.size() < 2) {
249 LOG(LS_WARNING) << "Transport parameter missing value.";
250 return RTCErrorType::SYNTAX_ERROR;
251 }
252 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
hnslbd44bb02016-12-12 03:14:30 -0800253 (turn_transport_type != cricket::PROTO_UDP &&
254 turn_transport_type != cricket::PROTO_TCP)) {
zstein9dd77ba2017-02-07 15:09:50 -0800255 LOG(LS_WARNING) << "Transport parameter should always be udp or tcp.";
deadbeef293e9262017-01-11 12:28:30 -0800256 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200258 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200262 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
263 &service_type,
264 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
deadbeef293e9262017-01-11 12:28:30 -0800266 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200267 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000268
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
270 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200271
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200272 // Let's break hostname.
273 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700274 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
275
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200276 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700277 if (tokens.size() > kTurnHostTokensNum) {
278 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800279 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700280 }
281 if (tokens.size() == kTurnHostTokensNum) {
282 if (tokens[0].empty() || tokens[1].empty()) {
283 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800284 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700285 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200286 username.assign(rtc::s_url_decode(tokens[0]));
287 hoststring = tokens[1];
288 } else {
289 hoststring = tokens[0];
290 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000291
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200292 int port = kDefaultStunPort;
293 if (service_type == TURNS) {
294 port = kDefaultStunTlsPort;
hnsl277b2502016-12-13 05:17:23 -0800295 turn_transport_type = cricket::PROTO_TLS;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200296 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000297
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200298 std::string address;
299 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700300 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
deadbeef293e9262017-01-11 12:28:30 -0800301 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200302 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000303
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200304 if (port <= 0 || port > 0xffff) {
305 LOG(WARNING) << "Invalid port: " << port;
deadbeef293e9262017-01-11 12:28:30 -0800306 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000308
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200309 switch (service_type) {
310 case STUN:
311 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800312 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200313 break;
314 case TURN:
315 case TURNS: {
deadbeef293e9262017-01-11 12:28:30 -0800316 if (username.empty() || server.password.empty()) {
317 // The WebRTC spec requires throwing an InvalidAccessError when username
318 // or credential are ommitted; this is the native equivalent.
319 return RTCErrorType::INVALID_PARAMETER;
320 }
hnsl04833622017-01-09 08:35:45 -0800321 cricket::RelayServerConfig config = cricket::RelayServerConfig(
322 address, port, username, server.password, turn_transport_type);
323 if (server.tls_cert_policy ==
324 PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
325 config.tls_cert_policy =
326 cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
327 }
328 turn_servers->push_back(config);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200329 break;
330 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200331 default:
deadbeef293e9262017-01-11 12:28:30 -0800332 // We shouldn't get to this point with an invalid service_type, we should
333 // have returned an error already.
nisseeb4ca4e2017-01-12 02:24:27 -0800334 RTC_NOTREACHED() << "Unexpected service type";
deadbeef293e9262017-01-11 12:28:30 -0800335 return RTCErrorType::INTERNAL_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200336 }
deadbeef293e9262017-01-11 12:28:30 -0800337 return RTCErrorType::NONE;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200338}
339
deadbeefab9b2d12015-10-14 11:33:11 -0700340// Check if we can send |new_stream| on a PeerConnection.
341bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
342 webrtc::MediaStreamInterface* new_stream) {
343 if (!new_stream || !current_streams) {
344 return false;
345 }
346 if (current_streams->find(new_stream->label()) != nullptr) {
347 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
348 << " is already added.";
349 return false;
350 }
351 return true;
352}
353
354bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
355 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
356}
357
deadbeef5e97fb52015-10-15 12:49:08 -0700358// If the direction is "recvonly" or "inactive", treat the description
359// as containing no streams.
360// See: https://code.google.com/p/webrtc/issues/detail?id=5054
361std::vector<cricket::StreamParams> GetActiveStreams(
362 const cricket::MediaContentDescription* desc) {
363 return MediaContentDirectionHasSend(desc->direction())
364 ? desc->streams()
365 : std::vector<cricket::StreamParams>();
366}
367
deadbeefab9b2d12015-10-14 11:33:11 -0700368bool IsValidOfferToReceiveMedia(int value) {
369 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
370 return (value >= Options::kUndefined) &&
371 (value <= Options::kMaxOfferToReceiveMedia);
372}
373
374// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800375void AddSendStreams(
376 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700377 const std::vector<rtc::scoped_refptr<
378 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800379 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
380 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700381 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800382 for (const auto& sender : senders) {
383 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700384 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700385 }
386
387 // Check for data channels.
388 for (const auto& kv : rtp_data_channels) {
389 const DataChannel* channel = kv.second;
390 if (channel->state() == DataChannel::kConnecting ||
391 channel->state() == DataChannel::kOpen) {
392 // |streamid| and |sync_label| are both set to the DataChannel label
393 // here so they can be signaled the same way as MediaStreams and Tracks.
394 // For MediaStreams, the sync_label is the MediaStream label and the
395 // track label is the same as |streamid|.
396 const std::string& streamid = channel->label();
397 const std::string& sync_label = channel->label();
398 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
399 sync_label);
400 }
401 }
402}
403
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700404uint32_t ConvertIceTransportTypeToCandidateFilter(
405 PeerConnectionInterface::IceTransportsType type) {
406 switch (type) {
407 case PeerConnectionInterface::kNone:
408 return cricket::CF_NONE;
409 case PeerConnectionInterface::kRelay:
410 return cricket::CF_RELAY;
411 case PeerConnectionInterface::kNoHost:
412 return (cricket::CF_ALL & ~cricket::CF_HOST);
413 case PeerConnectionInterface::kAll:
414 return cricket::CF_ALL;
415 default:
nissec80e7412017-01-11 05:56:46 -0800416 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700417 }
418 return cricket::CF_NONE;
419}
420
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700421// Helper method to set a voice/video channel on all applicable senders
422// and receivers when one is created/destroyed by WebRtcSession.
423//
424// Used by On(Voice|Video)Channel(Created|Destroyed)
425template <class SENDER,
426 class RECEIVER,
427 class CHANNEL,
428 class SENDERS,
429 class RECEIVERS>
430void SetChannelOnSendersAndReceivers(CHANNEL* channel,
431 SENDERS& senders,
432 RECEIVERS& receivers,
433 cricket::MediaType media_type) {
434 for (auto& sender : senders) {
435 if (sender->media_type() == media_type) {
436 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
437 }
438 }
439 for (auto& receiver : receivers) {
440 if (receiver->media_type() == media_type) {
441 if (!channel) {
442 receiver->internal()->Stop();
443 }
444 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
445 }
446 }
447}
448
deadbeef293e9262017-01-11 12:28:30 -0800449// Helper to set an error and return from a method.
450bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
451 if (error) {
452 error->set_type(type);
453 }
454 return type == webrtc::RTCErrorType::NONE;
455}
456
deadbeef0a6c4ca2015-10-06 11:38:28 -0700457} // namespace
458
459namespace webrtc {
460
deadbeef293e9262017-01-11 12:28:30 -0800461bool PeerConnectionInterface::RTCConfiguration::operator==(
462 const PeerConnectionInterface::RTCConfiguration& o) const {
463 // This static_assert prevents us from accidentally breaking operator==.
464 struct stuff_being_tested_for_equality {
465 IceTransportsType type;
466 IceServers servers;
467 BundlePolicy bundle_policy;
468 RtcpMuxPolicy rtcp_mux_policy;
469 TcpCandidatePolicy tcp_candidate_policy;
470 CandidateNetworkPolicy candidate_network_policy;
471 int audio_jitter_buffer_max_packets;
472 bool audio_jitter_buffer_fast_accelerate;
473 int ice_connection_receiving_timeout;
474 int ice_backup_candidate_pair_ping_interval;
475 ContinualGatheringPolicy continual_gathering_policy;
476 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
477 bool prioritize_most_likely_ice_candidate_pairs;
478 struct cricket::MediaConfig media_config;
479 bool disable_ipv6;
zhihuangb09b3f92017-03-07 14:40:51 -0800480 bool disable_ipv6_on_wifi;
deadbeef293e9262017-01-11 12:28:30 -0800481 bool enable_rtp_data_channel;
482 bool enable_quic;
483 rtc::Optional<int> screencast_min_bitrate;
484 rtc::Optional<bool> combined_audio_video_bwe;
485 rtc::Optional<bool> enable_dtls_srtp;
486 int ice_candidate_pool_size;
487 bool prune_turn_ports;
488 bool presume_writable_when_fully_relayed;
489 bool enable_ice_renomination;
490 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800491 rtc::Optional<int> ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800492 };
493 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
494 "Did you add something to RTCConfiguration and forget to "
495 "update operator==?");
496 return type == o.type && servers == o.servers &&
497 bundle_policy == o.bundle_policy &&
498 rtcp_mux_policy == o.rtcp_mux_policy &&
499 tcp_candidate_policy == o.tcp_candidate_policy &&
500 candidate_network_policy == o.candidate_network_policy &&
501 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
502 audio_jitter_buffer_fast_accelerate ==
503 o.audio_jitter_buffer_fast_accelerate &&
504 ice_connection_receiving_timeout ==
505 o.ice_connection_receiving_timeout &&
506 ice_backup_candidate_pair_ping_interval ==
507 o.ice_backup_candidate_pair_ping_interval &&
508 continual_gathering_policy == o.continual_gathering_policy &&
509 certificates == o.certificates &&
510 prioritize_most_likely_ice_candidate_pairs ==
511 o.prioritize_most_likely_ice_candidate_pairs &&
512 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800513 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeef293e9262017-01-11 12:28:30 -0800514 enable_rtp_data_channel == o.enable_rtp_data_channel &&
515 enable_quic == o.enable_quic &&
516 screencast_min_bitrate == o.screencast_min_bitrate &&
517 combined_audio_video_bwe == o.combined_audio_video_bwe &&
518 enable_dtls_srtp == o.enable_dtls_srtp &&
519 ice_candidate_pool_size == o.ice_candidate_pool_size &&
520 prune_turn_ports == o.prune_turn_ports &&
521 presume_writable_when_fully_relayed ==
522 o.presume_writable_when_fully_relayed &&
523 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800524 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
525 ice_check_min_interval == o.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800526}
527
528bool PeerConnectionInterface::RTCConfiguration::operator!=(
529 const PeerConnectionInterface::RTCConfiguration& o) const {
530 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800531}
532
zhihuang8f65cdf2016-05-06 18:40:30 -0700533// Generate a RTCP CNAME when a PeerConnection is created.
534std::string GenerateRtcpCname() {
535 std::string cname;
536 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
537 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800538 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700539 }
540 return cname;
541}
542
htaa2a49d92016-03-04 02:51:39 -0800543bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700544 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800545 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700546 cricket::MediaSessionOptions* session_options) {
547 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
548 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
549 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
550 return false;
551 }
552
htaaac2dea2016-03-10 13:35:55 -0800553 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700554 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700555 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800556 } else {
557 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700558 }
htaaac2dea2016-03-10 13:35:55 -0800559 // For offers, we only offer video if we have it or it's forced by options.
560 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700561 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700562 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800563 } else if (is_offer) {
564 session_options->recv_video = false;
565 } else {
566 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700567 }
568
569 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700570 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800571 for (auto& kv : session_options->transport_options) {
572 kv.second.ice_restart = rtc_options.ice_restart;
573 }
deadbeefab9b2d12015-10-14 11:33:11 -0700574
575 return true;
576}
577
578bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
579 cricket::MediaSessionOptions* session_options) {
580 bool value = false;
581 size_t mandatory_constraints_satisfied = 0;
582
583 // kOfferToReceiveAudio defaults to true according to spec.
584 if (!FindConstraint(constraints,
585 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
586 &mandatory_constraints_satisfied) ||
587 value) {
588 session_options->recv_audio = true;
589 }
590
591 // kOfferToReceiveVideo defaults to false according to spec. But
592 // if it is an answer and video is offered, we should still accept video
593 // per default.
594 value = false;
595 if (!FindConstraint(constraints,
596 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
597 &mandatory_constraints_satisfied) ||
598 value) {
599 session_options->recv_video = true;
600 }
601
602 if (FindConstraint(constraints,
603 MediaConstraintsInterface::kVoiceActivityDetection, &value,
604 &mandatory_constraints_satisfied)) {
605 session_options->vad_enabled = value;
606 }
607
608 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
609 &mandatory_constraints_satisfied)) {
610 session_options->bundle_enabled = value;
611 } else {
612 // kUseRtpMux defaults to true according to spec.
613 session_options->bundle_enabled = true;
614 }
deadbeefab9b2d12015-10-14 11:33:11 -0700615
deadbeef0ed85b22016-02-23 17:24:52 -0800616 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700617 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
618 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700619 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800620 ice_restart = true;
621 }
622 for (auto& kv : session_options->transport_options) {
623 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700624 }
625
626 if (!constraints) {
627 return true;
628 }
629 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
630}
631
deadbeef293e9262017-01-11 12:28:30 -0800632RTCErrorType ParseIceServers(
633 const PeerConnectionInterface::IceServers& servers,
634 cricket::ServerAddresses* stun_servers,
635 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200636 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
637 if (!server.urls.empty()) {
638 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200639 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700640 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800641 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200642 }
deadbeef293e9262017-01-11 12:28:30 -0800643 RTCErrorType err =
644 ParseIceServerUrl(server, url, stun_servers, turn_servers);
645 if (err != RTCErrorType::NONE) {
646 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200647 }
648 }
649 } else if (!server.uri.empty()) {
650 // Fallback to old .uri if new .urls isn't present.
deadbeef293e9262017-01-11 12:28:30 -0800651 RTCErrorType err =
652 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
653 if (err != RTCErrorType::NONE) {
654 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200655 }
656 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700657 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800658 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659 }
660 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800661 // Candidates must have unique priorities, so that connectivity checks
662 // are performed in a well-defined order.
663 int priority = static_cast<int>(turn_servers->size() - 1);
664 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
665 // First in the list gets highest priority.
666 turn_server.priority = priority--;
667 }
deadbeef293e9262017-01-11 12:28:30 -0800668 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669}
670
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671PeerConnection::PeerConnection(PeerConnectionFactory* factory)
672 : factory_(factory),
673 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000674 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700677 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800678 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700679 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700680 local_streams_(StreamCollection::Create()),
681 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682
683PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100684 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700685 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700686 // Need to detach RTP senders/receivers from WebRtcSession,
687 // since it's about to be destroyed.
688 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700689 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700690 }
691 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700692 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700693 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700694 // Destroy stats_ because it depends on session_.
695 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800696 if (stats_collector_) {
697 stats_collector_->WaitForPendingRequest();
698 stats_collector_ = nullptr;
699 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700700 // Now destroy session_ before destroying other members,
701 // because its destruction fires signals (such as VoiceChannelDestroyed)
702 // which will trigger some final actions in PeerConnection...
703 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700704 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700705 network_thread()->Invoke<void>(RTC_FROM_HERE,
706 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707}
708
709bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000710 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700711 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200712 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800713 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100714 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800715 if (!allocator) {
716 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
717 << "This shouldn't happen if using PeerConnectionFactory.";
718 return false;
719 }
deadbeef653b8e02015-11-11 12:55:10 -0800720 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800721 // TODO(deadbeef): Why do we do this?
722 LOG(LS_ERROR) << "PeerConnection initialized without a "
723 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800724 return false;
725 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000726 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800727 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800728
deadbeef91dd5672016-05-18 16:55:30 -0700729 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700730 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700731 if (!network_thread()->Invoke<bool>(
732 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
733 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734 return false;
735 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736
skvlad11a9cbf2016-10-07 11:53:05 -0700737 media_controller_.reset(factory_->CreateMediaController(
738 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000739
zhihuang29ff8442016-07-27 11:07:25 -0700740 session_.reset(new WebRtcSession(
741 media_controller_.get(), factory_->network_thread(),
742 factory_->worker_thread(), factory_->signaling_thread(),
743 port_allocator_.get(),
744 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700745 factory_->CreateTransportController(
746 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800747 configuration.redetermine_role_on_ice_restart)),
748#ifdef HAVE_SCTP
749 std::unique_ptr<cricket::SctpTransportInternalFactory>(
750 new cricket::SctpTransportFactory(factory_->network_thread()))
751#else
752 nullptr
753#endif
754 ));
zhihuang29ff8442016-07-27 11:07:25 -0700755
deadbeefab9b2d12015-10-14 11:33:11 -0700756 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700757 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758
759 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200760 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800761 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700763 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765 // Register PeerConnection as receiver of local ice candidates.
766 // All the callbacks will be posted to the application from PeerConnection.
767 session_->RegisterIceObserver(this);
768 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700769 session_->SignalVoiceChannelCreated.connect(
770 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700771 session_->SignalVoiceChannelDestroyed.connect(
772 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700773 session_->SignalVideoChannelCreated.connect(
774 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700775 session_->SignalVideoChannelDestroyed.connect(
776 this, &PeerConnection::OnVideoChannelDestroyed);
777 session_->SignalDataChannelCreated.connect(
778 this, &PeerConnection::OnDataChannelCreated);
779 session_->SignalDataChannelDestroyed.connect(
780 this, &PeerConnection::OnDataChannelDestroyed);
781 session_->SignalDataChannelOpenMessage.connect(
782 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800783
784 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785 return true;
786}
787
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000788rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000789PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700790 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000791}
792
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000793rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700795 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796}
797
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000798bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100799 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800 if (IsClosed()) {
801 return false;
802 }
deadbeefab9b2d12015-10-14 11:33:11 -0700803 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 return false;
805 }
deadbeefab9b2d12015-10-14 11:33:11 -0700806
807 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800808 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
809 observer->SignalAudioTrackAdded.connect(this,
810 &PeerConnection::OnAudioTrackAdded);
811 observer->SignalAudioTrackRemoved.connect(
812 this, &PeerConnection::OnAudioTrackRemoved);
813 observer->SignalVideoTrackAdded.connect(this,
814 &PeerConnection::OnVideoTrackAdded);
815 observer->SignalVideoTrackRemoved.connect(
816 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700817 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700818
deadbeefab9b2d12015-10-14 11:33:11 -0700819 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800820 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700821 }
822 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800823 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700824 }
825
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000826 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 observer_->OnRenegotiationNeeded();
828 return true;
829}
830
831void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100832 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700833 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800834 OnAudioTrackRemoved(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 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700838 }
839
840 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800841 stream_observers_.erase(
842 std::remove_if(
843 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700844 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800845 return observer->stream()->label().compare(local_stream->label()) ==
846 0;
847 }),
848 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700849
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 if (IsClosed()) {
851 return;
852 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853 observer_->OnRenegotiationNeeded();
854}
855
deadbeefe1f9d832016-01-14 15:35:42 -0800856rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
857 MediaStreamTrackInterface* track,
858 std::vector<MediaStreamInterface*> streams) {
859 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
860 if (IsClosed()) {
861 return nullptr;
862 }
863 if (streams.size() >= 2) {
864 LOG(LS_ERROR)
865 << "Adding a track with two streams is not currently supported.";
866 return nullptr;
867 }
868 // TODO(deadbeef): Support adding a track to two different senders.
869 if (FindSenderForTrack(track) != senders_.end()) {
870 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
871 return nullptr;
872 }
873
874 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700875 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800876 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700877 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800878 signaling_thread(),
879 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700880 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800881 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700882 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800883 }
884 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700885 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800886 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700887 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800888 }
889 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700890 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800891 signaling_thread(),
892 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700893 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800894 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700895 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800896 }
897 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700898 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800899 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700900 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800901 }
902 } else {
903 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
904 return rtc::scoped_refptr<RtpSenderInterface>();
905 }
906
907 senders_.push_back(new_sender);
908 observer_->OnRenegotiationNeeded();
909 return new_sender;
910}
911
912bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
913 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
914 if (IsClosed()) {
915 return false;
916 }
917
918 auto it = std::find(senders_.begin(), senders_.end(), sender);
919 if (it == senders_.end()) {
920 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
921 return false;
922 }
deadbeefa601f5c2016-06-06 14:27:39 -0700923 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800924 senders_.erase(it);
925
926 observer_->OnRenegotiationNeeded();
927 return true;
928}
929
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000930rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100932 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700933 if (IsClosed()) {
934 return nullptr;
935 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936 if (!track) {
937 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800938 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939 }
deadbeef20cb0c12017-02-01 20:27:00 -0800940 auto it = FindSenderForTrack(track);
941 if (it == senders_.end()) {
942 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
943 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944 }
945
deadbeef20cb0c12017-02-01 20:27:00 -0800946 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947}
948
deadbeeffac06552015-11-25 11:26:01 -0800949rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800950 const std::string& kind,
951 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100952 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700953 if (IsClosed()) {
954 return nullptr;
955 }
deadbeefa601f5c2016-06-06 14:27:39 -0700956 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800957 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700958 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700959 signaling_thread(),
960 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800961 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700962 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700963 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800964 } else {
965 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800966 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800967 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800968 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700969 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800970 }
deadbeeffac06552015-11-25 11:26:01 -0800971 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800972 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800973}
974
deadbeef70ab1a12015-09-28 16:53:55 -0700975std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
976 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700977 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
978 for (const auto& sender : senders_) {
979 ret.push_back(sender.get());
980 }
981 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700982}
983
984std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
985PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700986 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
987 for (const auto& receiver : receivers_) {
988 ret.push_back(receiver.get());
989 }
990 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700991}
992
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000994 MediaStreamTrackInterface* track,
995 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100996 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700997 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800998 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1000 return false;
1001 }
1002
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001003 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001004 // The StatsCollector is used to tell if a track is valid because it may
1005 // remember tracks that the PeerConnection previously removed.
1006 if (track && !stats_->IsValidTrack(track->id())) {
1007 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1008 << track->id();
1009 return false;
1010 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001011 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001012 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 return true;
1014}
1015
hbos74e1a4f2016-09-15 23:33:01 -07001016void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1017 RTC_DCHECK(stats_collector_);
1018 stats_collector_->GetStatsReport(callback);
1019}
1020
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1022 return signaling_state_;
1023}
1024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025PeerConnectionInterface::IceConnectionState
1026PeerConnection::ice_connection_state() {
1027 return ice_connection_state_;
1028}
1029
1030PeerConnectionInterface::IceGatheringState
1031PeerConnection::ice_gathering_state() {
1032 return ice_gathering_state_;
1033}
1034
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001035rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036PeerConnection::CreateDataChannel(
1037 const std::string& label,
1038 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001039 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001040#ifdef HAVE_QUIC
1041 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1042 // TODO(zhihuang): Handle case when config is NULL.
1043 if (!config) {
1044 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1045 return nullptr;
1046 }
1047 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1048 if (!config->reliable || config->ordered) {
1049 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1050 "ordered delivery.";
1051 return nullptr;
1052 }
1053 return session_->quic_data_transport()->CreateDataChannel(label, config);
1054 }
1055#endif // HAVE_QUIC
1056
deadbeefab9b2d12015-10-14 11:33:11 -07001057 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001058
kwibergd1fe2812016-04-27 06:47:29 -07001059 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001060 if (config) {
1061 internal_config.reset(new InternalDataChannelInit(*config));
1062 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001063 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001064 InternalCreateDataChannel(label, internal_config.get()));
1065 if (!channel.get()) {
1066 return nullptr;
1067 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001069 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1070 // the first SCTP DataChannel.
1071 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1072 observer_->OnRenegotiationNeeded();
1073 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001074
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 return DataChannelProxy::Create(signaling_thread(), channel.get());
1076}
1077
1078void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1079 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001080 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001081 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1083 return;
1084 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001085 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001086
1087 bool value;
1088 size_t mandatory_constraints = 0;
1089
1090 if (FindConstraint(constraints,
1091 MediaConstraintsInterface::kOfferToReceiveAudio,
1092 &value,
1093 &mandatory_constraints)) {
1094 options.offer_to_receive_audio =
1095 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1096 }
1097
1098 if (FindConstraint(constraints,
1099 MediaConstraintsInterface::kOfferToReceiveVideo,
1100 &value,
1101 &mandatory_constraints)) {
1102 options.offer_to_receive_video =
1103 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1104 }
1105
1106 if (FindConstraint(constraints,
1107 MediaConstraintsInterface::kVoiceActivityDetection,
1108 &value,
1109 &mandatory_constraints)) {
1110 options.voice_activity_detection = value;
1111 }
1112
1113 if (FindConstraint(constraints,
1114 MediaConstraintsInterface::kIceRestart,
1115 &value,
1116 &mandatory_constraints)) {
1117 options.ice_restart = value;
1118 }
1119
1120 if (FindConstraint(constraints,
1121 MediaConstraintsInterface::kUseRtpMux,
1122 &value,
1123 &mandatory_constraints)) {
1124 options.use_rtp_mux = value;
1125 }
1126
1127 CreateOffer(observer, options);
1128}
1129
1130void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1131 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001132 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001133 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001134 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1135 return;
1136 }
deadbeefab9b2d12015-10-14 11:33:11 -07001137
1138 cricket::MediaSessionOptions session_options;
1139 if (!GetOptionsForOffer(options, &session_options)) {
1140 std::string error = "CreateOffer called with invalid options.";
1141 LOG(LS_ERROR) << error;
1142 PostCreateSessionDescriptionFailure(observer, error);
1143 return;
1144 }
1145
1146 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147}
1148
1149void PeerConnection::CreateAnswer(
1150 CreateSessionDescriptionObserver* observer,
1151 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001152 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001153 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1155 return;
1156 }
deadbeefab9b2d12015-10-14 11:33:11 -07001157
1158 cricket::MediaSessionOptions session_options;
1159 if (!GetOptionsForAnswer(constraints, &session_options)) {
1160 std::string error = "CreateAnswer called with invalid constraints.";
1161 LOG(LS_ERROR) << error;
1162 PostCreateSessionDescriptionFailure(observer, error);
1163 return;
1164 }
1165
htaa2a49d92016-03-04 02:51:39 -08001166 session_->CreateAnswer(observer, session_options);
1167}
1168
1169void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1170 const RTCOfferAnswerOptions& options) {
1171 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001172 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -08001173 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1174 return;
1175 }
1176
1177 cricket::MediaSessionOptions session_options;
1178 if (!GetOptionsForAnswer(options, &session_options)) {
1179 std::string error = "CreateAnswer called with invalid options.";
1180 LOG(LS_ERROR) << error;
1181 PostCreateSessionDescriptionFailure(observer, error);
1182 return;
1183 }
1184
1185 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186}
1187
1188void PeerConnection::SetLocalDescription(
1189 SetSessionDescriptionObserver* observer,
1190 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001191 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001192 if (IsClosed()) {
1193 return;
1194 }
nisse7ce109a2017-01-31 00:57:56 -08001195 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001196 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1197 return;
1198 }
1199 if (!desc) {
1200 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1201 return;
1202 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203 // Update stats here so that we have the most recent stats for tracks and
1204 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001205 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 std::string error;
1207 if (!session_->SetLocalDescription(desc, &error)) {
1208 PostSetSessionDescriptionFailure(observer, error);
1209 return;
1210 }
deadbeefab9b2d12015-10-14 11:33:11 -07001211
1212 // If setting the description decided our SSL role, allocate any necessary
1213 // SCTP sids.
1214 rtc::SSLRole role;
1215 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001216 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001217 AllocateSctpSids(role);
1218 }
1219
1220 // Update state and SSRC of local MediaStreams and DataChannels based on the
1221 // local session description.
1222 const cricket::ContentInfo* audio_content =
1223 GetFirstAudioContent(desc->description());
1224 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001225 if (audio_content->rejected) {
1226 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1227 } else {
1228 const cricket::AudioContentDescription* audio_desc =
1229 static_cast<const cricket::AudioContentDescription*>(
1230 audio_content->description);
1231 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1232 }
deadbeefab9b2d12015-10-14 11:33:11 -07001233 }
1234
1235 const cricket::ContentInfo* video_content =
1236 GetFirstVideoContent(desc->description());
1237 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001238 if (video_content->rejected) {
1239 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1240 } else {
1241 const cricket::VideoContentDescription* video_desc =
1242 static_cast<const cricket::VideoContentDescription*>(
1243 video_content->description);
1244 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1245 }
deadbeefab9b2d12015-10-14 11:33:11 -07001246 }
1247
1248 const cricket::ContentInfo* data_content =
1249 GetFirstDataContent(desc->description());
1250 if (data_content) {
1251 const cricket::DataContentDescription* data_desc =
1252 static_cast<const cricket::DataContentDescription*>(
1253 data_content->description);
1254 if (rtc::starts_with(data_desc->protocol().data(),
1255 cricket::kMediaProtocolRtpPrefix)) {
1256 UpdateLocalRtpDataChannels(data_desc->streams());
1257 }
1258 }
1259
1260 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001261 signaling_thread()->Post(RTC_FROM_HERE, this,
1262 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001263
deadbeefcbecd352015-09-23 11:50:27 -07001264 // MaybeStartGathering needs to be called after posting
1265 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1266 // before signaling that SetLocalDescription completed.
1267 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268}
1269
1270void PeerConnection::SetRemoteDescription(
1271 SetSessionDescriptionObserver* observer,
1272 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001273 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001274 if (IsClosed()) {
1275 return;
1276 }
nisse7ce109a2017-01-31 00:57:56 -08001277 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1279 return;
1280 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281 if (!desc) {
1282 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1283 return;
1284 }
1285 // Update stats here so that we have the most recent stats for tracks and
1286 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001287 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288 std::string error;
1289 if (!session_->SetRemoteDescription(desc, &error)) {
1290 PostSetSessionDescriptionFailure(observer, error);
1291 return;
1292 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293
deadbeefab9b2d12015-10-14 11:33:11 -07001294 // If setting the description decided our SSL role, allocate any necessary
1295 // SCTP sids.
1296 rtc::SSLRole role;
1297 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001298 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001299 AllocateSctpSids(role);
1300 }
1301
1302 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001303 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1304 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1305 const cricket::AudioContentDescription* audio_desc =
1306 GetFirstAudioContentDescription(remote_desc);
1307 const cricket::VideoContentDescription* video_desc =
1308 GetFirstVideoContentDescription(remote_desc);
1309 const cricket::DataContentDescription* data_desc =
1310 GetFirstDataContentDescription(remote_desc);
1311
1312 // Check if the descriptions include streams, just in case the peer supports
1313 // MSID, but doesn't indicate so with "a=msid-semantic".
1314 if (remote_desc->msid_supported() ||
1315 (audio_desc && !audio_desc->streams().empty()) ||
1316 (video_desc && !video_desc->streams().empty())) {
1317 remote_peer_supports_msid_ = true;
1318 }
deadbeefab9b2d12015-10-14 11:33:11 -07001319
1320 // We wait to signal new streams until we finish processing the description,
1321 // since only at that point will new streams have all their tracks.
1322 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1323
1324 // Find all audio rtp streams and create corresponding remote AudioTracks
1325 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001326 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001327 if (audio_content->rejected) {
1328 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1329 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001330 bool default_audio_track_needed =
1331 !remote_peer_supports_msid_ &&
1332 MediaContentDirectionHasSend(audio_desc->direction());
1333 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1334 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001335 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001336 }
deadbeefab9b2d12015-10-14 11:33:11 -07001337 }
1338
1339 // Find all video rtp streams and create corresponding remote VideoTracks
1340 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001341 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001342 if (video_content->rejected) {
1343 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1344 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001345 bool default_video_track_needed =
1346 !remote_peer_supports_msid_ &&
1347 MediaContentDirectionHasSend(video_desc->direction());
1348 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1349 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001350 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001351 }
deadbeefab9b2d12015-10-14 11:33:11 -07001352 }
1353
1354 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001355 if (data_desc) {
1356 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001357 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001358 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001359 }
1360 }
1361
1362 // Iterate new_streams and notify the observer about new MediaStreams.
1363 for (size_t i = 0; i < new_streams->count(); ++i) {
1364 MediaStreamInterface* new_stream = new_streams->at(i);
1365 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001366 // Call both the raw pointer and scoped_refptr versions of the method
1367 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001368 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001369 observer_->OnAddStream(
1370 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001371 }
1372
deadbeefbda7e0b2015-12-08 17:13:40 -08001373 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001374
1375 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001376 signaling_thread()->Post(RTC_FROM_HERE, this,
1377 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001378}
1379
deadbeef46c73892016-11-16 19:42:04 -08001380PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1381 return configuration_;
1382}
1383
deadbeef293e9262017-01-11 12:28:30 -08001384bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1385 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001386 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001387
1388 if (session_->local_description() &&
1389 configuration.ice_candidate_pool_size !=
1390 configuration_.ice_candidate_pool_size) {
1391 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1392 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001393 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001394 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001395
deadbeef293e9262017-01-11 12:28:30 -08001396 // The simplest (and most future-compatible) way to tell if the config was
1397 // modified in an invalid way is to copy each property we do support
1398 // modifying, then use operator==. There are far more properties we don't
1399 // support modifying than those we do, and more could be added.
1400 RTCConfiguration modified_config = configuration_;
1401 modified_config.servers = configuration.servers;
1402 modified_config.type = configuration.type;
1403 modified_config.ice_candidate_pool_size =
1404 configuration.ice_candidate_pool_size;
1405 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001406 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001407 if (configuration != modified_config) {
1408 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1409 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1410 }
1411
1412 // Note that this isn't possible through chromium, since it's an unsigned
1413 // short in WebIDL.
1414 if (configuration.ice_candidate_pool_size < 0 ||
1415 configuration.ice_candidate_pool_size > UINT16_MAX) {
1416 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1417 }
1418
1419 // Parse ICE servers before hopping to network thread.
1420 cricket::ServerAddresses stun_servers;
1421 std::vector<cricket::RelayServerConfig> turn_servers;
1422 RTCErrorType parse_error =
1423 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1424 if (parse_error != RTCErrorType::NONE) {
1425 return SafeSetError(parse_error, error);
1426 }
1427
1428 // In theory this shouldn't fail.
1429 if (!network_thread()->Invoke<bool>(
1430 RTC_FROM_HERE,
1431 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1432 stun_servers, turn_servers, modified_config.type,
1433 modified_config.ice_candidate_pool_size,
1434 modified_config.prune_turn_ports))) {
1435 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1436 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1437 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001438
deadbeefd1a38b52016-12-10 13:15:33 -08001439 // As described in JSEP, calling setConfiguration with new ICE servers or
1440 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1441 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001442 if (modified_config.servers != configuration_.servers ||
1443 modified_config.type != configuration_.type ||
1444 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001445 session_->SetNeedsIceRestartFlag();
1446 }
skvladd1f5fda2017-02-03 16:54:05 -08001447
1448 if (modified_config.ice_check_min_interval !=
1449 configuration_.ice_check_min_interval) {
1450 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1451 }
1452
deadbeef293e9262017-01-11 12:28:30 -08001453 configuration_ = modified_config;
1454 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001455}
1456
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457bool PeerConnection::AddIceCandidate(
1458 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001459 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001460 if (IsClosed()) {
1461 return false;
1462 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 return session_->ProcessIceMessage(ice_candidate);
1464}
1465
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001466bool PeerConnection::RemoveIceCandidates(
1467 const std::vector<cricket::Candidate>& candidates) {
1468 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1469 return session_->RemoveRemoteIceCandidates(candidates);
1470}
1471
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001472void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001473 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001474 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001475
1476 if (session_) {
1477 session_->set_metrics_observer(uma_observer_);
1478 }
1479
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001480 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001481 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001482 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001483 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001484 uma_observer_->IncrementEnumCounter(
1485 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1486 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001487 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001488 uma_observer_->IncrementEnumCounter(
1489 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1490 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001491 }
1492 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001493}
1494
ivoc14d5dbe2016-07-04 07:06:55 -07001495bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1496 int64_t max_size_bytes) {
1497 return factory_->worker_thread()->Invoke<bool>(
1498 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1499 max_size_bytes));
1500}
1501
1502void PeerConnection::StopRtcEventLog() {
1503 factory_->worker_thread()->Invoke<void>(
1504 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1505}
1506
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507const SessionDescriptionInterface* PeerConnection::local_description() const {
1508 return session_->local_description();
1509}
1510
1511const SessionDescriptionInterface* PeerConnection::remote_description() const {
1512 return session_->remote_description();
1513}
1514
deadbeeffe4a8a42016-12-20 17:56:17 -08001515const SessionDescriptionInterface* PeerConnection::current_local_description()
1516 const {
1517 return session_->current_local_description();
1518}
1519
1520const SessionDescriptionInterface* PeerConnection::current_remote_description()
1521 const {
1522 return session_->current_remote_description();
1523}
1524
1525const SessionDescriptionInterface* PeerConnection::pending_local_description()
1526 const {
1527 return session_->pending_local_description();
1528}
1529
1530const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1531 const {
1532 return session_->pending_remote_description();
1533}
1534
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001536 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537 // Update stats here so that we have the most recent stats for tracks and
1538 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001539 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540
deadbeefd59daf82015-10-14 15:02:44 -07001541 session_->Close();
zhihuang77985012017-02-07 15:45:16 -08001542 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001543}
1544
deadbeefd59daf82015-10-14 15:02:44 -07001545void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1546 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001548 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001550 break;
deadbeefd59daf82015-10-14 15:02:44 -07001551 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001552 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1553 break;
deadbeefd59daf82015-10-14 15:02:44 -07001554 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001555 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1556 break;
deadbeefd59daf82015-10-14 15:02:44 -07001557 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1559 break;
deadbeefd59daf82015-10-14 15:02:44 -07001560 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1562 break;
deadbeefd59daf82015-10-14 15:02:44 -07001563 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001564 ChangeSignalingState(PeerConnectionInterface::kStable);
1565 break;
deadbeefd59daf82015-10-14 15:02:44 -07001566 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567 ChangeSignalingState(PeerConnectionInterface::kClosed);
1568 break;
1569 default:
1570 break;
1571 }
1572}
1573
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001574void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001575 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1577 SetSessionDescriptionMsg* param =
1578 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1579 param->observer->OnSuccess();
1580 delete param;
1581 break;
1582 }
1583 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1584 SetSessionDescriptionMsg* param =
1585 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1586 param->observer->OnFailure(param->error);
1587 delete param;
1588 break;
1589 }
deadbeefab9b2d12015-10-14 11:33:11 -07001590 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1591 CreateSessionDescriptionMsg* param =
1592 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1593 param->observer->OnFailure(param->error);
1594 delete param;
1595 break;
1596 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001597 case MSG_GETSTATS: {
1598 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001599 StatsReports reports;
1600 stats_->GetStats(param->track, &reports);
1601 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001602 delete param;
1603 break;
1604 }
deadbeefbd292462015-12-14 18:15:29 -08001605 case MSG_FREE_DATACHANNELS: {
1606 sctp_data_channels_to_free_.clear();
1607 break;
1608 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001609 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001610 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001611 break;
1612 }
1613}
1614
deadbeefab9b2d12015-10-14 11:33:11 -07001615void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001616 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001617 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001618 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1619 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001620 signaling_thread(),
1621 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1622 stream->AddTrack(
1623 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001624 receivers_.push_back(receiver);
1625 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1626 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1627 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001628}
1629
deadbeefab9b2d12015-10-14 11:33:11 -07001630void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001631 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001632 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001633 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1634 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001635 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001636 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1637 session_->video_channel()));
1638 stream->AddTrack(
1639 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001640 receivers_.push_back(receiver);
1641 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1642 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1643 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001644}
1645
deadbeef70ab1a12015-09-28 16:53:55 -07001646// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1647// description.
perkjd61bf802016-03-24 03:16:19 -07001648void PeerConnection::DestroyReceiver(const std::string& track_id) {
1649 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001650 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001651 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001652 << " doesn't exist.";
1653 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001654 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001655 receivers_.erase(it);
1656 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657}
1658
zstein6dfd53a2017-03-06 13:49:03 -08001659void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001660 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001661 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001662 // After transitioning to "closed", ignore any additional states from
1663 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001664 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001665 return;
1666 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001667 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001668 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001669}
1670
1671void PeerConnection::OnIceGatheringChange(
1672 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001673 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674 if (IsClosed()) {
1675 return;
1676 }
1677 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001678 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001679}
1680
1681void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001682 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001683 if (IsClosed()) {
1684 return;
1685 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001686 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687}
1688
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001689void PeerConnection::OnIceCandidatesRemoved(
1690 const std::vector<cricket::Candidate>& candidates) {
1691 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001692 if (IsClosed()) {
1693 return;
1694 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001695 observer_->OnIceCandidatesRemoved(candidates);
1696}
1697
Peter Thatcher54360512015-07-08 11:08:35 -07001698void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001699 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001700 if (IsClosed()) {
1701 return;
1702 }
Peter Thatcher54360512015-07-08 11:08:35 -07001703 observer_->OnIceConnectionReceivingChange(receiving);
1704}
1705
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706void PeerConnection::ChangeSignalingState(
1707 PeerConnectionInterface::SignalingState signaling_state) {
1708 signaling_state_ = signaling_state;
1709 if (signaling_state == kClosed) {
1710 ice_connection_state_ = kIceConnectionClosed;
1711 observer_->OnIceConnectionChange(ice_connection_state_);
1712 if (ice_gathering_state_ != kIceGatheringComplete) {
1713 ice_gathering_state_ = kIceGatheringComplete;
1714 observer_->OnIceGatheringChange(ice_gathering_state_);
1715 }
1716 }
1717 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718}
1719
deadbeefeb459812015-12-15 19:24:43 -08001720void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1721 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001722 if (IsClosed()) {
1723 return;
1724 }
deadbeefeb459812015-12-15 19:24:43 -08001725 auto sender = FindSenderForTrack(track);
1726 if (sender != senders_.end()) {
1727 // We already have a sender for this track, so just change the stream_id
1728 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001729 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001730 return;
1731 }
1732
1733 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001734 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1735 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001736 signaling_thread(),
1737 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1738 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001739 senders_.push_back(new_sender);
1740 // If the sender has already been configured in SDP, we call SetSsrc,
1741 // which will connect the sender to the underlying transport. This can
1742 // occur if a local session description that contains the ID of the sender
1743 // is set before AddStream is called. It can also occur if the local
1744 // session description is not changed and RemoveStream is called, and
1745 // later AddStream is called again with the same stream.
1746 const TrackInfo* track_info =
1747 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1748 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001749 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001750 }
1751}
1752
1753// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1754// indefinitely, when we have unified plan SDP.
1755void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1756 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001757 if (IsClosed()) {
1758 return;
1759 }
deadbeefeb459812015-12-15 19:24:43 -08001760 auto sender = FindSenderForTrack(track);
1761 if (sender == senders_.end()) {
1762 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1763 << " doesn't exist.";
1764 return;
1765 }
deadbeefa601f5c2016-06-06 14:27:39 -07001766 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001767 senders_.erase(sender);
1768}
1769
1770void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1771 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001772 if (IsClosed()) {
1773 return;
1774 }
deadbeefeb459812015-12-15 19:24:43 -08001775 auto sender = FindSenderForTrack(track);
1776 if (sender != senders_.end()) {
1777 // We already have a sender for this track, so just change the stream_id
1778 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001779 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001780 return;
1781 }
1782
1783 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001784 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1785 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001786 signaling_thread(), new VideoRtpSender(track, stream->label(),
1787 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001788 senders_.push_back(new_sender);
1789 const TrackInfo* track_info =
1790 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1791 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001792 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001793 }
1794}
1795
1796void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1797 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001798 if (IsClosed()) {
1799 return;
1800 }
deadbeefeb459812015-12-15 19:24:43 -08001801 auto sender = FindSenderForTrack(track);
1802 if (sender == senders_.end()) {
1803 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1804 << " doesn't exist.";
1805 return;
1806 }
deadbeefa601f5c2016-06-06 14:27:39 -07001807 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001808 senders_.erase(sender);
1809}
1810
deadbeefab9b2d12015-10-14 11:33:11 -07001811void PeerConnection::PostSetSessionDescriptionFailure(
1812 SetSessionDescriptionObserver* observer,
1813 const std::string& error) {
1814 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1815 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001816 signaling_thread()->Post(RTC_FROM_HERE, this,
1817 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001818}
1819
1820void PeerConnection::PostCreateSessionDescriptionFailure(
1821 CreateSessionDescriptionObserver* observer,
1822 const std::string& error) {
1823 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1824 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001825 signaling_thread()->Post(RTC_FROM_HERE, this,
1826 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001827}
1828
1829bool PeerConnection::GetOptionsForOffer(
1830 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1831 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001832 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1833 // ContentInfos.
1834 if (session_->local_description()) {
1835 for (const cricket::ContentInfo& content :
1836 session_->local_description()->description()->contents()) {
1837 session_options->transport_options[content.name] =
1838 cricket::TransportOptions();
1839 }
1840 }
deadbeef46c73892016-11-16 19:42:04 -08001841 session_options->enable_ice_renomination =
1842 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001843
htaaac2dea2016-03-10 13:35:55 -08001844 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001845 return false;
1846 }
1847
deadbeeffac06552015-11-25 11:26:01 -08001848 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001849 // Offer to receive audio/video if the constraint is not set and there are
1850 // send streams, or we're currently receiving.
1851 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1852 session_options->recv_audio =
1853 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1854 !remote_audio_tracks_.empty();
1855 }
1856 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1857 session_options->recv_video =
1858 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1859 !remote_video_tracks_.empty();
1860 }
deadbeefc80741f2015-10-22 13:14:45 -07001861
zhihuang9763d562016-08-05 11:14:50 -07001862 // Intentionally unset the data channel type for RTP data channel with the
1863 // second condition. Otherwise the RTP data channels would be successfully
1864 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1865 // when building with chromium. We want to leave RTP data channels broken, so
1866 // people won't try to use them.
1867 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1868 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001869 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001870
zhihuangaf388472016-11-02 16:49:48 -07001871 session_options->bundle_enabled =
1872 session_options->bundle_enabled &&
1873 (session_options->has_audio() || session_options->has_video() ||
1874 session_options->has_data());
1875
zhihuang8f65cdf2016-05-06 18:40:30 -07001876 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001877 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001878 return true;
1879}
1880
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001881void PeerConnection::InitializeOptionsForAnswer(
1882 cricket::MediaSessionOptions* session_options) {
1883 session_options->recv_audio = false;
1884 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001885 session_options->enable_ice_renomination =
1886 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001887}
1888
htaa2a49d92016-03-04 02:51:39 -08001889void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001890 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001891 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1892 // ContentInfos.
1893 if (session_->remote_description()) {
1894 // Initialize the transport_options map.
1895 for (const cricket::ContentInfo& content :
1896 session_->remote_description()->description()->contents()) {
1897 session_options->transport_options[content.name] =
1898 cricket::TransportOptions();
1899 }
1900 }
deadbeeffac06552015-11-25 11:26:01 -08001901 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001902 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1903 // are not signaled in the SDP so does not go through that path and must be
1904 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001905 // Intentionally unset the data channel type for RTP data channel. Otherwise
1906 // the RTP data channels would be successfully negotiated by default and the
1907 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1908 // We want to leave RTP data channels broken, so people won't try to use them.
1909 if (session_->data_channel_type() != cricket::DCT_RTP) {
1910 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001911 }
zhihuangaf388472016-11-02 16:49:48 -07001912 session_options->bundle_enabled =
1913 session_options->bundle_enabled &&
1914 (session_options->has_audio() || session_options->has_video() ||
1915 session_options->has_data());
1916
jbauchcb560652016-08-04 05:20:32 -07001917 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001918}
1919
1920bool PeerConnection::GetOptionsForAnswer(
1921 const MediaConstraintsInterface* constraints,
1922 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001923 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001924 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1925 return false;
1926 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001927 session_options->rtcp_cname = rtcp_cname_;
1928
htaa2a49d92016-03-04 02:51:39 -08001929 FinishOptionsForAnswer(session_options);
1930 return true;
1931}
1932
1933bool PeerConnection::GetOptionsForAnswer(
1934 const RTCOfferAnswerOptions& options,
1935 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001936 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001937 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001938 return false;
1939 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001940 session_options->rtcp_cname = rtcp_cname_;
1941
htaa2a49d92016-03-04 02:51:39 -08001942 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001943 return true;
1944}
1945
deadbeeffaac4972015-11-12 15:33:07 -08001946void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1947 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001948 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1949 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001950}
1951
deadbeefab9b2d12015-10-14 11:33:11 -07001952void PeerConnection::UpdateRemoteStreamsList(
1953 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001954 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001955 cricket::MediaType media_type,
1956 StreamCollection* new_streams) {
1957 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1958
1959 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001960 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001961 auto track_it = current_tracks->begin();
1962 while (track_it != current_tracks->end()) {
1963 const TrackInfo& info = *track_it;
1964 const cricket::StreamParams* params =
1965 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001966 bool track_exists = params && params->id == info.track_id;
1967 // If this is a default track, and we still need it, don't remove it.
1968 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1969 track_exists) {
1970 ++track_it;
1971 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001972 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1973 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001974 }
1975 }
1976
1977 // Find new and active tracks.
1978 for (const cricket::StreamParams& params : streams) {
1979 // The sync_label is the MediaStream label and the |stream.id| is the
1980 // track id.
1981 const std::string& stream_label = params.sync_label;
1982 const std::string& track_id = params.id;
1983 uint32_t ssrc = params.first_ssrc();
1984
1985 rtc::scoped_refptr<MediaStreamInterface> stream =
1986 remote_streams_->find(stream_label);
1987 if (!stream) {
1988 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001989 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1990 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001991 remote_streams_->AddStream(stream);
1992 new_streams->AddStream(stream);
1993 }
1994
1995 const TrackInfo* track_info =
1996 FindTrackInfo(*current_tracks, stream_label, track_id);
1997 if (!track_info) {
1998 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1999 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2000 }
2001 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002002
2003 // Add default track if necessary.
2004 if (default_track_needed) {
2005 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2006 remote_streams_->find(kDefaultStreamLabel);
2007 if (!default_stream) {
2008 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002009 default_stream = MediaStreamProxy::Create(
2010 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002011 remote_streams_->AddStream(default_stream);
2012 new_streams->AddStream(default_stream);
2013 }
2014 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2015 ? kDefaultAudioTrackLabel
2016 : kDefaultVideoTrackLabel;
2017 const TrackInfo* default_track_info =
2018 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2019 if (!default_track_info) {
2020 current_tracks->push_back(
2021 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2022 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2023 }
2024 }
deadbeefab9b2d12015-10-14 11:33:11 -07002025}
2026
2027void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2028 const std::string& track_id,
2029 uint32_t ssrc,
2030 cricket::MediaType media_type) {
2031 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2032
2033 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002034 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002035 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002036 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002037 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002038 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002039 }
2040}
2041
2042void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2043 const std::string& track_id,
2044 cricket::MediaType media_type) {
2045 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2046
2047 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002048 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2049 // will be notified which will end the AudioRtpReceiver::track().
2050 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002051 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2052 stream->FindAudioTrack(track_id);
2053 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002054 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002055 }
2056 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002057 // Stopping or destroying a VideoRtpReceiver will end the
2058 // VideoRtpReceiver::track().
2059 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002060 rtc::scoped_refptr<VideoTrackInterface> video_track =
2061 stream->FindVideoTrack(track_id);
2062 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002063 // There's no guarantee the track is still available, e.g. the track may
2064 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002065 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002066 }
2067 } else {
nisseede5da42017-01-12 05:15:36 -08002068 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002069 }
2070}
2071
2072void PeerConnection::UpdateEndedRemoteMediaStreams() {
2073 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2074 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2075 MediaStreamInterface* stream = remote_streams_->at(i);
2076 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2077 streams_to_remove.push_back(stream);
2078 }
2079 }
2080
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002081 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002082 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002083 // Call both the raw pointer and scoped_refptr versions of the method
2084 // for compatibility.
2085 observer_->OnRemoveStream(stream.get());
2086 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002087 }
2088}
2089
deadbeefab9b2d12015-10-14 11:33:11 -07002090void PeerConnection::UpdateLocalTracks(
2091 const std::vector<cricket::StreamParams>& streams,
2092 cricket::MediaType media_type) {
2093 TrackInfos* current_tracks = GetLocalTracks(media_type);
2094
2095 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2096 // don't match the new StreamParam.
2097 TrackInfos::iterator track_it = current_tracks->begin();
2098 while (track_it != current_tracks->end()) {
2099 const TrackInfo& info = *track_it;
2100 const cricket::StreamParams* params =
2101 cricket::GetStreamBySsrc(streams, info.ssrc);
2102 if (!params || params->id != info.track_id ||
2103 params->sync_label != info.stream_label) {
2104 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2105 media_type);
2106 track_it = current_tracks->erase(track_it);
2107 } else {
2108 ++track_it;
2109 }
2110 }
2111
2112 // Find new and active tracks.
2113 for (const cricket::StreamParams& params : streams) {
2114 // The sync_label is the MediaStream label and the |stream.id| is the
2115 // track id.
2116 const std::string& stream_label = params.sync_label;
2117 const std::string& track_id = params.id;
2118 uint32_t ssrc = params.first_ssrc();
2119 const TrackInfo* track_info =
2120 FindTrackInfo(*current_tracks, stream_label, track_id);
2121 if (!track_info) {
2122 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2123 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2124 }
2125 }
2126}
2127
2128void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2129 const std::string& track_id,
2130 uint32_t ssrc,
2131 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002132 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002133 if (!sender) {
2134 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2135 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002136 return;
2137 }
2138
deadbeeffac06552015-11-25 11:26:01 -08002139 if (sender->media_type() != media_type) {
2140 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2141 << " description with an unexpected media type.";
2142 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002143 }
deadbeeffac06552015-11-25 11:26:01 -08002144
2145 sender->set_stream_id(stream_label);
2146 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002147}
2148
2149void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2150 const std::string& track_id,
2151 uint32_t ssrc,
2152 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002153 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002154 if (!sender) {
2155 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002156 // SessionDescriptions has been renegotiated.
2157 return;
2158 }
deadbeeffac06552015-11-25 11:26:01 -08002159
2160 // A sender has been removed from the SessionDescription but it's still
2161 // associated with the PeerConnection. This only occurs if the SDP doesn't
2162 // match with the calls to CreateSender, AddStream and RemoveStream.
2163 if (sender->media_type() != media_type) {
2164 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2165 << " description with an unexpected media type.";
2166 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002167 }
deadbeeffac06552015-11-25 11:26:01 -08002168
2169 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002170}
2171
2172void PeerConnection::UpdateLocalRtpDataChannels(
2173 const cricket::StreamParamsVec& streams) {
2174 std::vector<std::string> existing_channels;
2175
2176 // Find new and active data channels.
2177 for (const cricket::StreamParams& params : streams) {
2178 // |it->sync_label| is actually the data channel label. The reason is that
2179 // we use the same naming of data channels as we do for
2180 // MediaStreams and Tracks.
2181 // For MediaStreams, the sync_label is the MediaStream label and the
2182 // track label is the same as |streamid|.
2183 const std::string& channel_label = params.sync_label;
2184 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002185 if (data_channel_it == rtp_data_channels_.end()) {
2186 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002187 continue;
2188 }
2189 // Set the SSRC the data channel should use for sending.
2190 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2191 existing_channels.push_back(data_channel_it->first);
2192 }
2193
2194 UpdateClosingRtpDataChannels(existing_channels, true);
2195}
2196
2197void PeerConnection::UpdateRemoteRtpDataChannels(
2198 const cricket::StreamParamsVec& streams) {
2199 std::vector<std::string> existing_channels;
2200
2201 // Find new and active data channels.
2202 for (const cricket::StreamParams& params : streams) {
2203 // The data channel label is either the mslabel or the SSRC if the mslabel
2204 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2205 std::string label = params.sync_label.empty()
2206 ? rtc::ToString(params.first_ssrc())
2207 : params.sync_label;
2208 auto data_channel_it = rtp_data_channels_.find(label);
2209 if (data_channel_it == rtp_data_channels_.end()) {
2210 // This is a new data channel.
2211 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2212 } else {
2213 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2214 }
2215 existing_channels.push_back(label);
2216 }
2217
2218 UpdateClosingRtpDataChannels(existing_channels, false);
2219}
2220
2221void PeerConnection::UpdateClosingRtpDataChannels(
2222 const std::vector<std::string>& active_channels,
2223 bool is_local_update) {
2224 auto it = rtp_data_channels_.begin();
2225 while (it != rtp_data_channels_.end()) {
2226 DataChannel* data_channel = it->second;
2227 if (std::find(active_channels.begin(), active_channels.end(),
2228 data_channel->label()) != active_channels.end()) {
2229 ++it;
2230 continue;
2231 }
2232
2233 if (is_local_update) {
2234 data_channel->SetSendSsrc(0);
2235 } else {
2236 data_channel->RemotePeerRequestClose();
2237 }
2238
2239 if (data_channel->state() == DataChannel::kClosed) {
2240 rtp_data_channels_.erase(it);
2241 it = rtp_data_channels_.begin();
2242 } else {
2243 ++it;
2244 }
2245 }
2246}
2247
2248void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2249 uint32_t remote_ssrc) {
2250 rtc::scoped_refptr<DataChannel> channel(
2251 InternalCreateDataChannel(label, nullptr));
2252 if (!channel.get()) {
2253 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2254 << "CreateDataChannel failed.";
2255 return;
2256 }
2257 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002258 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2259 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002260 // Call both the raw pointer and scoped_refptr versions of the method
2261 // for compatibility.
2262 observer_->OnDataChannel(proxy_channel.get());
2263 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002264}
2265
2266rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2267 const std::string& label,
2268 const InternalDataChannelInit* config) {
2269 if (IsClosed()) {
2270 return nullptr;
2271 }
2272 if (session_->data_channel_type() == cricket::DCT_NONE) {
2273 LOG(LS_ERROR)
2274 << "InternalCreateDataChannel: Data is not supported in this call.";
2275 return nullptr;
2276 }
2277 InternalDataChannelInit new_config =
2278 config ? (*config) : InternalDataChannelInit();
2279 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2280 if (new_config.id < 0) {
2281 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002282 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002283 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2284 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2285 return nullptr;
2286 }
2287 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2288 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2289 << "because the id is already in use or out of range.";
2290 return nullptr;
2291 }
2292 }
2293
2294 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2295 session_.get(), session_->data_channel_type(), label, new_config));
2296 if (!channel) {
2297 sid_allocator_.ReleaseSid(new_config.id);
2298 return nullptr;
2299 }
2300
2301 if (channel->data_channel_type() == cricket::DCT_RTP) {
2302 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2303 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2304 << " already exists.";
2305 return nullptr;
2306 }
2307 rtp_data_channels_[channel->label()] = channel;
2308 } else {
2309 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2310 sctp_data_channels_.push_back(channel);
2311 channel->SignalClosed.connect(this,
2312 &PeerConnection::OnSctpDataChannelClosed);
2313 }
2314
hbos82ebe022016-11-14 01:41:09 -08002315 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002316 return channel;
2317}
2318
2319bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002320#ifdef HAVE_QUIC
2321 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2322 (session_->quic_data_transport() &&
2323 session_->quic_data_transport()->HasDataChannels());
2324#else
deadbeefab9b2d12015-10-14 11:33:11 -07002325 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002326#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002327}
2328
2329void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2330 for (const auto& channel : sctp_data_channels_) {
2331 if (channel->id() < 0) {
2332 int sid;
2333 if (!sid_allocator_.AllocateSid(role, &sid)) {
2334 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2335 continue;
2336 }
2337 channel->SetSctpSid(sid);
2338 }
2339 }
2340}
2341
2342void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002343 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002344 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2345 ++it) {
2346 if (it->get() == channel) {
2347 if (channel->id() >= 0) {
2348 sid_allocator_.ReleaseSid(channel->id());
2349 }
deadbeefbd292462015-12-14 18:15:29 -08002350 // Since this method is triggered by a signal from the DataChannel,
2351 // we can't free it directly here; we need to free it asynchronously.
2352 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002353 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002354 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2355 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002356 return;
2357 }
2358 }
2359}
2360
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002361void PeerConnection::OnVoiceChannelCreated() {
2362 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2363 session_->voice_channel(), senders_, receivers_,
2364 cricket::MEDIA_TYPE_AUDIO);
2365}
2366
deadbeefab9b2d12015-10-14 11:33:11 -07002367void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002368 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2369 cricket::VoiceChannel>(
2370 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2371}
2372
2373void PeerConnection::OnVideoChannelCreated() {
2374 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2375 session_->video_channel(), senders_, receivers_,
2376 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002377}
2378
2379void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002380 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2381 cricket::VideoChannel>(
2382 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002383}
2384
2385void PeerConnection::OnDataChannelCreated() {
2386 for (const auto& channel : sctp_data_channels_) {
2387 channel->OnTransportChannelCreated();
2388 }
2389}
2390
2391void PeerConnection::OnDataChannelDestroyed() {
2392 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2393 // DataChannel may callback to us and try to modify the list.
2394 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2395 temp_rtp_dcs.swap(rtp_data_channels_);
2396 for (const auto& kv : temp_rtp_dcs) {
2397 kv.second->OnTransportChannelDestroyed();
2398 }
2399
2400 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2401 temp_sctp_dcs.swap(sctp_data_channels_);
2402 for (const auto& channel : temp_sctp_dcs) {
2403 channel->OnTransportChannelDestroyed();
2404 }
2405}
2406
2407void PeerConnection::OnDataChannelOpenMessage(
2408 const std::string& label,
2409 const InternalDataChannelInit& config) {
2410 rtc::scoped_refptr<DataChannel> channel(
2411 InternalCreateDataChannel(label, &config));
2412 if (!channel.get()) {
2413 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2414 return;
2415 }
2416
deadbeefa601f5c2016-06-06 14:27:39 -07002417 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2418 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002419 // Call both the raw pointer and scoped_refptr versions of the method
2420 // for compatibility.
2421 observer_->OnDataChannel(proxy_channel.get());
2422 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002423}
2424
deadbeefa601f5c2016-06-06 14:27:39 -07002425RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2426 auto it = std::find_if(
2427 senders_.begin(), senders_.end(),
2428 [id](const rtc::scoped_refptr<
2429 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2430 return sender->id() == id;
2431 });
2432 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002433}
2434
deadbeefa601f5c2016-06-06 14:27:39 -07002435std::vector<
2436 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002437PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2438 return std::find_if(
2439 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002440 [track](const rtc::scoped_refptr<
2441 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002442 return sender->track() == track;
2443 });
2444}
2445
deadbeefa601f5c2016-06-06 14:27:39 -07002446std::vector<rtc::scoped_refptr<
2447 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002448PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002449 return std::find_if(
2450 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002451 [track_id](const rtc::scoped_refptr<
2452 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002453 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002454 });
2455}
2456
deadbeefab9b2d12015-10-14 11:33:11 -07002457PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2458 cricket::MediaType media_type) {
2459 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2460 media_type == cricket::MEDIA_TYPE_VIDEO);
2461 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2462 : &remote_video_tracks_;
2463}
2464
2465PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2466 cricket::MediaType media_type) {
2467 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2468 media_type == cricket::MEDIA_TYPE_VIDEO);
2469 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2470 : &local_video_tracks_;
2471}
2472
2473const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2474 const PeerConnection::TrackInfos& infos,
2475 const std::string& stream_label,
2476 const std::string track_id) const {
2477 for (const TrackInfo& track_info : infos) {
2478 if (track_info.stream_label == stream_label &&
2479 track_info.track_id == track_id) {
2480 return &track_info;
2481 }
2482 }
2483 return nullptr;
2484}
2485
2486DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2487 for (const auto& channel : sctp_data_channels_) {
2488 if (channel->id() == sid) {
2489 return channel;
2490 }
2491 }
2492 return nullptr;
2493}
2494
deadbeef91dd5672016-05-18 16:55:30 -07002495bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002496 const RTCConfiguration& configuration) {
2497 cricket::ServerAddresses stun_servers;
2498 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002499 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2500 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002501 return false;
2502 }
2503
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002504 port_allocator_->Initialize();
2505
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002506 // To handle both internal and externally created port allocator, we will
2507 // enable BUNDLE here.
2508 int portallocator_flags = port_allocator_->flags();
2509 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002510 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2511 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002512 // If the disable-IPv6 flag was specified, we'll not override it
2513 // by experiment.
2514 if (configuration.disable_ipv6) {
2515 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002516 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2517 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002518 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2519 }
2520
zhihuangb09b3f92017-03-07 14:40:51 -08002521 if (configuration.disable_ipv6_on_wifi) {
2522 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2523 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2524 }
2525
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002526 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2527 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2528 LOG(LS_INFO) << "TCP candidates are disabled.";
2529 }
2530
honghaiz60347052016-05-31 18:29:12 -07002531 if (configuration.candidate_network_policy ==
2532 kCandidateNetworkPolicyLowCost) {
2533 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2534 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2535 }
2536
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002537 port_allocator_->set_flags(portallocator_flags);
2538 // No step delay is used while allocating ports.
2539 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2540 port_allocator_->set_candidate_filter(
2541 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2542
2543 // Call this last since it may create pooled allocator sessions using the
2544 // properties set above.
2545 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002546 configuration.ice_candidate_pool_size,
2547 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002548 return true;
2549}
2550
deadbeef91dd5672016-05-18 16:55:30 -07002551bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002552 const cricket::ServerAddresses& stun_servers,
2553 const std::vector<cricket::RelayServerConfig>& turn_servers,
2554 IceTransportsType type,
2555 int candidate_pool_size,
2556 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002557 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002558 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002559 // Call this last since it may create pooled allocator sessions using the
2560 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002561 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002562 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002563}
2564
ivoc14d5dbe2016-07-04 07:06:55 -07002565bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2566 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002567 if (!event_log_) {
2568 return false;
2569 }
skvlad11a9cbf2016-10-07 11:53:05 -07002570 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002571}
2572
2573void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002574 if (event_log_) {
2575 event_log_->StopLogging();
2576 }
ivoc14d5dbe2016-07-04 07:06:55 -07002577}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578} // namespace webrtc