blob: 48ffebe222d1c6482d81e27d244ee6f4e79dbc25 [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;
480 bool enable_rtp_data_channel;
481 bool enable_quic;
482 rtc::Optional<int> screencast_min_bitrate;
483 rtc::Optional<bool> combined_audio_video_bwe;
484 rtc::Optional<bool> enable_dtls_srtp;
485 int ice_candidate_pool_size;
486 bool prune_turn_ports;
487 bool presume_writable_when_fully_relayed;
488 bool enable_ice_renomination;
489 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800490 rtc::Optional<int> ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800491 };
492 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
493 "Did you add something to RTCConfiguration and forget to "
494 "update operator==?");
495 return type == o.type && servers == o.servers &&
496 bundle_policy == o.bundle_policy &&
497 rtcp_mux_policy == o.rtcp_mux_policy &&
498 tcp_candidate_policy == o.tcp_candidate_policy &&
499 candidate_network_policy == o.candidate_network_policy &&
500 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
501 audio_jitter_buffer_fast_accelerate ==
502 o.audio_jitter_buffer_fast_accelerate &&
503 ice_connection_receiving_timeout ==
504 o.ice_connection_receiving_timeout &&
505 ice_backup_candidate_pair_ping_interval ==
506 o.ice_backup_candidate_pair_ping_interval &&
507 continual_gathering_policy == o.continual_gathering_policy &&
508 certificates == o.certificates &&
509 prioritize_most_likely_ice_candidate_pairs ==
510 o.prioritize_most_likely_ice_candidate_pairs &&
511 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
512 enable_rtp_data_channel == o.enable_rtp_data_channel &&
513 enable_quic == o.enable_quic &&
514 screencast_min_bitrate == o.screencast_min_bitrate &&
515 combined_audio_video_bwe == o.combined_audio_video_bwe &&
516 enable_dtls_srtp == o.enable_dtls_srtp &&
517 ice_candidate_pool_size == o.ice_candidate_pool_size &&
518 prune_turn_ports == o.prune_turn_ports &&
519 presume_writable_when_fully_relayed ==
520 o.presume_writable_when_fully_relayed &&
521 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800522 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
523 ice_check_min_interval == o.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800524}
525
526bool PeerConnectionInterface::RTCConfiguration::operator!=(
527 const PeerConnectionInterface::RTCConfiguration& o) const {
528 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800529}
530
zhihuang8f65cdf2016-05-06 18:40:30 -0700531// Generate a RTCP CNAME when a PeerConnection is created.
532std::string GenerateRtcpCname() {
533 std::string cname;
534 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
535 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800536 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700537 }
538 return cname;
539}
540
htaa2a49d92016-03-04 02:51:39 -0800541bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700542 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800543 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700544 cricket::MediaSessionOptions* session_options) {
545 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
546 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
547 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
548 return false;
549 }
550
htaaac2dea2016-03-10 13:35:55 -0800551 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700552 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700553 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800554 } else {
555 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700556 }
htaaac2dea2016-03-10 13:35:55 -0800557 // For offers, we only offer video if we have it or it's forced by options.
558 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700559 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700560 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800561 } else if (is_offer) {
562 session_options->recv_video = false;
563 } else {
564 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700565 }
566
567 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700568 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800569 for (auto& kv : session_options->transport_options) {
570 kv.second.ice_restart = rtc_options.ice_restart;
571 }
deadbeefab9b2d12015-10-14 11:33:11 -0700572
573 return true;
574}
575
576bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
577 cricket::MediaSessionOptions* session_options) {
578 bool value = false;
579 size_t mandatory_constraints_satisfied = 0;
580
581 // kOfferToReceiveAudio defaults to true according to spec.
582 if (!FindConstraint(constraints,
583 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
584 &mandatory_constraints_satisfied) ||
585 value) {
586 session_options->recv_audio = true;
587 }
588
589 // kOfferToReceiveVideo defaults to false according to spec. But
590 // if it is an answer and video is offered, we should still accept video
591 // per default.
592 value = false;
593 if (!FindConstraint(constraints,
594 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
595 &mandatory_constraints_satisfied) ||
596 value) {
597 session_options->recv_video = true;
598 }
599
600 if (FindConstraint(constraints,
601 MediaConstraintsInterface::kVoiceActivityDetection, &value,
602 &mandatory_constraints_satisfied)) {
603 session_options->vad_enabled = value;
604 }
605
606 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
607 &mandatory_constraints_satisfied)) {
608 session_options->bundle_enabled = value;
609 } else {
610 // kUseRtpMux defaults to true according to spec.
611 session_options->bundle_enabled = true;
612 }
deadbeefab9b2d12015-10-14 11:33:11 -0700613
deadbeef0ed85b22016-02-23 17:24:52 -0800614 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700615 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
616 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700617 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800618 ice_restart = true;
619 }
620 for (auto& kv : session_options->transport_options) {
621 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700622 }
623
624 if (!constraints) {
625 return true;
626 }
627 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
628}
629
deadbeef293e9262017-01-11 12:28:30 -0800630RTCErrorType ParseIceServers(
631 const PeerConnectionInterface::IceServers& servers,
632 cricket::ServerAddresses* stun_servers,
633 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200634 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
635 if (!server.urls.empty()) {
636 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200637 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700638 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800639 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200640 }
deadbeef293e9262017-01-11 12:28:30 -0800641 RTCErrorType err =
642 ParseIceServerUrl(server, url, stun_servers, turn_servers);
643 if (err != RTCErrorType::NONE) {
644 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200645 }
646 }
647 } else if (!server.uri.empty()) {
648 // Fallback to old .uri if new .urls isn't present.
deadbeef293e9262017-01-11 12:28:30 -0800649 RTCErrorType err =
650 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
651 if (err != RTCErrorType::NONE) {
652 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200653 }
654 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700655 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800656 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 }
658 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800659 // Candidates must have unique priorities, so that connectivity checks
660 // are performed in a well-defined order.
661 int priority = static_cast<int>(turn_servers->size() - 1);
662 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
663 // First in the list gets highest priority.
664 turn_server.priority = priority--;
665 }
deadbeef293e9262017-01-11 12:28:30 -0800666 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667}
668
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669PeerConnection::PeerConnection(PeerConnectionFactory* factory)
670 : factory_(factory),
671 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000672 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700675 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800676 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700677 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700678 local_streams_(StreamCollection::Create()),
679 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680
681PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100682 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700683 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700684 // Need to detach RTP senders/receivers from WebRtcSession,
685 // since it's about to be destroyed.
686 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700687 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700688 }
689 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700690 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700691 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700692 // Destroy stats_ because it depends on session_.
693 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800694 if (stats_collector_) {
695 stats_collector_->WaitForPendingRequest();
696 stats_collector_ = nullptr;
697 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700698 // Now destroy session_ before destroying other members,
699 // because its destruction fires signals (such as VoiceChannelDestroyed)
700 // which will trigger some final actions in PeerConnection...
701 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700702 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700703 network_thread()->Invoke<void>(RTC_FROM_HERE,
704 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705}
706
707bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000708 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700709 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200710 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800711 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100712 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800713 if (!allocator) {
714 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
715 << "This shouldn't happen if using PeerConnectionFactory.";
716 return false;
717 }
deadbeef653b8e02015-11-11 12:55:10 -0800718 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800719 // TODO(deadbeef): Why do we do this?
720 LOG(LS_ERROR) << "PeerConnection initialized without a "
721 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800722 return false;
723 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000724 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800725 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800726
deadbeef91dd5672016-05-18 16:55:30 -0700727 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700728 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700729 if (!network_thread()->Invoke<bool>(
730 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
731 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732 return false;
733 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734
skvlad11a9cbf2016-10-07 11:53:05 -0700735 media_controller_.reset(factory_->CreateMediaController(
736 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737
zhihuang29ff8442016-07-27 11:07:25 -0700738 session_.reset(new WebRtcSession(
739 media_controller_.get(), factory_->network_thread(),
740 factory_->worker_thread(), factory_->signaling_thread(),
741 port_allocator_.get(),
742 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700743 factory_->CreateTransportController(
744 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800745 configuration.redetermine_role_on_ice_restart)),
746#ifdef HAVE_SCTP
747 std::unique_ptr<cricket::SctpTransportInternalFactory>(
748 new cricket::SctpTransportFactory(factory_->network_thread()))
749#else
750 nullptr
751#endif
752 ));
zhihuang29ff8442016-07-27 11:07:25 -0700753
deadbeefab9b2d12015-10-14 11:33:11 -0700754 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700755 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756
757 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200758 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800759 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000760 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700761 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763 // Register PeerConnection as receiver of local ice candidates.
764 // All the callbacks will be posted to the application from PeerConnection.
765 session_->RegisterIceObserver(this);
766 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700767 session_->SignalVoiceChannelCreated.connect(
768 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700769 session_->SignalVoiceChannelDestroyed.connect(
770 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700771 session_->SignalVideoChannelCreated.connect(
772 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700773 session_->SignalVideoChannelDestroyed.connect(
774 this, &PeerConnection::OnVideoChannelDestroyed);
775 session_->SignalDataChannelCreated.connect(
776 this, &PeerConnection::OnDataChannelCreated);
777 session_->SignalDataChannelDestroyed.connect(
778 this, &PeerConnection::OnDataChannelDestroyed);
779 session_->SignalDataChannelOpenMessage.connect(
780 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800781
782 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783 return true;
784}
785
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000786rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000787PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700788 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000789}
790
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000791rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000792PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700793 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794}
795
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000796bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100797 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000798 if (IsClosed()) {
799 return false;
800 }
deadbeefab9b2d12015-10-14 11:33:11 -0700801 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802 return false;
803 }
deadbeefab9b2d12015-10-14 11:33:11 -0700804
805 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800806 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
807 observer->SignalAudioTrackAdded.connect(this,
808 &PeerConnection::OnAudioTrackAdded);
809 observer->SignalAudioTrackRemoved.connect(
810 this, &PeerConnection::OnAudioTrackRemoved);
811 observer->SignalVideoTrackAdded.connect(this,
812 &PeerConnection::OnVideoTrackAdded);
813 observer->SignalVideoTrackRemoved.connect(
814 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700815 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700816
deadbeefab9b2d12015-10-14 11:33:11 -0700817 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800818 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700819 }
820 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800821 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700822 }
823
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000824 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 observer_->OnRenegotiationNeeded();
826 return true;
827}
828
829void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700831 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800832 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700833 }
834 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800835 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700836 }
837
838 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800839 stream_observers_.erase(
840 std::remove_if(
841 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700842 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800843 return observer->stream()->label().compare(local_stream->label()) ==
844 0;
845 }),
846 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700847
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 if (IsClosed()) {
849 return;
850 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000851 observer_->OnRenegotiationNeeded();
852}
853
deadbeefe1f9d832016-01-14 15:35:42 -0800854rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
855 MediaStreamTrackInterface* track,
856 std::vector<MediaStreamInterface*> streams) {
857 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
858 if (IsClosed()) {
859 return nullptr;
860 }
861 if (streams.size() >= 2) {
862 LOG(LS_ERROR)
863 << "Adding a track with two streams is not currently supported.";
864 return nullptr;
865 }
866 // TODO(deadbeef): Support adding a track to two different senders.
867 if (FindSenderForTrack(track) != senders_.end()) {
868 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
869 return nullptr;
870 }
871
872 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700873 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800874 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700875 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800876 signaling_thread(),
877 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700878 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800879 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700880 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800881 }
882 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700883 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800884 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700885 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800886 }
887 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700888 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800889 signaling_thread(),
890 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700891 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800892 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700893 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800894 }
895 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700896 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800897 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700898 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800899 }
900 } else {
901 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
902 return rtc::scoped_refptr<RtpSenderInterface>();
903 }
904
905 senders_.push_back(new_sender);
906 observer_->OnRenegotiationNeeded();
907 return new_sender;
908}
909
910bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
911 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
912 if (IsClosed()) {
913 return false;
914 }
915
916 auto it = std::find(senders_.begin(), senders_.end(), sender);
917 if (it == senders_.end()) {
918 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
919 return false;
920 }
deadbeefa601f5c2016-06-06 14:27:39 -0700921 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800922 senders_.erase(it);
923
924 observer_->OnRenegotiationNeeded();
925 return true;
926}
927
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000928rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100930 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700931 if (IsClosed()) {
932 return nullptr;
933 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934 if (!track) {
935 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800936 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 }
deadbeef20cb0c12017-02-01 20:27:00 -0800938 auto it = FindSenderForTrack(track);
939 if (it == senders_.end()) {
940 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
941 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942 }
943
deadbeef20cb0c12017-02-01 20:27:00 -0800944 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945}
946
deadbeeffac06552015-11-25 11:26:01 -0800947rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800948 const std::string& kind,
949 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100950 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700951 if (IsClosed()) {
952 return nullptr;
953 }
deadbeefa601f5c2016-06-06 14:27:39 -0700954 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800955 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700956 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700957 signaling_thread(),
958 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800959 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700960 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700961 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800962 } else {
963 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800964 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800965 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800966 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700967 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800968 }
deadbeeffac06552015-11-25 11:26:01 -0800969 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800970 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800971}
972
deadbeef70ab1a12015-09-28 16:53:55 -0700973std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
974 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700975 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
976 for (const auto& sender : senders_) {
977 ret.push_back(sender.get());
978 }
979 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700980}
981
982std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
983PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700984 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
985 for (const auto& receiver : receivers_) {
986 ret.push_back(receiver.get());
987 }
988 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700989}
990
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000992 MediaStreamTrackInterface* track,
993 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100994 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700995 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800996 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 LOG(LS_ERROR) << "GetStats - observer is NULL.";
998 return false;
999 }
1000
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001001 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001002 // The StatsCollector is used to tell if a track is valid because it may
1003 // remember tracks that the PeerConnection previously removed.
1004 if (track && !stats_->IsValidTrack(track->id())) {
1005 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1006 << track->id();
1007 return false;
1008 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001009 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001010 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 return true;
1012}
1013
hbos74e1a4f2016-09-15 23:33:01 -07001014void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1015 RTC_DCHECK(stats_collector_);
1016 stats_collector_->GetStatsReport(callback);
1017}
1018
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1020 return signaling_state_;
1021}
1022
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023PeerConnectionInterface::IceConnectionState
1024PeerConnection::ice_connection_state() {
1025 return ice_connection_state_;
1026}
1027
1028PeerConnectionInterface::IceGatheringState
1029PeerConnection::ice_gathering_state() {
1030 return ice_gathering_state_;
1031}
1032
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001033rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034PeerConnection::CreateDataChannel(
1035 const std::string& label,
1036 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001037 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001038#ifdef HAVE_QUIC
1039 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1040 // TODO(zhihuang): Handle case when config is NULL.
1041 if (!config) {
1042 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1043 return nullptr;
1044 }
1045 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1046 if (!config->reliable || config->ordered) {
1047 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1048 "ordered delivery.";
1049 return nullptr;
1050 }
1051 return session_->quic_data_transport()->CreateDataChannel(label, config);
1052 }
1053#endif // HAVE_QUIC
1054
deadbeefab9b2d12015-10-14 11:33:11 -07001055 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001056
kwibergd1fe2812016-04-27 06:47:29 -07001057 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001058 if (config) {
1059 internal_config.reset(new InternalDataChannelInit(*config));
1060 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001061 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001062 InternalCreateDataChannel(label, internal_config.get()));
1063 if (!channel.get()) {
1064 return nullptr;
1065 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001067 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1068 // the first SCTP DataChannel.
1069 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1070 observer_->OnRenegotiationNeeded();
1071 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001072
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073 return DataChannelProxy::Create(signaling_thread(), channel.get());
1074}
1075
1076void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1077 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001078 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001079 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1081 return;
1082 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001083 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001084
1085 bool value;
1086 size_t mandatory_constraints = 0;
1087
1088 if (FindConstraint(constraints,
1089 MediaConstraintsInterface::kOfferToReceiveAudio,
1090 &value,
1091 &mandatory_constraints)) {
1092 options.offer_to_receive_audio =
1093 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1094 }
1095
1096 if (FindConstraint(constraints,
1097 MediaConstraintsInterface::kOfferToReceiveVideo,
1098 &value,
1099 &mandatory_constraints)) {
1100 options.offer_to_receive_video =
1101 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1102 }
1103
1104 if (FindConstraint(constraints,
1105 MediaConstraintsInterface::kVoiceActivityDetection,
1106 &value,
1107 &mandatory_constraints)) {
1108 options.voice_activity_detection = value;
1109 }
1110
1111 if (FindConstraint(constraints,
1112 MediaConstraintsInterface::kIceRestart,
1113 &value,
1114 &mandatory_constraints)) {
1115 options.ice_restart = value;
1116 }
1117
1118 if (FindConstraint(constraints,
1119 MediaConstraintsInterface::kUseRtpMux,
1120 &value,
1121 &mandatory_constraints)) {
1122 options.use_rtp_mux = value;
1123 }
1124
1125 CreateOffer(observer, options);
1126}
1127
1128void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1129 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001130 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001131 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001132 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1133 return;
1134 }
deadbeefab9b2d12015-10-14 11:33:11 -07001135
1136 cricket::MediaSessionOptions session_options;
1137 if (!GetOptionsForOffer(options, &session_options)) {
1138 std::string error = "CreateOffer called with invalid options.";
1139 LOG(LS_ERROR) << error;
1140 PostCreateSessionDescriptionFailure(observer, error);
1141 return;
1142 }
1143
1144 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001145}
1146
1147void PeerConnection::CreateAnswer(
1148 CreateSessionDescriptionObserver* observer,
1149 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001150 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001151 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1153 return;
1154 }
deadbeefab9b2d12015-10-14 11:33:11 -07001155
1156 cricket::MediaSessionOptions session_options;
1157 if (!GetOptionsForAnswer(constraints, &session_options)) {
1158 std::string error = "CreateAnswer called with invalid constraints.";
1159 LOG(LS_ERROR) << error;
1160 PostCreateSessionDescriptionFailure(observer, error);
1161 return;
1162 }
1163
htaa2a49d92016-03-04 02:51:39 -08001164 session_->CreateAnswer(observer, session_options);
1165}
1166
1167void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1168 const RTCOfferAnswerOptions& options) {
1169 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001170 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -08001171 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1172 return;
1173 }
1174
1175 cricket::MediaSessionOptions session_options;
1176 if (!GetOptionsForAnswer(options, &session_options)) {
1177 std::string error = "CreateAnswer called with invalid options.";
1178 LOG(LS_ERROR) << error;
1179 PostCreateSessionDescriptionFailure(observer, error);
1180 return;
1181 }
1182
1183 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184}
1185
1186void PeerConnection::SetLocalDescription(
1187 SetSessionDescriptionObserver* observer,
1188 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001189 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001190 if (IsClosed()) {
1191 return;
1192 }
nisse7ce109a2017-01-31 00:57:56 -08001193 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1195 return;
1196 }
1197 if (!desc) {
1198 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1199 return;
1200 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201 // Update stats here so that we have the most recent stats for tracks and
1202 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001203 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001204 std::string error;
1205 if (!session_->SetLocalDescription(desc, &error)) {
1206 PostSetSessionDescriptionFailure(observer, error);
1207 return;
1208 }
deadbeefab9b2d12015-10-14 11:33:11 -07001209
1210 // If setting the description decided our SSL role, allocate any necessary
1211 // SCTP sids.
1212 rtc::SSLRole role;
1213 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001214 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001215 AllocateSctpSids(role);
1216 }
1217
1218 // Update state and SSRC of local MediaStreams and DataChannels based on the
1219 // local session description.
1220 const cricket::ContentInfo* audio_content =
1221 GetFirstAudioContent(desc->description());
1222 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001223 if (audio_content->rejected) {
1224 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1225 } else {
1226 const cricket::AudioContentDescription* audio_desc =
1227 static_cast<const cricket::AudioContentDescription*>(
1228 audio_content->description);
1229 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1230 }
deadbeefab9b2d12015-10-14 11:33:11 -07001231 }
1232
1233 const cricket::ContentInfo* video_content =
1234 GetFirstVideoContent(desc->description());
1235 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001236 if (video_content->rejected) {
1237 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1238 } else {
1239 const cricket::VideoContentDescription* video_desc =
1240 static_cast<const cricket::VideoContentDescription*>(
1241 video_content->description);
1242 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1243 }
deadbeefab9b2d12015-10-14 11:33:11 -07001244 }
1245
1246 const cricket::ContentInfo* data_content =
1247 GetFirstDataContent(desc->description());
1248 if (data_content) {
1249 const cricket::DataContentDescription* data_desc =
1250 static_cast<const cricket::DataContentDescription*>(
1251 data_content->description);
1252 if (rtc::starts_with(data_desc->protocol().data(),
1253 cricket::kMediaProtocolRtpPrefix)) {
1254 UpdateLocalRtpDataChannels(data_desc->streams());
1255 }
1256 }
1257
1258 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001259 signaling_thread()->Post(RTC_FROM_HERE, this,
1260 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001261
deadbeefcbecd352015-09-23 11:50:27 -07001262 // MaybeStartGathering needs to be called after posting
1263 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1264 // before signaling that SetLocalDescription completed.
1265 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266}
1267
1268void PeerConnection::SetRemoteDescription(
1269 SetSessionDescriptionObserver* observer,
1270 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001271 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001272 if (IsClosed()) {
1273 return;
1274 }
nisse7ce109a2017-01-31 00:57:56 -08001275 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1277 return;
1278 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279 if (!desc) {
1280 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1281 return;
1282 }
1283 // Update stats here so that we have the most recent stats for tracks and
1284 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001285 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286 std::string error;
1287 if (!session_->SetRemoteDescription(desc, &error)) {
1288 PostSetSessionDescriptionFailure(observer, error);
1289 return;
1290 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291
deadbeefab9b2d12015-10-14 11:33:11 -07001292 // If setting the description decided our SSL role, allocate any necessary
1293 // SCTP sids.
1294 rtc::SSLRole role;
1295 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001296 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001297 AllocateSctpSids(role);
1298 }
1299
1300 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001301 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1302 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1303 const cricket::AudioContentDescription* audio_desc =
1304 GetFirstAudioContentDescription(remote_desc);
1305 const cricket::VideoContentDescription* video_desc =
1306 GetFirstVideoContentDescription(remote_desc);
1307 const cricket::DataContentDescription* data_desc =
1308 GetFirstDataContentDescription(remote_desc);
1309
1310 // Check if the descriptions include streams, just in case the peer supports
1311 // MSID, but doesn't indicate so with "a=msid-semantic".
1312 if (remote_desc->msid_supported() ||
1313 (audio_desc && !audio_desc->streams().empty()) ||
1314 (video_desc && !video_desc->streams().empty())) {
1315 remote_peer_supports_msid_ = true;
1316 }
deadbeefab9b2d12015-10-14 11:33:11 -07001317
1318 // We wait to signal new streams until we finish processing the description,
1319 // since only at that point will new streams have all their tracks.
1320 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1321
1322 // Find all audio rtp streams and create corresponding remote AudioTracks
1323 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001324 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001325 if (audio_content->rejected) {
1326 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1327 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001328 bool default_audio_track_needed =
1329 !remote_peer_supports_msid_ &&
1330 MediaContentDirectionHasSend(audio_desc->direction());
1331 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1332 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001333 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001334 }
deadbeefab9b2d12015-10-14 11:33:11 -07001335 }
1336
1337 // Find all video rtp streams and create corresponding remote VideoTracks
1338 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001339 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001340 if (video_content->rejected) {
1341 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1342 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001343 bool default_video_track_needed =
1344 !remote_peer_supports_msid_ &&
1345 MediaContentDirectionHasSend(video_desc->direction());
1346 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1347 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001348 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001349 }
deadbeefab9b2d12015-10-14 11:33:11 -07001350 }
1351
1352 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001353 if (data_desc) {
1354 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001355 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001356 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001357 }
1358 }
1359
1360 // Iterate new_streams and notify the observer about new MediaStreams.
1361 for (size_t i = 0; i < new_streams->count(); ++i) {
1362 MediaStreamInterface* new_stream = new_streams->at(i);
1363 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001364 // Call both the raw pointer and scoped_refptr versions of the method
1365 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001366 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001367 observer_->OnAddStream(
1368 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001369 }
1370
deadbeefbda7e0b2015-12-08 17:13:40 -08001371 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001372
1373 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001374 signaling_thread()->Post(RTC_FROM_HERE, this,
1375 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001376}
1377
deadbeef46c73892016-11-16 19:42:04 -08001378PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1379 return configuration_;
1380}
1381
deadbeef293e9262017-01-11 12:28:30 -08001382bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1383 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001384 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001385
1386 if (session_->local_description() &&
1387 configuration.ice_candidate_pool_size !=
1388 configuration_.ice_candidate_pool_size) {
1389 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1390 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001391 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001392 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001393
deadbeef293e9262017-01-11 12:28:30 -08001394 // The simplest (and most future-compatible) way to tell if the config was
1395 // modified in an invalid way is to copy each property we do support
1396 // modifying, then use operator==. There are far more properties we don't
1397 // support modifying than those we do, and more could be added.
1398 RTCConfiguration modified_config = configuration_;
1399 modified_config.servers = configuration.servers;
1400 modified_config.type = configuration.type;
1401 modified_config.ice_candidate_pool_size =
1402 configuration.ice_candidate_pool_size;
1403 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001404 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001405 if (configuration != modified_config) {
1406 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1407 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1408 }
1409
1410 // Note that this isn't possible through chromium, since it's an unsigned
1411 // short in WebIDL.
1412 if (configuration.ice_candidate_pool_size < 0 ||
1413 configuration.ice_candidate_pool_size > UINT16_MAX) {
1414 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1415 }
1416
1417 // Parse ICE servers before hopping to network thread.
1418 cricket::ServerAddresses stun_servers;
1419 std::vector<cricket::RelayServerConfig> turn_servers;
1420 RTCErrorType parse_error =
1421 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1422 if (parse_error != RTCErrorType::NONE) {
1423 return SafeSetError(parse_error, error);
1424 }
1425
1426 // In theory this shouldn't fail.
1427 if (!network_thread()->Invoke<bool>(
1428 RTC_FROM_HERE,
1429 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1430 stun_servers, turn_servers, modified_config.type,
1431 modified_config.ice_candidate_pool_size,
1432 modified_config.prune_turn_ports))) {
1433 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1434 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1435 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001436
deadbeefd1a38b52016-12-10 13:15:33 -08001437 // As described in JSEP, calling setConfiguration with new ICE servers or
1438 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1439 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001440 if (modified_config.servers != configuration_.servers ||
1441 modified_config.type != configuration_.type ||
1442 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001443 session_->SetNeedsIceRestartFlag();
1444 }
skvladd1f5fda2017-02-03 16:54:05 -08001445
1446 if (modified_config.ice_check_min_interval !=
1447 configuration_.ice_check_min_interval) {
1448 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1449 }
1450
deadbeef293e9262017-01-11 12:28:30 -08001451 configuration_ = modified_config;
1452 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001453}
1454
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455bool PeerConnection::AddIceCandidate(
1456 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001457 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001458 if (IsClosed()) {
1459 return false;
1460 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 return session_->ProcessIceMessage(ice_candidate);
1462}
1463
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001464bool PeerConnection::RemoveIceCandidates(
1465 const std::vector<cricket::Candidate>& candidates) {
1466 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1467 return session_->RemoveRemoteIceCandidates(candidates);
1468}
1469
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001470void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001471 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001472 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001473
1474 if (session_) {
1475 session_->set_metrics_observer(uma_observer_);
1476 }
1477
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001478 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001479 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001480 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001481 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001482 uma_observer_->IncrementEnumCounter(
1483 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1484 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001485 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001486 uma_observer_->IncrementEnumCounter(
1487 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1488 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001489 }
1490 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001491}
1492
ivoc14d5dbe2016-07-04 07:06:55 -07001493bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1494 int64_t max_size_bytes) {
1495 return factory_->worker_thread()->Invoke<bool>(
1496 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1497 max_size_bytes));
1498}
1499
1500void PeerConnection::StopRtcEventLog() {
1501 factory_->worker_thread()->Invoke<void>(
1502 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1503}
1504
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505const SessionDescriptionInterface* PeerConnection::local_description() const {
1506 return session_->local_description();
1507}
1508
1509const SessionDescriptionInterface* PeerConnection::remote_description() const {
1510 return session_->remote_description();
1511}
1512
deadbeeffe4a8a42016-12-20 17:56:17 -08001513const SessionDescriptionInterface* PeerConnection::current_local_description()
1514 const {
1515 return session_->current_local_description();
1516}
1517
1518const SessionDescriptionInterface* PeerConnection::current_remote_description()
1519 const {
1520 return session_->current_remote_description();
1521}
1522
1523const SessionDescriptionInterface* PeerConnection::pending_local_description()
1524 const {
1525 return session_->pending_local_description();
1526}
1527
1528const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1529 const {
1530 return session_->pending_remote_description();
1531}
1532
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001534 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535 // Update stats here so that we have the most recent stats for tracks and
1536 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001537 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001538
deadbeefd59daf82015-10-14 15:02:44 -07001539 session_->Close();
zhihuang77985012017-02-07 15:45:16 -08001540 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001541}
1542
deadbeefd59daf82015-10-14 15:02:44 -07001543void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1544 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001546 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001548 break;
deadbeefd59daf82015-10-14 15:02:44 -07001549 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001550 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1551 break;
deadbeefd59daf82015-10-14 15:02:44 -07001552 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001553 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1554 break;
deadbeefd59daf82015-10-14 15:02:44 -07001555 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1557 break;
deadbeefd59daf82015-10-14 15:02:44 -07001558 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1560 break;
deadbeefd59daf82015-10-14 15:02:44 -07001561 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562 ChangeSignalingState(PeerConnectionInterface::kStable);
1563 break;
deadbeefd59daf82015-10-14 15:02:44 -07001564 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 ChangeSignalingState(PeerConnectionInterface::kClosed);
1566 break;
1567 default:
1568 break;
1569 }
1570}
1571
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001572void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1575 SetSessionDescriptionMsg* param =
1576 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1577 param->observer->OnSuccess();
1578 delete param;
1579 break;
1580 }
1581 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1582 SetSessionDescriptionMsg* param =
1583 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1584 param->observer->OnFailure(param->error);
1585 delete param;
1586 break;
1587 }
deadbeefab9b2d12015-10-14 11:33:11 -07001588 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1589 CreateSessionDescriptionMsg* param =
1590 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1591 param->observer->OnFailure(param->error);
1592 delete param;
1593 break;
1594 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001595 case MSG_GETSTATS: {
1596 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001597 StatsReports reports;
1598 stats_->GetStats(param->track, &reports);
1599 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600 delete param;
1601 break;
1602 }
deadbeefbd292462015-12-14 18:15:29 -08001603 case MSG_FREE_DATACHANNELS: {
1604 sctp_data_channels_to_free_.clear();
1605 break;
1606 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001608 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001609 break;
1610 }
1611}
1612
deadbeefab9b2d12015-10-14 11:33:11 -07001613void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001614 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001615 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001616 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1617 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001618 signaling_thread(),
1619 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1620 stream->AddTrack(
1621 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001622 receivers_.push_back(receiver);
1623 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1624 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1625 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626}
1627
deadbeefab9b2d12015-10-14 11:33:11 -07001628void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001629 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001630 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001631 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1632 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001633 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001634 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1635 session_->video_channel()));
1636 stream->AddTrack(
1637 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001638 receivers_.push_back(receiver);
1639 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1640 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1641 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001642}
1643
deadbeef70ab1a12015-09-28 16:53:55 -07001644// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1645// description.
perkjd61bf802016-03-24 03:16:19 -07001646void PeerConnection::DestroyReceiver(const std::string& track_id) {
1647 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001648 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001649 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001650 << " doesn't exist.";
1651 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001652 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001653 receivers_.erase(it);
1654 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001655}
1656
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657void PeerConnection::OnIceConnectionChange(
1658 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001659 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001660 // After transitioning to "closed", ignore any additional states from
1661 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001662 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001663 return;
1664 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001665 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001666 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001667}
1668
1669void PeerConnection::OnIceGatheringChange(
1670 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001671 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672 if (IsClosed()) {
1673 return;
1674 }
1675 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001676 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001677}
1678
1679void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001680 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001681 if (IsClosed()) {
1682 return;
1683 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001684 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685}
1686
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001687void PeerConnection::OnIceCandidatesRemoved(
1688 const std::vector<cricket::Candidate>& candidates) {
1689 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001690 if (IsClosed()) {
1691 return;
1692 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001693 observer_->OnIceCandidatesRemoved(candidates);
1694}
1695
Peter Thatcher54360512015-07-08 11:08:35 -07001696void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001697 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001698 if (IsClosed()) {
1699 return;
1700 }
Peter Thatcher54360512015-07-08 11:08:35 -07001701 observer_->OnIceConnectionReceivingChange(receiving);
1702}
1703
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704void PeerConnection::ChangeSignalingState(
1705 PeerConnectionInterface::SignalingState signaling_state) {
1706 signaling_state_ = signaling_state;
1707 if (signaling_state == kClosed) {
1708 ice_connection_state_ = kIceConnectionClosed;
1709 observer_->OnIceConnectionChange(ice_connection_state_);
1710 if (ice_gathering_state_ != kIceGatheringComplete) {
1711 ice_gathering_state_ = kIceGatheringComplete;
1712 observer_->OnIceGatheringChange(ice_gathering_state_);
1713 }
1714 }
1715 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716}
1717
deadbeefeb459812015-12-15 19:24:43 -08001718void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1719 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001720 if (IsClosed()) {
1721 return;
1722 }
deadbeefeb459812015-12-15 19:24:43 -08001723 auto sender = FindSenderForTrack(track);
1724 if (sender != senders_.end()) {
1725 // We already have a sender for this track, so just change the stream_id
1726 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001727 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001728 return;
1729 }
1730
1731 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001732 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1733 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001734 signaling_thread(),
1735 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1736 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001737 senders_.push_back(new_sender);
1738 // If the sender has already been configured in SDP, we call SetSsrc,
1739 // which will connect the sender to the underlying transport. This can
1740 // occur if a local session description that contains the ID of the sender
1741 // is set before AddStream is called. It can also occur if the local
1742 // session description is not changed and RemoveStream is called, and
1743 // later AddStream is called again with the same stream.
1744 const TrackInfo* track_info =
1745 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1746 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001747 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001748 }
1749}
1750
1751// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1752// indefinitely, when we have unified plan SDP.
1753void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1754 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001755 if (IsClosed()) {
1756 return;
1757 }
deadbeefeb459812015-12-15 19:24:43 -08001758 auto sender = FindSenderForTrack(track);
1759 if (sender == senders_.end()) {
1760 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1761 << " doesn't exist.";
1762 return;
1763 }
deadbeefa601f5c2016-06-06 14:27:39 -07001764 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001765 senders_.erase(sender);
1766}
1767
1768void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1769 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001770 if (IsClosed()) {
1771 return;
1772 }
deadbeefeb459812015-12-15 19:24:43 -08001773 auto sender = FindSenderForTrack(track);
1774 if (sender != senders_.end()) {
1775 // We already have a sender for this track, so just change the stream_id
1776 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001777 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001778 return;
1779 }
1780
1781 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001782 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1783 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001784 signaling_thread(), new VideoRtpSender(track, stream->label(),
1785 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001786 senders_.push_back(new_sender);
1787 const TrackInfo* track_info =
1788 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1789 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001790 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001791 }
1792}
1793
1794void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1795 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001796 if (IsClosed()) {
1797 return;
1798 }
deadbeefeb459812015-12-15 19:24:43 -08001799 auto sender = FindSenderForTrack(track);
1800 if (sender == senders_.end()) {
1801 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1802 << " doesn't exist.";
1803 return;
1804 }
deadbeefa601f5c2016-06-06 14:27:39 -07001805 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001806 senders_.erase(sender);
1807}
1808
deadbeefab9b2d12015-10-14 11:33:11 -07001809void PeerConnection::PostSetSessionDescriptionFailure(
1810 SetSessionDescriptionObserver* observer,
1811 const std::string& error) {
1812 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1813 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001814 signaling_thread()->Post(RTC_FROM_HERE, this,
1815 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001816}
1817
1818void PeerConnection::PostCreateSessionDescriptionFailure(
1819 CreateSessionDescriptionObserver* observer,
1820 const std::string& error) {
1821 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1822 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001823 signaling_thread()->Post(RTC_FROM_HERE, this,
1824 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001825}
1826
1827bool PeerConnection::GetOptionsForOffer(
1828 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1829 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001830 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1831 // ContentInfos.
1832 if (session_->local_description()) {
1833 for (const cricket::ContentInfo& content :
1834 session_->local_description()->description()->contents()) {
1835 session_options->transport_options[content.name] =
1836 cricket::TransportOptions();
1837 }
1838 }
deadbeef46c73892016-11-16 19:42:04 -08001839 session_options->enable_ice_renomination =
1840 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001841
htaaac2dea2016-03-10 13:35:55 -08001842 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001843 return false;
1844 }
1845
deadbeeffac06552015-11-25 11:26:01 -08001846 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001847 // Offer to receive audio/video if the constraint is not set and there are
1848 // send streams, or we're currently receiving.
1849 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1850 session_options->recv_audio =
1851 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1852 !remote_audio_tracks_.empty();
1853 }
1854 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1855 session_options->recv_video =
1856 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1857 !remote_video_tracks_.empty();
1858 }
deadbeefc80741f2015-10-22 13:14:45 -07001859
zhihuang9763d562016-08-05 11:14:50 -07001860 // Intentionally unset the data channel type for RTP data channel with the
1861 // second condition. Otherwise the RTP data channels would be successfully
1862 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1863 // when building with chromium. We want to leave RTP data channels broken, so
1864 // people won't try to use them.
1865 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1866 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001867 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001868
zhihuangaf388472016-11-02 16:49:48 -07001869 session_options->bundle_enabled =
1870 session_options->bundle_enabled &&
1871 (session_options->has_audio() || session_options->has_video() ||
1872 session_options->has_data());
1873
zhihuang8f65cdf2016-05-06 18:40:30 -07001874 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001875 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001876 return true;
1877}
1878
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001879void PeerConnection::InitializeOptionsForAnswer(
1880 cricket::MediaSessionOptions* session_options) {
1881 session_options->recv_audio = false;
1882 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001883 session_options->enable_ice_renomination =
1884 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001885}
1886
htaa2a49d92016-03-04 02:51:39 -08001887void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001888 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001889 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1890 // ContentInfos.
1891 if (session_->remote_description()) {
1892 // Initialize the transport_options map.
1893 for (const cricket::ContentInfo& content :
1894 session_->remote_description()->description()->contents()) {
1895 session_options->transport_options[content.name] =
1896 cricket::TransportOptions();
1897 }
1898 }
deadbeeffac06552015-11-25 11:26:01 -08001899 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001900 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1901 // are not signaled in the SDP so does not go through that path and must be
1902 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001903 // Intentionally unset the data channel type for RTP data channel. Otherwise
1904 // the RTP data channels would be successfully negotiated by default and the
1905 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1906 // We want to leave RTP data channels broken, so people won't try to use them.
1907 if (session_->data_channel_type() != cricket::DCT_RTP) {
1908 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001909 }
zhihuangaf388472016-11-02 16:49:48 -07001910 session_options->bundle_enabled =
1911 session_options->bundle_enabled &&
1912 (session_options->has_audio() || session_options->has_video() ||
1913 session_options->has_data());
1914
jbauchcb560652016-08-04 05:20:32 -07001915 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001916}
1917
1918bool PeerConnection::GetOptionsForAnswer(
1919 const MediaConstraintsInterface* constraints,
1920 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001921 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001922 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1923 return false;
1924 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001925 session_options->rtcp_cname = rtcp_cname_;
1926
htaa2a49d92016-03-04 02:51:39 -08001927 FinishOptionsForAnswer(session_options);
1928 return true;
1929}
1930
1931bool PeerConnection::GetOptionsForAnswer(
1932 const RTCOfferAnswerOptions& options,
1933 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001934 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001935 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001936 return false;
1937 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001938 session_options->rtcp_cname = rtcp_cname_;
1939
htaa2a49d92016-03-04 02:51:39 -08001940 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001941 return true;
1942}
1943
deadbeeffaac4972015-11-12 15:33:07 -08001944void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1945 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001946 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1947 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001948}
1949
deadbeefab9b2d12015-10-14 11:33:11 -07001950void PeerConnection::UpdateRemoteStreamsList(
1951 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001952 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001953 cricket::MediaType media_type,
1954 StreamCollection* new_streams) {
1955 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1956
1957 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001958 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001959 auto track_it = current_tracks->begin();
1960 while (track_it != current_tracks->end()) {
1961 const TrackInfo& info = *track_it;
1962 const cricket::StreamParams* params =
1963 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001964 bool track_exists = params && params->id == info.track_id;
1965 // If this is a default track, and we still need it, don't remove it.
1966 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1967 track_exists) {
1968 ++track_it;
1969 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001970 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1971 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001972 }
1973 }
1974
1975 // Find new and active tracks.
1976 for (const cricket::StreamParams& params : streams) {
1977 // The sync_label is the MediaStream label and the |stream.id| is the
1978 // track id.
1979 const std::string& stream_label = params.sync_label;
1980 const std::string& track_id = params.id;
1981 uint32_t ssrc = params.first_ssrc();
1982
1983 rtc::scoped_refptr<MediaStreamInterface> stream =
1984 remote_streams_->find(stream_label);
1985 if (!stream) {
1986 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001987 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1988 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001989 remote_streams_->AddStream(stream);
1990 new_streams->AddStream(stream);
1991 }
1992
1993 const TrackInfo* track_info =
1994 FindTrackInfo(*current_tracks, stream_label, track_id);
1995 if (!track_info) {
1996 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1997 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1998 }
1999 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002000
2001 // Add default track if necessary.
2002 if (default_track_needed) {
2003 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2004 remote_streams_->find(kDefaultStreamLabel);
2005 if (!default_stream) {
2006 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002007 default_stream = MediaStreamProxy::Create(
2008 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002009 remote_streams_->AddStream(default_stream);
2010 new_streams->AddStream(default_stream);
2011 }
2012 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2013 ? kDefaultAudioTrackLabel
2014 : kDefaultVideoTrackLabel;
2015 const TrackInfo* default_track_info =
2016 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2017 if (!default_track_info) {
2018 current_tracks->push_back(
2019 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2020 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2021 }
2022 }
deadbeefab9b2d12015-10-14 11:33:11 -07002023}
2024
2025void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2026 const std::string& track_id,
2027 uint32_t ssrc,
2028 cricket::MediaType media_type) {
2029 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2030
2031 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002032 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002033 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002034 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002035 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002036 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002037 }
2038}
2039
2040void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2041 const std::string& track_id,
2042 cricket::MediaType media_type) {
2043 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2044
2045 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002046 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2047 // will be notified which will end the AudioRtpReceiver::track().
2048 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002049 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2050 stream->FindAudioTrack(track_id);
2051 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002052 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002053 }
2054 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002055 // Stopping or destroying a VideoRtpReceiver will end the
2056 // VideoRtpReceiver::track().
2057 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002058 rtc::scoped_refptr<VideoTrackInterface> video_track =
2059 stream->FindVideoTrack(track_id);
2060 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002061 // There's no guarantee the track is still available, e.g. the track may
2062 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002063 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002064 }
2065 } else {
nisseede5da42017-01-12 05:15:36 -08002066 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002067 }
2068}
2069
2070void PeerConnection::UpdateEndedRemoteMediaStreams() {
2071 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2072 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2073 MediaStreamInterface* stream = remote_streams_->at(i);
2074 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2075 streams_to_remove.push_back(stream);
2076 }
2077 }
2078
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002079 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002080 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002081 // Call both the raw pointer and scoped_refptr versions of the method
2082 // for compatibility.
2083 observer_->OnRemoveStream(stream.get());
2084 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002085 }
2086}
2087
deadbeefab9b2d12015-10-14 11:33:11 -07002088void PeerConnection::UpdateLocalTracks(
2089 const std::vector<cricket::StreamParams>& streams,
2090 cricket::MediaType media_type) {
2091 TrackInfos* current_tracks = GetLocalTracks(media_type);
2092
2093 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2094 // don't match the new StreamParam.
2095 TrackInfos::iterator track_it = current_tracks->begin();
2096 while (track_it != current_tracks->end()) {
2097 const TrackInfo& info = *track_it;
2098 const cricket::StreamParams* params =
2099 cricket::GetStreamBySsrc(streams, info.ssrc);
2100 if (!params || params->id != info.track_id ||
2101 params->sync_label != info.stream_label) {
2102 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2103 media_type);
2104 track_it = current_tracks->erase(track_it);
2105 } else {
2106 ++track_it;
2107 }
2108 }
2109
2110 // Find new and active tracks.
2111 for (const cricket::StreamParams& params : streams) {
2112 // The sync_label is the MediaStream label and the |stream.id| is the
2113 // track id.
2114 const std::string& stream_label = params.sync_label;
2115 const std::string& track_id = params.id;
2116 uint32_t ssrc = params.first_ssrc();
2117 const TrackInfo* track_info =
2118 FindTrackInfo(*current_tracks, stream_label, track_id);
2119 if (!track_info) {
2120 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2121 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2122 }
2123 }
2124}
2125
2126void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2127 const std::string& track_id,
2128 uint32_t ssrc,
2129 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002130 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002131 if (!sender) {
2132 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2133 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002134 return;
2135 }
2136
deadbeeffac06552015-11-25 11:26:01 -08002137 if (sender->media_type() != media_type) {
2138 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2139 << " description with an unexpected media type.";
2140 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002141 }
deadbeeffac06552015-11-25 11:26:01 -08002142
2143 sender->set_stream_id(stream_label);
2144 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002145}
2146
2147void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2148 const std::string& track_id,
2149 uint32_t ssrc,
2150 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002151 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002152 if (!sender) {
2153 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002154 // SessionDescriptions has been renegotiated.
2155 return;
2156 }
deadbeeffac06552015-11-25 11:26:01 -08002157
2158 // A sender has been removed from the SessionDescription but it's still
2159 // associated with the PeerConnection. This only occurs if the SDP doesn't
2160 // match with the calls to CreateSender, AddStream and RemoveStream.
2161 if (sender->media_type() != media_type) {
2162 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2163 << " description with an unexpected media type.";
2164 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002165 }
deadbeeffac06552015-11-25 11:26:01 -08002166
2167 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002168}
2169
2170void PeerConnection::UpdateLocalRtpDataChannels(
2171 const cricket::StreamParamsVec& streams) {
2172 std::vector<std::string> existing_channels;
2173
2174 // Find new and active data channels.
2175 for (const cricket::StreamParams& params : streams) {
2176 // |it->sync_label| is actually the data channel label. The reason is that
2177 // we use the same naming of data channels as we do for
2178 // MediaStreams and Tracks.
2179 // For MediaStreams, the sync_label is the MediaStream label and the
2180 // track label is the same as |streamid|.
2181 const std::string& channel_label = params.sync_label;
2182 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002183 if (data_channel_it == rtp_data_channels_.end()) {
2184 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002185 continue;
2186 }
2187 // Set the SSRC the data channel should use for sending.
2188 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2189 existing_channels.push_back(data_channel_it->first);
2190 }
2191
2192 UpdateClosingRtpDataChannels(existing_channels, true);
2193}
2194
2195void PeerConnection::UpdateRemoteRtpDataChannels(
2196 const cricket::StreamParamsVec& streams) {
2197 std::vector<std::string> existing_channels;
2198
2199 // Find new and active data channels.
2200 for (const cricket::StreamParams& params : streams) {
2201 // The data channel label is either the mslabel or the SSRC if the mslabel
2202 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2203 std::string label = params.sync_label.empty()
2204 ? rtc::ToString(params.first_ssrc())
2205 : params.sync_label;
2206 auto data_channel_it = rtp_data_channels_.find(label);
2207 if (data_channel_it == rtp_data_channels_.end()) {
2208 // This is a new data channel.
2209 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2210 } else {
2211 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2212 }
2213 existing_channels.push_back(label);
2214 }
2215
2216 UpdateClosingRtpDataChannels(existing_channels, false);
2217}
2218
2219void PeerConnection::UpdateClosingRtpDataChannels(
2220 const std::vector<std::string>& active_channels,
2221 bool is_local_update) {
2222 auto it = rtp_data_channels_.begin();
2223 while (it != rtp_data_channels_.end()) {
2224 DataChannel* data_channel = it->second;
2225 if (std::find(active_channels.begin(), active_channels.end(),
2226 data_channel->label()) != active_channels.end()) {
2227 ++it;
2228 continue;
2229 }
2230
2231 if (is_local_update) {
2232 data_channel->SetSendSsrc(0);
2233 } else {
2234 data_channel->RemotePeerRequestClose();
2235 }
2236
2237 if (data_channel->state() == DataChannel::kClosed) {
2238 rtp_data_channels_.erase(it);
2239 it = rtp_data_channels_.begin();
2240 } else {
2241 ++it;
2242 }
2243 }
2244}
2245
2246void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2247 uint32_t remote_ssrc) {
2248 rtc::scoped_refptr<DataChannel> channel(
2249 InternalCreateDataChannel(label, nullptr));
2250 if (!channel.get()) {
2251 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2252 << "CreateDataChannel failed.";
2253 return;
2254 }
2255 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002256 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2257 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002258 // Call both the raw pointer and scoped_refptr versions of the method
2259 // for compatibility.
2260 observer_->OnDataChannel(proxy_channel.get());
2261 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002262}
2263
2264rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2265 const std::string& label,
2266 const InternalDataChannelInit* config) {
2267 if (IsClosed()) {
2268 return nullptr;
2269 }
2270 if (session_->data_channel_type() == cricket::DCT_NONE) {
2271 LOG(LS_ERROR)
2272 << "InternalCreateDataChannel: Data is not supported in this call.";
2273 return nullptr;
2274 }
2275 InternalDataChannelInit new_config =
2276 config ? (*config) : InternalDataChannelInit();
2277 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2278 if (new_config.id < 0) {
2279 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002280 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002281 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2282 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2283 return nullptr;
2284 }
2285 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2286 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2287 << "because the id is already in use or out of range.";
2288 return nullptr;
2289 }
2290 }
2291
2292 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2293 session_.get(), session_->data_channel_type(), label, new_config));
2294 if (!channel) {
2295 sid_allocator_.ReleaseSid(new_config.id);
2296 return nullptr;
2297 }
2298
2299 if (channel->data_channel_type() == cricket::DCT_RTP) {
2300 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2301 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2302 << " already exists.";
2303 return nullptr;
2304 }
2305 rtp_data_channels_[channel->label()] = channel;
2306 } else {
2307 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2308 sctp_data_channels_.push_back(channel);
2309 channel->SignalClosed.connect(this,
2310 &PeerConnection::OnSctpDataChannelClosed);
2311 }
2312
hbos82ebe022016-11-14 01:41:09 -08002313 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002314 return channel;
2315}
2316
2317bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002318#ifdef HAVE_QUIC
2319 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2320 (session_->quic_data_transport() &&
2321 session_->quic_data_transport()->HasDataChannels());
2322#else
deadbeefab9b2d12015-10-14 11:33:11 -07002323 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002324#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002325}
2326
2327void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2328 for (const auto& channel : sctp_data_channels_) {
2329 if (channel->id() < 0) {
2330 int sid;
2331 if (!sid_allocator_.AllocateSid(role, &sid)) {
2332 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2333 continue;
2334 }
2335 channel->SetSctpSid(sid);
2336 }
2337 }
2338}
2339
2340void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002341 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002342 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2343 ++it) {
2344 if (it->get() == channel) {
2345 if (channel->id() >= 0) {
2346 sid_allocator_.ReleaseSid(channel->id());
2347 }
deadbeefbd292462015-12-14 18:15:29 -08002348 // Since this method is triggered by a signal from the DataChannel,
2349 // we can't free it directly here; we need to free it asynchronously.
2350 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002351 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002352 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2353 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002354 return;
2355 }
2356 }
2357}
2358
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002359void PeerConnection::OnVoiceChannelCreated() {
2360 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2361 session_->voice_channel(), senders_, receivers_,
2362 cricket::MEDIA_TYPE_AUDIO);
2363}
2364
deadbeefab9b2d12015-10-14 11:33:11 -07002365void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002366 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2367 cricket::VoiceChannel>(
2368 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2369}
2370
2371void PeerConnection::OnVideoChannelCreated() {
2372 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2373 session_->video_channel(), senders_, receivers_,
2374 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002375}
2376
2377void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002378 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2379 cricket::VideoChannel>(
2380 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002381}
2382
2383void PeerConnection::OnDataChannelCreated() {
2384 for (const auto& channel : sctp_data_channels_) {
2385 channel->OnTransportChannelCreated();
2386 }
2387}
2388
2389void PeerConnection::OnDataChannelDestroyed() {
2390 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2391 // DataChannel may callback to us and try to modify the list.
2392 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2393 temp_rtp_dcs.swap(rtp_data_channels_);
2394 for (const auto& kv : temp_rtp_dcs) {
2395 kv.second->OnTransportChannelDestroyed();
2396 }
2397
2398 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2399 temp_sctp_dcs.swap(sctp_data_channels_);
2400 for (const auto& channel : temp_sctp_dcs) {
2401 channel->OnTransportChannelDestroyed();
2402 }
2403}
2404
2405void PeerConnection::OnDataChannelOpenMessage(
2406 const std::string& label,
2407 const InternalDataChannelInit& config) {
2408 rtc::scoped_refptr<DataChannel> channel(
2409 InternalCreateDataChannel(label, &config));
2410 if (!channel.get()) {
2411 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2412 return;
2413 }
2414
deadbeefa601f5c2016-06-06 14:27:39 -07002415 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2416 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002417 // Call both the raw pointer and scoped_refptr versions of the method
2418 // for compatibility.
2419 observer_->OnDataChannel(proxy_channel.get());
2420 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002421}
2422
deadbeefa601f5c2016-06-06 14:27:39 -07002423RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2424 auto it = std::find_if(
2425 senders_.begin(), senders_.end(),
2426 [id](const rtc::scoped_refptr<
2427 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2428 return sender->id() == id;
2429 });
2430 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002431}
2432
deadbeefa601f5c2016-06-06 14:27:39 -07002433std::vector<
2434 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002435PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2436 return std::find_if(
2437 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002438 [track](const rtc::scoped_refptr<
2439 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002440 return sender->track() == track;
2441 });
2442}
2443
deadbeefa601f5c2016-06-06 14:27:39 -07002444std::vector<rtc::scoped_refptr<
2445 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002446PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002447 return std::find_if(
2448 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002449 [track_id](const rtc::scoped_refptr<
2450 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002451 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002452 });
2453}
2454
deadbeefab9b2d12015-10-14 11:33:11 -07002455PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2456 cricket::MediaType media_type) {
2457 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2458 media_type == cricket::MEDIA_TYPE_VIDEO);
2459 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2460 : &remote_video_tracks_;
2461}
2462
2463PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2464 cricket::MediaType media_type) {
2465 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2466 media_type == cricket::MEDIA_TYPE_VIDEO);
2467 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2468 : &local_video_tracks_;
2469}
2470
2471const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2472 const PeerConnection::TrackInfos& infos,
2473 const std::string& stream_label,
2474 const std::string track_id) const {
2475 for (const TrackInfo& track_info : infos) {
2476 if (track_info.stream_label == stream_label &&
2477 track_info.track_id == track_id) {
2478 return &track_info;
2479 }
2480 }
2481 return nullptr;
2482}
2483
2484DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2485 for (const auto& channel : sctp_data_channels_) {
2486 if (channel->id() == sid) {
2487 return channel;
2488 }
2489 }
2490 return nullptr;
2491}
2492
deadbeef91dd5672016-05-18 16:55:30 -07002493bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002494 const RTCConfiguration& configuration) {
2495 cricket::ServerAddresses stun_servers;
2496 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002497 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2498 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002499 return false;
2500 }
2501
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002502 port_allocator_->Initialize();
2503
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002504 // To handle both internal and externally created port allocator, we will
2505 // enable BUNDLE here.
2506 int portallocator_flags = port_allocator_->flags();
2507 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2508 cricket::PORTALLOCATOR_ENABLE_IPV6;
2509 // If the disable-IPv6 flag was specified, we'll not override it
2510 // by experiment.
2511 if (configuration.disable_ipv6) {
2512 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002513 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2514 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002515 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2516 }
2517
2518 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2519 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2520 LOG(LS_INFO) << "TCP candidates are disabled.";
2521 }
2522
honghaiz60347052016-05-31 18:29:12 -07002523 if (configuration.candidate_network_policy ==
2524 kCandidateNetworkPolicyLowCost) {
2525 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2526 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2527 }
2528
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002529 port_allocator_->set_flags(portallocator_flags);
2530 // No step delay is used while allocating ports.
2531 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2532 port_allocator_->set_candidate_filter(
2533 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2534
2535 // Call this last since it may create pooled allocator sessions using the
2536 // properties set above.
2537 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002538 configuration.ice_candidate_pool_size,
2539 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002540 return true;
2541}
2542
deadbeef91dd5672016-05-18 16:55:30 -07002543bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002544 const cricket::ServerAddresses& stun_servers,
2545 const std::vector<cricket::RelayServerConfig>& turn_servers,
2546 IceTransportsType type,
2547 int candidate_pool_size,
2548 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002549 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002550 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002551 // Call this last since it may create pooled allocator sessions using the
2552 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002553 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002554 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002555}
2556
ivoc14d5dbe2016-07-04 07:06:55 -07002557bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2558 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002559 if (!event_log_) {
2560 return false;
2561 }
skvlad11a9cbf2016-10-07 11:53:05 -07002562 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002563}
2564
2565void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002566 if (event_log_) {
2567 event_log_->StopLogging();
2568 }
ivoc14d5dbe2016-07-04 07:06:55 -07002569}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570} // namespace webrtc