blob: 96e2b339a49d25faa32e449b2944c362b27c946a [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 -0800461static const char* const kRTCErrorTypeNames[] = {
deadbeef3edec7c2016-12-10 11:44:26 -0800462 "NONE",
463 "UNSUPPORTED_PARAMETER",
464 "INVALID_PARAMETER",
465 "INVALID_RANGE",
466 "SYNTAX_ERROR",
467 "INVALID_STATE",
468 "INVALID_MODIFICATION",
469 "NETWORK_ERROR",
470 "INTERNAL_ERROR",
471};
deadbeef293e9262017-01-11 12:28:30 -0800472static_assert(static_cast<int>(RTCErrorType::INTERNAL_ERROR) ==
473 (arraysize(kRTCErrorTypeNames) - 1),
474 "kRTCErrorTypeNames must have as many strings as RTCErrorType "
475 "has values.");
deadbeef3edec7c2016-12-10 11:44:26 -0800476
deadbeef293e9262017-01-11 12:28:30 -0800477std::ostream& operator<<(std::ostream& stream, RTCErrorType error) {
deadbeef3edec7c2016-12-10 11:44:26 -0800478 int index = static_cast<int>(error);
deadbeef293e9262017-01-11 12:28:30 -0800479 return stream << kRTCErrorTypeNames[index];
480}
481
482bool PeerConnectionInterface::RTCConfiguration::operator==(
483 const PeerConnectionInterface::RTCConfiguration& o) const {
484 // This static_assert prevents us from accidentally breaking operator==.
485 struct stuff_being_tested_for_equality {
486 IceTransportsType type;
487 IceServers servers;
488 BundlePolicy bundle_policy;
489 RtcpMuxPolicy rtcp_mux_policy;
490 TcpCandidatePolicy tcp_candidate_policy;
491 CandidateNetworkPolicy candidate_network_policy;
492 int audio_jitter_buffer_max_packets;
493 bool audio_jitter_buffer_fast_accelerate;
494 int ice_connection_receiving_timeout;
495 int ice_backup_candidate_pair_ping_interval;
496 ContinualGatheringPolicy continual_gathering_policy;
497 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
498 bool prioritize_most_likely_ice_candidate_pairs;
499 struct cricket::MediaConfig media_config;
500 bool disable_ipv6;
501 bool enable_rtp_data_channel;
502 bool enable_quic;
503 rtc::Optional<int> screencast_min_bitrate;
504 rtc::Optional<bool> combined_audio_video_bwe;
505 rtc::Optional<bool> enable_dtls_srtp;
506 int ice_candidate_pool_size;
507 bool prune_turn_ports;
508 bool presume_writable_when_fully_relayed;
509 bool enable_ice_renomination;
510 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800511 rtc::Optional<int> ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800512 };
513 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
514 "Did you add something to RTCConfiguration and forget to "
515 "update operator==?");
516 return type == o.type && servers == o.servers &&
517 bundle_policy == o.bundle_policy &&
518 rtcp_mux_policy == o.rtcp_mux_policy &&
519 tcp_candidate_policy == o.tcp_candidate_policy &&
520 candidate_network_policy == o.candidate_network_policy &&
521 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
522 audio_jitter_buffer_fast_accelerate ==
523 o.audio_jitter_buffer_fast_accelerate &&
524 ice_connection_receiving_timeout ==
525 o.ice_connection_receiving_timeout &&
526 ice_backup_candidate_pair_ping_interval ==
527 o.ice_backup_candidate_pair_ping_interval &&
528 continual_gathering_policy == o.continual_gathering_policy &&
529 certificates == o.certificates &&
530 prioritize_most_likely_ice_candidate_pairs ==
531 o.prioritize_most_likely_ice_candidate_pairs &&
532 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
533 enable_rtp_data_channel == o.enable_rtp_data_channel &&
534 enable_quic == o.enable_quic &&
535 screencast_min_bitrate == o.screencast_min_bitrate &&
536 combined_audio_video_bwe == o.combined_audio_video_bwe &&
537 enable_dtls_srtp == o.enable_dtls_srtp &&
538 ice_candidate_pool_size == o.ice_candidate_pool_size &&
539 prune_turn_ports == o.prune_turn_ports &&
540 presume_writable_when_fully_relayed ==
541 o.presume_writable_when_fully_relayed &&
542 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800543 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
544 ice_check_min_interval == o.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800545}
546
547bool PeerConnectionInterface::RTCConfiguration::operator!=(
548 const PeerConnectionInterface::RTCConfiguration& o) const {
549 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800550}
551
zhihuang8f65cdf2016-05-06 18:40:30 -0700552// Generate a RTCP CNAME when a PeerConnection is created.
553std::string GenerateRtcpCname() {
554 std::string cname;
555 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
556 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800557 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700558 }
559 return cname;
560}
561
htaa2a49d92016-03-04 02:51:39 -0800562bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700563 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800564 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700565 cricket::MediaSessionOptions* session_options) {
566 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
567 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
568 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
569 return false;
570 }
571
htaaac2dea2016-03-10 13:35:55 -0800572 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700573 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700574 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800575 } else {
576 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700577 }
htaaac2dea2016-03-10 13:35:55 -0800578 // For offers, we only offer video if we have it or it's forced by options.
579 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700580 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700581 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800582 } else if (is_offer) {
583 session_options->recv_video = false;
584 } else {
585 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700586 }
587
588 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700589 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800590 for (auto& kv : session_options->transport_options) {
591 kv.second.ice_restart = rtc_options.ice_restart;
592 }
deadbeefab9b2d12015-10-14 11:33:11 -0700593
594 return true;
595}
596
597bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
598 cricket::MediaSessionOptions* session_options) {
599 bool value = false;
600 size_t mandatory_constraints_satisfied = 0;
601
602 // kOfferToReceiveAudio defaults to true according to spec.
603 if (!FindConstraint(constraints,
604 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
605 &mandatory_constraints_satisfied) ||
606 value) {
607 session_options->recv_audio = true;
608 }
609
610 // kOfferToReceiveVideo defaults to false according to spec. But
611 // if it is an answer and video is offered, we should still accept video
612 // per default.
613 value = false;
614 if (!FindConstraint(constraints,
615 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
616 &mandatory_constraints_satisfied) ||
617 value) {
618 session_options->recv_video = true;
619 }
620
621 if (FindConstraint(constraints,
622 MediaConstraintsInterface::kVoiceActivityDetection, &value,
623 &mandatory_constraints_satisfied)) {
624 session_options->vad_enabled = value;
625 }
626
627 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
628 &mandatory_constraints_satisfied)) {
629 session_options->bundle_enabled = value;
630 } else {
631 // kUseRtpMux defaults to true according to spec.
632 session_options->bundle_enabled = true;
633 }
deadbeefab9b2d12015-10-14 11:33:11 -0700634
deadbeef0ed85b22016-02-23 17:24:52 -0800635 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700636 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
637 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700638 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800639 ice_restart = true;
640 }
641 for (auto& kv : session_options->transport_options) {
642 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700643 }
644
645 if (!constraints) {
646 return true;
647 }
648 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
649}
650
deadbeef293e9262017-01-11 12:28:30 -0800651RTCErrorType ParseIceServers(
652 const PeerConnectionInterface::IceServers& servers,
653 cricket::ServerAddresses* stun_servers,
654 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200655 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
656 if (!server.urls.empty()) {
657 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200658 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700659 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800660 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200661 }
deadbeef293e9262017-01-11 12:28:30 -0800662 RTCErrorType err =
663 ParseIceServerUrl(server, url, stun_servers, turn_servers);
664 if (err != RTCErrorType::NONE) {
665 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200666 }
667 }
668 } else if (!server.uri.empty()) {
669 // Fallback to old .uri if new .urls isn't present.
deadbeef293e9262017-01-11 12:28:30 -0800670 RTCErrorType err =
671 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
672 if (err != RTCErrorType::NONE) {
673 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200674 }
675 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700676 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800677 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678 }
679 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800680 // Candidates must have unique priorities, so that connectivity checks
681 // are performed in a well-defined order.
682 int priority = static_cast<int>(turn_servers->size() - 1);
683 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
684 // First in the list gets highest priority.
685 turn_server.priority = priority--;
686 }
deadbeef293e9262017-01-11 12:28:30 -0800687 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688}
689
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690PeerConnection::PeerConnection(PeerConnectionFactory* factory)
691 : factory_(factory),
692 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000693 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000694 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700696 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800697 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700698 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700699 local_streams_(StreamCollection::Create()),
700 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701
702PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100703 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700704 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700705 // Need to detach RTP senders/receivers from WebRtcSession,
706 // since it's about to be destroyed.
707 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700708 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700709 }
710 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700711 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700712 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700713 // Destroy stats_ because it depends on session_.
714 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800715 if (stats_collector_) {
716 stats_collector_->WaitForPendingRequest();
717 stats_collector_ = nullptr;
718 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700719 // Now destroy session_ before destroying other members,
720 // because its destruction fires signals (such as VoiceChannelDestroyed)
721 // which will trigger some final actions in PeerConnection...
722 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700723 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700724 network_thread()->Invoke<void>(RTC_FROM_HERE,
725 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726}
727
728bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000729 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700730 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200731 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800732 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100733 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800734 if (!allocator) {
735 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
736 << "This shouldn't happen if using PeerConnectionFactory.";
737 return false;
738 }
deadbeef653b8e02015-11-11 12:55:10 -0800739 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800740 // TODO(deadbeef): Why do we do this?
741 LOG(LS_ERROR) << "PeerConnection initialized without a "
742 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800743 return false;
744 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000745 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800746 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800747
deadbeef91dd5672016-05-18 16:55:30 -0700748 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700749 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700750 if (!network_thread()->Invoke<bool>(
751 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
752 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753 return false;
754 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000755
skvlad11a9cbf2016-10-07 11:53:05 -0700756 media_controller_.reset(factory_->CreateMediaController(
757 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758
zhihuang29ff8442016-07-27 11:07:25 -0700759 session_.reset(new WebRtcSession(
760 media_controller_.get(), factory_->network_thread(),
761 factory_->worker_thread(), factory_->signaling_thread(),
762 port_allocator_.get(),
763 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700764 factory_->CreateTransportController(
765 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800766 configuration.redetermine_role_on_ice_restart)),
767#ifdef HAVE_SCTP
768 std::unique_ptr<cricket::SctpTransportInternalFactory>(
769 new cricket::SctpTransportFactory(factory_->network_thread()))
770#else
771 nullptr
772#endif
773 ));
zhihuang29ff8442016-07-27 11:07:25 -0700774
deadbeefab9b2d12015-10-14 11:33:11 -0700775 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700776 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000777
778 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200779 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800780 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000781 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700782 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000784 // Register PeerConnection as receiver of local ice candidates.
785 // All the callbacks will be posted to the application from PeerConnection.
786 session_->RegisterIceObserver(this);
787 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700788 session_->SignalVoiceChannelCreated.connect(
789 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700790 session_->SignalVoiceChannelDestroyed.connect(
791 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700792 session_->SignalVideoChannelCreated.connect(
793 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700794 session_->SignalVideoChannelDestroyed.connect(
795 this, &PeerConnection::OnVideoChannelDestroyed);
796 session_->SignalDataChannelCreated.connect(
797 this, &PeerConnection::OnDataChannelCreated);
798 session_->SignalDataChannelDestroyed.connect(
799 this, &PeerConnection::OnDataChannelDestroyed);
800 session_->SignalDataChannelOpenMessage.connect(
801 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800802
803 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 return true;
805}
806
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000807rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700809 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810}
811
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000812rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700814 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000815}
816
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000817bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100818 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 if (IsClosed()) {
820 return false;
821 }
deadbeefab9b2d12015-10-14 11:33:11 -0700822 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 return false;
824 }
deadbeefab9b2d12015-10-14 11:33:11 -0700825
826 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800827 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
828 observer->SignalAudioTrackAdded.connect(this,
829 &PeerConnection::OnAudioTrackAdded);
830 observer->SignalAudioTrackRemoved.connect(
831 this, &PeerConnection::OnAudioTrackRemoved);
832 observer->SignalVideoTrackAdded.connect(this,
833 &PeerConnection::OnVideoTrackAdded);
834 observer->SignalVideoTrackRemoved.connect(
835 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700836 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700837
deadbeefab9b2d12015-10-14 11:33:11 -0700838 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800839 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700840 }
841 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800842 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700843 }
844
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000845 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 observer_->OnRenegotiationNeeded();
847 return true;
848}
849
850void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100851 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700852 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800853 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700854 }
855 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800856 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700857 }
858
859 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800860 stream_observers_.erase(
861 std::remove_if(
862 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700863 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800864 return observer->stream()->label().compare(local_stream->label()) ==
865 0;
866 }),
867 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700868
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869 if (IsClosed()) {
870 return;
871 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 observer_->OnRenegotiationNeeded();
873}
874
deadbeefe1f9d832016-01-14 15:35:42 -0800875rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
876 MediaStreamTrackInterface* track,
877 std::vector<MediaStreamInterface*> streams) {
878 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
879 if (IsClosed()) {
880 return nullptr;
881 }
882 if (streams.size() >= 2) {
883 LOG(LS_ERROR)
884 << "Adding a track with two streams is not currently supported.";
885 return nullptr;
886 }
887 // TODO(deadbeef): Support adding a track to two different senders.
888 if (FindSenderForTrack(track) != senders_.end()) {
889 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
890 return nullptr;
891 }
892
893 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700894 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800895 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700896 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800897 signaling_thread(),
898 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700899 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800900 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700901 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800902 }
903 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700904 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800905 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700906 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800907 }
908 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700909 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800910 signaling_thread(),
911 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700912 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800913 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700914 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800915 }
916 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700917 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800918 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700919 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800920 }
921 } else {
922 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
923 return rtc::scoped_refptr<RtpSenderInterface>();
924 }
925
926 senders_.push_back(new_sender);
927 observer_->OnRenegotiationNeeded();
928 return new_sender;
929}
930
931bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
932 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
933 if (IsClosed()) {
934 return false;
935 }
936
937 auto it = std::find(senders_.begin(), senders_.end(), sender);
938 if (it == senders_.end()) {
939 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
940 return false;
941 }
deadbeefa601f5c2016-06-06 14:27:39 -0700942 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800943 senders_.erase(it);
944
945 observer_->OnRenegotiationNeeded();
946 return true;
947}
948
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000949rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100951 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700952 if (IsClosed()) {
953 return nullptr;
954 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 if (!track) {
956 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800957 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958 }
deadbeef20cb0c12017-02-01 20:27:00 -0800959 auto it = FindSenderForTrack(track);
960 if (it == senders_.end()) {
961 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
962 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 }
964
deadbeef20cb0c12017-02-01 20:27:00 -0800965 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000966}
967
deadbeeffac06552015-11-25 11:26:01 -0800968rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800969 const std::string& kind,
970 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100971 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700972 if (IsClosed()) {
973 return nullptr;
974 }
deadbeefa601f5c2016-06-06 14:27:39 -0700975 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800976 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700977 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700978 signaling_thread(),
979 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800980 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700981 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700982 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800983 } else {
984 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800985 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800986 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800987 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700988 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800989 }
deadbeeffac06552015-11-25 11:26:01 -0800990 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800991 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800992}
993
deadbeef70ab1a12015-09-28 16:53:55 -0700994std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
995 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700996 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
997 for (const auto& sender : senders_) {
998 ret.push_back(sender.get());
999 }
1000 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001001}
1002
1003std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1004PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001005 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
1006 for (const auto& receiver : receivers_) {
1007 ret.push_back(receiver.get());
1008 }
1009 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001010}
1011
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001013 MediaStreamTrackInterface* track,
1014 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001015 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001016 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001017 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1019 return false;
1020 }
1021
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001022 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001023 // The StatsCollector is used to tell if a track is valid because it may
1024 // remember tracks that the PeerConnection previously removed.
1025 if (track && !stats_->IsValidTrack(track->id())) {
1026 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1027 << track->id();
1028 return false;
1029 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001030 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001031 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032 return true;
1033}
1034
hbos74e1a4f2016-09-15 23:33:01 -07001035void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1036 RTC_DCHECK(stats_collector_);
1037 stats_collector_->GetStatsReport(callback);
1038}
1039
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001040PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1041 return signaling_state_;
1042}
1043
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044PeerConnectionInterface::IceConnectionState
1045PeerConnection::ice_connection_state() {
1046 return ice_connection_state_;
1047}
1048
1049PeerConnectionInterface::IceGatheringState
1050PeerConnection::ice_gathering_state() {
1051 return ice_gathering_state_;
1052}
1053
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001054rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001055PeerConnection::CreateDataChannel(
1056 const std::string& label,
1057 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001058 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001059#ifdef HAVE_QUIC
1060 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1061 // TODO(zhihuang): Handle case when config is NULL.
1062 if (!config) {
1063 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1064 return nullptr;
1065 }
1066 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1067 if (!config->reliable || config->ordered) {
1068 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1069 "ordered delivery.";
1070 return nullptr;
1071 }
1072 return session_->quic_data_transport()->CreateDataChannel(label, config);
1073 }
1074#endif // HAVE_QUIC
1075
deadbeefab9b2d12015-10-14 11:33:11 -07001076 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001077
kwibergd1fe2812016-04-27 06:47:29 -07001078 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001079 if (config) {
1080 internal_config.reset(new InternalDataChannelInit(*config));
1081 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001082 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001083 InternalCreateDataChannel(label, internal_config.get()));
1084 if (!channel.get()) {
1085 return nullptr;
1086 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001087
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001088 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1089 // the first SCTP DataChannel.
1090 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1091 observer_->OnRenegotiationNeeded();
1092 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001093
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094 return DataChannelProxy::Create(signaling_thread(), channel.get());
1095}
1096
1097void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1098 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001099 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001100 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1102 return;
1103 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001104 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001105
1106 bool value;
1107 size_t mandatory_constraints = 0;
1108
1109 if (FindConstraint(constraints,
1110 MediaConstraintsInterface::kOfferToReceiveAudio,
1111 &value,
1112 &mandatory_constraints)) {
1113 options.offer_to_receive_audio =
1114 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1115 }
1116
1117 if (FindConstraint(constraints,
1118 MediaConstraintsInterface::kOfferToReceiveVideo,
1119 &value,
1120 &mandatory_constraints)) {
1121 options.offer_to_receive_video =
1122 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1123 }
1124
1125 if (FindConstraint(constraints,
1126 MediaConstraintsInterface::kVoiceActivityDetection,
1127 &value,
1128 &mandatory_constraints)) {
1129 options.voice_activity_detection = value;
1130 }
1131
1132 if (FindConstraint(constraints,
1133 MediaConstraintsInterface::kIceRestart,
1134 &value,
1135 &mandatory_constraints)) {
1136 options.ice_restart = value;
1137 }
1138
1139 if (FindConstraint(constraints,
1140 MediaConstraintsInterface::kUseRtpMux,
1141 &value,
1142 &mandatory_constraints)) {
1143 options.use_rtp_mux = value;
1144 }
1145
1146 CreateOffer(observer, options);
1147}
1148
1149void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1150 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001151 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001152 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001153 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1154 return;
1155 }
deadbeefab9b2d12015-10-14 11:33:11 -07001156
1157 cricket::MediaSessionOptions session_options;
1158 if (!GetOptionsForOffer(options, &session_options)) {
1159 std::string error = "CreateOffer called with invalid options.";
1160 LOG(LS_ERROR) << error;
1161 PostCreateSessionDescriptionFailure(observer, error);
1162 return;
1163 }
1164
1165 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001166}
1167
1168void PeerConnection::CreateAnswer(
1169 CreateSessionDescriptionObserver* observer,
1170 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001171 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001172 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1174 return;
1175 }
deadbeefab9b2d12015-10-14 11:33:11 -07001176
1177 cricket::MediaSessionOptions session_options;
1178 if (!GetOptionsForAnswer(constraints, &session_options)) {
1179 std::string error = "CreateAnswer called with invalid constraints.";
1180 LOG(LS_ERROR) << error;
1181 PostCreateSessionDescriptionFailure(observer, error);
1182 return;
1183 }
1184
htaa2a49d92016-03-04 02:51:39 -08001185 session_->CreateAnswer(observer, session_options);
1186}
1187
1188void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1189 const RTCOfferAnswerOptions& options) {
1190 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001191 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -08001192 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1193 return;
1194 }
1195
1196 cricket::MediaSessionOptions session_options;
1197 if (!GetOptionsForAnswer(options, &session_options)) {
1198 std::string error = "CreateAnswer called with invalid options.";
1199 LOG(LS_ERROR) << error;
1200 PostCreateSessionDescriptionFailure(observer, error);
1201 return;
1202 }
1203
1204 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001205}
1206
1207void PeerConnection::SetLocalDescription(
1208 SetSessionDescriptionObserver* observer,
1209 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001210 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001211 if (IsClosed()) {
1212 return;
1213 }
nisse7ce109a2017-01-31 00:57:56 -08001214 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001215 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1216 return;
1217 }
1218 if (!desc) {
1219 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1220 return;
1221 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222 // Update stats here so that we have the most recent stats for tracks and
1223 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001224 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001225 std::string error;
1226 if (!session_->SetLocalDescription(desc, &error)) {
1227 PostSetSessionDescriptionFailure(observer, error);
1228 return;
1229 }
deadbeefab9b2d12015-10-14 11:33:11 -07001230
1231 // If setting the description decided our SSL role, allocate any necessary
1232 // SCTP sids.
1233 rtc::SSLRole role;
1234 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001235 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001236 AllocateSctpSids(role);
1237 }
1238
1239 // Update state and SSRC of local MediaStreams and DataChannels based on the
1240 // local session description.
1241 const cricket::ContentInfo* audio_content =
1242 GetFirstAudioContent(desc->description());
1243 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001244 if (audio_content->rejected) {
1245 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1246 } else {
1247 const cricket::AudioContentDescription* audio_desc =
1248 static_cast<const cricket::AudioContentDescription*>(
1249 audio_content->description);
1250 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1251 }
deadbeefab9b2d12015-10-14 11:33:11 -07001252 }
1253
1254 const cricket::ContentInfo* video_content =
1255 GetFirstVideoContent(desc->description());
1256 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001257 if (video_content->rejected) {
1258 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1259 } else {
1260 const cricket::VideoContentDescription* video_desc =
1261 static_cast<const cricket::VideoContentDescription*>(
1262 video_content->description);
1263 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1264 }
deadbeefab9b2d12015-10-14 11:33:11 -07001265 }
1266
1267 const cricket::ContentInfo* data_content =
1268 GetFirstDataContent(desc->description());
1269 if (data_content) {
1270 const cricket::DataContentDescription* data_desc =
1271 static_cast<const cricket::DataContentDescription*>(
1272 data_content->description);
1273 if (rtc::starts_with(data_desc->protocol().data(),
1274 cricket::kMediaProtocolRtpPrefix)) {
1275 UpdateLocalRtpDataChannels(data_desc->streams());
1276 }
1277 }
1278
1279 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001280 signaling_thread()->Post(RTC_FROM_HERE, this,
1281 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001282
deadbeefcbecd352015-09-23 11:50:27 -07001283 // MaybeStartGathering needs to be called after posting
1284 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1285 // before signaling that SetLocalDescription completed.
1286 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287}
1288
1289void PeerConnection::SetRemoteDescription(
1290 SetSessionDescriptionObserver* observer,
1291 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001292 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001293 if (IsClosed()) {
1294 return;
1295 }
nisse7ce109a2017-01-31 00:57:56 -08001296 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1298 return;
1299 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300 if (!desc) {
1301 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1302 return;
1303 }
1304 // Update stats here so that we have the most recent stats for tracks and
1305 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001306 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 std::string error;
1308 if (!session_->SetRemoteDescription(desc, &error)) {
1309 PostSetSessionDescriptionFailure(observer, error);
1310 return;
1311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312
deadbeefab9b2d12015-10-14 11:33:11 -07001313 // If setting the description decided our SSL role, allocate any necessary
1314 // SCTP sids.
1315 rtc::SSLRole role;
1316 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001317 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001318 AllocateSctpSids(role);
1319 }
1320
1321 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001322 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1323 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1324 const cricket::AudioContentDescription* audio_desc =
1325 GetFirstAudioContentDescription(remote_desc);
1326 const cricket::VideoContentDescription* video_desc =
1327 GetFirstVideoContentDescription(remote_desc);
1328 const cricket::DataContentDescription* data_desc =
1329 GetFirstDataContentDescription(remote_desc);
1330
1331 // Check if the descriptions include streams, just in case the peer supports
1332 // MSID, but doesn't indicate so with "a=msid-semantic".
1333 if (remote_desc->msid_supported() ||
1334 (audio_desc && !audio_desc->streams().empty()) ||
1335 (video_desc && !video_desc->streams().empty())) {
1336 remote_peer_supports_msid_ = true;
1337 }
deadbeefab9b2d12015-10-14 11:33:11 -07001338
1339 // We wait to signal new streams until we finish processing the description,
1340 // since only at that point will new streams have all their tracks.
1341 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1342
1343 // Find all audio rtp streams and create corresponding remote AudioTracks
1344 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001345 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001346 if (audio_content->rejected) {
1347 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1348 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001349 bool default_audio_track_needed =
1350 !remote_peer_supports_msid_ &&
1351 MediaContentDirectionHasSend(audio_desc->direction());
1352 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1353 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001354 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001355 }
deadbeefab9b2d12015-10-14 11:33:11 -07001356 }
1357
1358 // Find all video rtp streams and create corresponding remote VideoTracks
1359 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001360 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001361 if (video_content->rejected) {
1362 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1363 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001364 bool default_video_track_needed =
1365 !remote_peer_supports_msid_ &&
1366 MediaContentDirectionHasSend(video_desc->direction());
1367 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1368 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001369 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001370 }
deadbeefab9b2d12015-10-14 11:33:11 -07001371 }
1372
1373 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001374 if (data_desc) {
1375 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001376 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001377 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001378 }
1379 }
1380
1381 // Iterate new_streams and notify the observer about new MediaStreams.
1382 for (size_t i = 0; i < new_streams->count(); ++i) {
1383 MediaStreamInterface* new_stream = new_streams->at(i);
1384 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001385 // Call both the raw pointer and scoped_refptr versions of the method
1386 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001387 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001388 observer_->OnAddStream(
1389 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001390 }
1391
deadbeefbda7e0b2015-12-08 17:13:40 -08001392 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001393
1394 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001395 signaling_thread()->Post(RTC_FROM_HERE, this,
1396 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001397}
1398
deadbeef46c73892016-11-16 19:42:04 -08001399PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1400 return configuration_;
1401}
1402
deadbeef293e9262017-01-11 12:28:30 -08001403bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1404 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001405 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001406
1407 if (session_->local_description() &&
1408 configuration.ice_candidate_pool_size !=
1409 configuration_.ice_candidate_pool_size) {
1410 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1411 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001412 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001413 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001414
deadbeef293e9262017-01-11 12:28:30 -08001415 // The simplest (and most future-compatible) way to tell if the config was
1416 // modified in an invalid way is to copy each property we do support
1417 // modifying, then use operator==. There are far more properties we don't
1418 // support modifying than those we do, and more could be added.
1419 RTCConfiguration modified_config = configuration_;
1420 modified_config.servers = configuration.servers;
1421 modified_config.type = configuration.type;
1422 modified_config.ice_candidate_pool_size =
1423 configuration.ice_candidate_pool_size;
1424 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001425 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001426 if (configuration != modified_config) {
1427 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1428 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1429 }
1430
1431 // Note that this isn't possible through chromium, since it's an unsigned
1432 // short in WebIDL.
1433 if (configuration.ice_candidate_pool_size < 0 ||
1434 configuration.ice_candidate_pool_size > UINT16_MAX) {
1435 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1436 }
1437
1438 // Parse ICE servers before hopping to network thread.
1439 cricket::ServerAddresses stun_servers;
1440 std::vector<cricket::RelayServerConfig> turn_servers;
1441 RTCErrorType parse_error =
1442 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1443 if (parse_error != RTCErrorType::NONE) {
1444 return SafeSetError(parse_error, error);
1445 }
1446
1447 // In theory this shouldn't fail.
1448 if (!network_thread()->Invoke<bool>(
1449 RTC_FROM_HERE,
1450 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1451 stun_servers, turn_servers, modified_config.type,
1452 modified_config.ice_candidate_pool_size,
1453 modified_config.prune_turn_ports))) {
1454 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1455 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1456 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001457
deadbeefd1a38b52016-12-10 13:15:33 -08001458 // As described in JSEP, calling setConfiguration with new ICE servers or
1459 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1460 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001461 if (modified_config.servers != configuration_.servers ||
1462 modified_config.type != configuration_.type ||
1463 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001464 session_->SetNeedsIceRestartFlag();
1465 }
skvladd1f5fda2017-02-03 16:54:05 -08001466
1467 if (modified_config.ice_check_min_interval !=
1468 configuration_.ice_check_min_interval) {
1469 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1470 }
1471
deadbeef293e9262017-01-11 12:28:30 -08001472 configuration_ = modified_config;
1473 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001474}
1475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476bool PeerConnection::AddIceCandidate(
1477 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001478 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001479 if (IsClosed()) {
1480 return false;
1481 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001482 return session_->ProcessIceMessage(ice_candidate);
1483}
1484
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001485bool PeerConnection::RemoveIceCandidates(
1486 const std::vector<cricket::Candidate>& candidates) {
1487 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1488 return session_->RemoveRemoteIceCandidates(candidates);
1489}
1490
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001491void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001492 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001493 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001494
1495 if (session_) {
1496 session_->set_metrics_observer(uma_observer_);
1497 }
1498
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001499 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001500 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001501 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001502 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001503 uma_observer_->IncrementEnumCounter(
1504 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1505 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001506 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001507 uma_observer_->IncrementEnumCounter(
1508 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1509 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001510 }
1511 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001512}
1513
ivoc14d5dbe2016-07-04 07:06:55 -07001514bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1515 int64_t max_size_bytes) {
1516 return factory_->worker_thread()->Invoke<bool>(
1517 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1518 max_size_bytes));
1519}
1520
1521void PeerConnection::StopRtcEventLog() {
1522 factory_->worker_thread()->Invoke<void>(
1523 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1524}
1525
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526const SessionDescriptionInterface* PeerConnection::local_description() const {
1527 return session_->local_description();
1528}
1529
1530const SessionDescriptionInterface* PeerConnection::remote_description() const {
1531 return session_->remote_description();
1532}
1533
deadbeeffe4a8a42016-12-20 17:56:17 -08001534const SessionDescriptionInterface* PeerConnection::current_local_description()
1535 const {
1536 return session_->current_local_description();
1537}
1538
1539const SessionDescriptionInterface* PeerConnection::current_remote_description()
1540 const {
1541 return session_->current_remote_description();
1542}
1543
1544const SessionDescriptionInterface* PeerConnection::pending_local_description()
1545 const {
1546 return session_->pending_local_description();
1547}
1548
1549const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1550 const {
1551 return session_->pending_remote_description();
1552}
1553
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001555 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556 // Update stats here so that we have the most recent stats for tracks and
1557 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001558 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559
deadbeefd59daf82015-10-14 15:02:44 -07001560 session_->Close();
zhihuang77985012017-02-07 15:45:16 -08001561 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562}
1563
deadbeefd59daf82015-10-14 15:02:44 -07001564void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1565 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001567 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001569 break;
deadbeefd59daf82015-10-14 15:02:44 -07001570 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1572 break;
deadbeefd59daf82015-10-14 15:02:44 -07001573 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1575 break;
deadbeefd59daf82015-10-14 15:02:44 -07001576 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001577 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1578 break;
deadbeefd59daf82015-10-14 15:02:44 -07001579 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1581 break;
deadbeefd59daf82015-10-14 15:02:44 -07001582 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583 ChangeSignalingState(PeerConnectionInterface::kStable);
1584 break;
deadbeefd59daf82015-10-14 15:02:44 -07001585 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 ChangeSignalingState(PeerConnectionInterface::kClosed);
1587 break;
1588 default:
1589 break;
1590 }
1591}
1592
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001593void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001594 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001595 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1596 SetSessionDescriptionMsg* param =
1597 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1598 param->observer->OnSuccess();
1599 delete param;
1600 break;
1601 }
1602 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1603 SetSessionDescriptionMsg* param =
1604 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1605 param->observer->OnFailure(param->error);
1606 delete param;
1607 break;
1608 }
deadbeefab9b2d12015-10-14 11:33:11 -07001609 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1610 CreateSessionDescriptionMsg* param =
1611 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1612 param->observer->OnFailure(param->error);
1613 delete param;
1614 break;
1615 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001616 case MSG_GETSTATS: {
1617 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001618 StatsReports reports;
1619 stats_->GetStats(param->track, &reports);
1620 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 delete param;
1622 break;
1623 }
deadbeefbd292462015-12-14 18:15:29 -08001624 case MSG_FREE_DATACHANNELS: {
1625 sctp_data_channels_to_free_.clear();
1626 break;
1627 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001628 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001629 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630 break;
1631 }
1632}
1633
deadbeefab9b2d12015-10-14 11:33:11 -07001634void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001635 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001636 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001637 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1638 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001639 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001640 session_->voice_channel()));
1641
1642 receivers_.push_back(receiver);
1643 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1644 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1645 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001646}
1647
deadbeefab9b2d12015-10-14 11:33:11 -07001648void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001649 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001650 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001651 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1652 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001653 signaling_thread(),
1654 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001655 ssrc, session_->video_channel()));
1656 receivers_.push_back(receiver);
1657 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1658 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1659 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001660}
1661
deadbeef70ab1a12015-09-28 16:53:55 -07001662// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1663// description.
perkjd61bf802016-03-24 03:16:19 -07001664void PeerConnection::DestroyReceiver(const std::string& track_id) {
1665 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001666 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001667 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001668 << " doesn't exist.";
1669 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001670 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001671 receivers_.erase(it);
1672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001673}
1674
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001675void PeerConnection::OnIceConnectionChange(
1676 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001677 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001678 // After transitioning to "closed", ignore any additional states from
1679 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001680 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001681 return;
1682 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001684 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685}
1686
1687void PeerConnection::OnIceGatheringChange(
1688 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001689 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690 if (IsClosed()) {
1691 return;
1692 }
1693 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001694 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695}
1696
1697void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001698 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001699 if (IsClosed()) {
1700 return;
1701 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001702 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001703}
1704
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001705void PeerConnection::OnIceCandidatesRemoved(
1706 const std::vector<cricket::Candidate>& candidates) {
1707 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001708 if (IsClosed()) {
1709 return;
1710 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001711 observer_->OnIceCandidatesRemoved(candidates);
1712}
1713
Peter Thatcher54360512015-07-08 11:08:35 -07001714void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001715 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001716 if (IsClosed()) {
1717 return;
1718 }
Peter Thatcher54360512015-07-08 11:08:35 -07001719 observer_->OnIceConnectionReceivingChange(receiving);
1720}
1721
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722void PeerConnection::ChangeSignalingState(
1723 PeerConnectionInterface::SignalingState signaling_state) {
1724 signaling_state_ = signaling_state;
1725 if (signaling_state == kClosed) {
1726 ice_connection_state_ = kIceConnectionClosed;
1727 observer_->OnIceConnectionChange(ice_connection_state_);
1728 if (ice_gathering_state_ != kIceGatheringComplete) {
1729 ice_gathering_state_ = kIceGatheringComplete;
1730 observer_->OnIceGatheringChange(ice_gathering_state_);
1731 }
1732 }
1733 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734}
1735
deadbeefeb459812015-12-15 19:24:43 -08001736void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1737 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001738 if (IsClosed()) {
1739 return;
1740 }
deadbeefeb459812015-12-15 19:24:43 -08001741 auto sender = FindSenderForTrack(track);
1742 if (sender != senders_.end()) {
1743 // We already have a sender for this track, so just change the stream_id
1744 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001745 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001746 return;
1747 }
1748
1749 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001750 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1751 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001752 signaling_thread(),
1753 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1754 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001755 senders_.push_back(new_sender);
1756 // If the sender has already been configured in SDP, we call SetSsrc,
1757 // which will connect the sender to the underlying transport. This can
1758 // occur if a local session description that contains the ID of the sender
1759 // is set before AddStream is called. It can also occur if the local
1760 // session description is not changed and RemoveStream is called, and
1761 // later AddStream is called again with the same stream.
1762 const TrackInfo* track_info =
1763 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1764 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001765 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001766 }
1767}
1768
1769// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1770// indefinitely, when we have unified plan SDP.
1771void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1772 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001773 if (IsClosed()) {
1774 return;
1775 }
deadbeefeb459812015-12-15 19:24:43 -08001776 auto sender = FindSenderForTrack(track);
1777 if (sender == senders_.end()) {
1778 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1779 << " doesn't exist.";
1780 return;
1781 }
deadbeefa601f5c2016-06-06 14:27:39 -07001782 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001783 senders_.erase(sender);
1784}
1785
1786void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1787 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001788 if (IsClosed()) {
1789 return;
1790 }
deadbeefeb459812015-12-15 19:24:43 -08001791 auto sender = FindSenderForTrack(track);
1792 if (sender != senders_.end()) {
1793 // We already have a sender for this track, so just change the stream_id
1794 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001795 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001796 return;
1797 }
1798
1799 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001800 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1801 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001802 signaling_thread(), new VideoRtpSender(track, stream->label(),
1803 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001804 senders_.push_back(new_sender);
1805 const TrackInfo* track_info =
1806 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1807 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001808 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001809 }
1810}
1811
1812void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1813 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001814 if (IsClosed()) {
1815 return;
1816 }
deadbeefeb459812015-12-15 19:24:43 -08001817 auto sender = FindSenderForTrack(track);
1818 if (sender == senders_.end()) {
1819 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1820 << " doesn't exist.";
1821 return;
1822 }
deadbeefa601f5c2016-06-06 14:27:39 -07001823 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001824 senders_.erase(sender);
1825}
1826
deadbeefab9b2d12015-10-14 11:33:11 -07001827void PeerConnection::PostSetSessionDescriptionFailure(
1828 SetSessionDescriptionObserver* observer,
1829 const std::string& error) {
1830 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1831 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001832 signaling_thread()->Post(RTC_FROM_HERE, this,
1833 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001834}
1835
1836void PeerConnection::PostCreateSessionDescriptionFailure(
1837 CreateSessionDescriptionObserver* observer,
1838 const std::string& error) {
1839 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1840 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001841 signaling_thread()->Post(RTC_FROM_HERE, this,
1842 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001843}
1844
1845bool PeerConnection::GetOptionsForOffer(
1846 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1847 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001848 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1849 // ContentInfos.
1850 if (session_->local_description()) {
1851 for (const cricket::ContentInfo& content :
1852 session_->local_description()->description()->contents()) {
1853 session_options->transport_options[content.name] =
1854 cricket::TransportOptions();
1855 }
1856 }
deadbeef46c73892016-11-16 19:42:04 -08001857 session_options->enable_ice_renomination =
1858 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001859
htaaac2dea2016-03-10 13:35:55 -08001860 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001861 return false;
1862 }
1863
deadbeeffac06552015-11-25 11:26:01 -08001864 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001865 // Offer to receive audio/video if the constraint is not set and there are
1866 // send streams, or we're currently receiving.
1867 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1868 session_options->recv_audio =
1869 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1870 !remote_audio_tracks_.empty();
1871 }
1872 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1873 session_options->recv_video =
1874 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1875 !remote_video_tracks_.empty();
1876 }
deadbeefc80741f2015-10-22 13:14:45 -07001877
zhihuang9763d562016-08-05 11:14:50 -07001878 // Intentionally unset the data channel type for RTP data channel with the
1879 // second condition. Otherwise the RTP data channels would be successfully
1880 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1881 // when building with chromium. We want to leave RTP data channels broken, so
1882 // people won't try to use them.
1883 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1884 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001885 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001886
zhihuangaf388472016-11-02 16:49:48 -07001887 session_options->bundle_enabled =
1888 session_options->bundle_enabled &&
1889 (session_options->has_audio() || session_options->has_video() ||
1890 session_options->has_data());
1891
zhihuang8f65cdf2016-05-06 18:40:30 -07001892 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001893 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001894 return true;
1895}
1896
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001897void PeerConnection::InitializeOptionsForAnswer(
1898 cricket::MediaSessionOptions* session_options) {
1899 session_options->recv_audio = false;
1900 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001901 session_options->enable_ice_renomination =
1902 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001903}
1904
htaa2a49d92016-03-04 02:51:39 -08001905void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001906 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001907 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1908 // ContentInfos.
1909 if (session_->remote_description()) {
1910 // Initialize the transport_options map.
1911 for (const cricket::ContentInfo& content :
1912 session_->remote_description()->description()->contents()) {
1913 session_options->transport_options[content.name] =
1914 cricket::TransportOptions();
1915 }
1916 }
deadbeeffac06552015-11-25 11:26:01 -08001917 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001918 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1919 // are not signaled in the SDP so does not go through that path and must be
1920 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001921 // Intentionally unset the data channel type for RTP data channel. Otherwise
1922 // the RTP data channels would be successfully negotiated by default and the
1923 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1924 // We want to leave RTP data channels broken, so people won't try to use them.
1925 if (session_->data_channel_type() != cricket::DCT_RTP) {
1926 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001927 }
zhihuangaf388472016-11-02 16:49:48 -07001928 session_options->bundle_enabled =
1929 session_options->bundle_enabled &&
1930 (session_options->has_audio() || session_options->has_video() ||
1931 session_options->has_data());
1932
jbauchcb560652016-08-04 05:20:32 -07001933 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001934}
1935
1936bool PeerConnection::GetOptionsForAnswer(
1937 const MediaConstraintsInterface* constraints,
1938 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001939 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001940 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1941 return false;
1942 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001943 session_options->rtcp_cname = rtcp_cname_;
1944
htaa2a49d92016-03-04 02:51:39 -08001945 FinishOptionsForAnswer(session_options);
1946 return true;
1947}
1948
1949bool PeerConnection::GetOptionsForAnswer(
1950 const RTCOfferAnswerOptions& options,
1951 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001952 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001953 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001954 return false;
1955 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001956 session_options->rtcp_cname = rtcp_cname_;
1957
htaa2a49d92016-03-04 02:51:39 -08001958 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001959 return true;
1960}
1961
deadbeeffaac4972015-11-12 15:33:07 -08001962void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1963 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001964 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1965 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001966}
1967
deadbeefab9b2d12015-10-14 11:33:11 -07001968void PeerConnection::UpdateRemoteStreamsList(
1969 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001970 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001971 cricket::MediaType media_type,
1972 StreamCollection* new_streams) {
1973 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1974
1975 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001976 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001977 auto track_it = current_tracks->begin();
1978 while (track_it != current_tracks->end()) {
1979 const TrackInfo& info = *track_it;
1980 const cricket::StreamParams* params =
1981 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001982 bool track_exists = params && params->id == info.track_id;
1983 // If this is a default track, and we still need it, don't remove it.
1984 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1985 track_exists) {
1986 ++track_it;
1987 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001988 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1989 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001990 }
1991 }
1992
1993 // Find new and active tracks.
1994 for (const cricket::StreamParams& params : streams) {
1995 // The sync_label is the MediaStream label and the |stream.id| is the
1996 // track id.
1997 const std::string& stream_label = params.sync_label;
1998 const std::string& track_id = params.id;
1999 uint32_t ssrc = params.first_ssrc();
2000
2001 rtc::scoped_refptr<MediaStreamInterface> stream =
2002 remote_streams_->find(stream_label);
2003 if (!stream) {
2004 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002005 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2006 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002007 remote_streams_->AddStream(stream);
2008 new_streams->AddStream(stream);
2009 }
2010
2011 const TrackInfo* track_info =
2012 FindTrackInfo(*current_tracks, stream_label, track_id);
2013 if (!track_info) {
2014 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2015 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2016 }
2017 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002018
2019 // Add default track if necessary.
2020 if (default_track_needed) {
2021 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2022 remote_streams_->find(kDefaultStreamLabel);
2023 if (!default_stream) {
2024 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002025 default_stream = MediaStreamProxy::Create(
2026 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002027 remote_streams_->AddStream(default_stream);
2028 new_streams->AddStream(default_stream);
2029 }
2030 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2031 ? kDefaultAudioTrackLabel
2032 : kDefaultVideoTrackLabel;
2033 const TrackInfo* default_track_info =
2034 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2035 if (!default_track_info) {
2036 current_tracks->push_back(
2037 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2038 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2039 }
2040 }
deadbeefab9b2d12015-10-14 11:33:11 -07002041}
2042
2043void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2044 const std::string& track_id,
2045 uint32_t ssrc,
2046 cricket::MediaType media_type) {
2047 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2048
2049 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002050 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002051 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002052 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002053 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002054 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002055 }
2056}
2057
2058void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2059 const std::string& track_id,
2060 cricket::MediaType media_type) {
2061 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2062
2063 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002064 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2065 // will be notified which will end the AudioRtpReceiver::track().
2066 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002067 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2068 stream->FindAudioTrack(track_id);
2069 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002070 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002071 }
2072 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002073 // Stopping or destroying a VideoRtpReceiver will end the
2074 // VideoRtpReceiver::track().
2075 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002076 rtc::scoped_refptr<VideoTrackInterface> video_track =
2077 stream->FindVideoTrack(track_id);
2078 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002079 // There's no guarantee the track is still available, e.g. the track may
2080 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002081 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002082 }
2083 } else {
nisseede5da42017-01-12 05:15:36 -08002084 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002085 }
2086}
2087
2088void PeerConnection::UpdateEndedRemoteMediaStreams() {
2089 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2090 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2091 MediaStreamInterface* stream = remote_streams_->at(i);
2092 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2093 streams_to_remove.push_back(stream);
2094 }
2095 }
2096
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002097 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002098 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002099 // Call both the raw pointer and scoped_refptr versions of the method
2100 // for compatibility.
2101 observer_->OnRemoveStream(stream.get());
2102 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002103 }
2104}
2105
deadbeefab9b2d12015-10-14 11:33:11 -07002106void PeerConnection::UpdateLocalTracks(
2107 const std::vector<cricket::StreamParams>& streams,
2108 cricket::MediaType media_type) {
2109 TrackInfos* current_tracks = GetLocalTracks(media_type);
2110
2111 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2112 // don't match the new StreamParam.
2113 TrackInfos::iterator track_it = current_tracks->begin();
2114 while (track_it != current_tracks->end()) {
2115 const TrackInfo& info = *track_it;
2116 const cricket::StreamParams* params =
2117 cricket::GetStreamBySsrc(streams, info.ssrc);
2118 if (!params || params->id != info.track_id ||
2119 params->sync_label != info.stream_label) {
2120 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2121 media_type);
2122 track_it = current_tracks->erase(track_it);
2123 } else {
2124 ++track_it;
2125 }
2126 }
2127
2128 // Find new and active tracks.
2129 for (const cricket::StreamParams& params : streams) {
2130 // The sync_label is the MediaStream label and the |stream.id| is the
2131 // track id.
2132 const std::string& stream_label = params.sync_label;
2133 const std::string& track_id = params.id;
2134 uint32_t ssrc = params.first_ssrc();
2135 const TrackInfo* track_info =
2136 FindTrackInfo(*current_tracks, stream_label, track_id);
2137 if (!track_info) {
2138 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2139 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2140 }
2141 }
2142}
2143
2144void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2145 const std::string& track_id,
2146 uint32_t ssrc,
2147 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002148 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002149 if (!sender) {
2150 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2151 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002152 return;
2153 }
2154
deadbeeffac06552015-11-25 11:26:01 -08002155 if (sender->media_type() != media_type) {
2156 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2157 << " description with an unexpected media type.";
2158 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002159 }
deadbeeffac06552015-11-25 11:26:01 -08002160
2161 sender->set_stream_id(stream_label);
2162 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002163}
2164
2165void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2166 const std::string& track_id,
2167 uint32_t ssrc,
2168 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002169 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002170 if (!sender) {
2171 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002172 // SessionDescriptions has been renegotiated.
2173 return;
2174 }
deadbeeffac06552015-11-25 11:26:01 -08002175
2176 // A sender has been removed from the SessionDescription but it's still
2177 // associated with the PeerConnection. This only occurs if the SDP doesn't
2178 // match with the calls to CreateSender, AddStream and RemoveStream.
2179 if (sender->media_type() != media_type) {
2180 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2181 << " description with an unexpected media type.";
2182 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002183 }
deadbeeffac06552015-11-25 11:26:01 -08002184
2185 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002186}
2187
2188void PeerConnection::UpdateLocalRtpDataChannels(
2189 const cricket::StreamParamsVec& streams) {
2190 std::vector<std::string> existing_channels;
2191
2192 // Find new and active data channels.
2193 for (const cricket::StreamParams& params : streams) {
2194 // |it->sync_label| is actually the data channel label. The reason is that
2195 // we use the same naming of data channels as we do for
2196 // MediaStreams and Tracks.
2197 // For MediaStreams, the sync_label is the MediaStream label and the
2198 // track label is the same as |streamid|.
2199 const std::string& channel_label = params.sync_label;
2200 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002201 if (data_channel_it == rtp_data_channels_.end()) {
2202 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002203 continue;
2204 }
2205 // Set the SSRC the data channel should use for sending.
2206 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2207 existing_channels.push_back(data_channel_it->first);
2208 }
2209
2210 UpdateClosingRtpDataChannels(existing_channels, true);
2211}
2212
2213void PeerConnection::UpdateRemoteRtpDataChannels(
2214 const cricket::StreamParamsVec& streams) {
2215 std::vector<std::string> existing_channels;
2216
2217 // Find new and active data channels.
2218 for (const cricket::StreamParams& params : streams) {
2219 // The data channel label is either the mslabel or the SSRC if the mslabel
2220 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2221 std::string label = params.sync_label.empty()
2222 ? rtc::ToString(params.first_ssrc())
2223 : params.sync_label;
2224 auto data_channel_it = rtp_data_channels_.find(label);
2225 if (data_channel_it == rtp_data_channels_.end()) {
2226 // This is a new data channel.
2227 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2228 } else {
2229 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2230 }
2231 existing_channels.push_back(label);
2232 }
2233
2234 UpdateClosingRtpDataChannels(existing_channels, false);
2235}
2236
2237void PeerConnection::UpdateClosingRtpDataChannels(
2238 const std::vector<std::string>& active_channels,
2239 bool is_local_update) {
2240 auto it = rtp_data_channels_.begin();
2241 while (it != rtp_data_channels_.end()) {
2242 DataChannel* data_channel = it->second;
2243 if (std::find(active_channels.begin(), active_channels.end(),
2244 data_channel->label()) != active_channels.end()) {
2245 ++it;
2246 continue;
2247 }
2248
2249 if (is_local_update) {
2250 data_channel->SetSendSsrc(0);
2251 } else {
2252 data_channel->RemotePeerRequestClose();
2253 }
2254
2255 if (data_channel->state() == DataChannel::kClosed) {
2256 rtp_data_channels_.erase(it);
2257 it = rtp_data_channels_.begin();
2258 } else {
2259 ++it;
2260 }
2261 }
2262}
2263
2264void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2265 uint32_t remote_ssrc) {
2266 rtc::scoped_refptr<DataChannel> channel(
2267 InternalCreateDataChannel(label, nullptr));
2268 if (!channel.get()) {
2269 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2270 << "CreateDataChannel failed.";
2271 return;
2272 }
2273 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002274 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2275 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002276 // Call both the raw pointer and scoped_refptr versions of the method
2277 // for compatibility.
2278 observer_->OnDataChannel(proxy_channel.get());
2279 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002280}
2281
2282rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2283 const std::string& label,
2284 const InternalDataChannelInit* config) {
2285 if (IsClosed()) {
2286 return nullptr;
2287 }
2288 if (session_->data_channel_type() == cricket::DCT_NONE) {
2289 LOG(LS_ERROR)
2290 << "InternalCreateDataChannel: Data is not supported in this call.";
2291 return nullptr;
2292 }
2293 InternalDataChannelInit new_config =
2294 config ? (*config) : InternalDataChannelInit();
2295 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2296 if (new_config.id < 0) {
2297 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002298 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002299 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2300 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2301 return nullptr;
2302 }
2303 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2304 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2305 << "because the id is already in use or out of range.";
2306 return nullptr;
2307 }
2308 }
2309
2310 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2311 session_.get(), session_->data_channel_type(), label, new_config));
2312 if (!channel) {
2313 sid_allocator_.ReleaseSid(new_config.id);
2314 return nullptr;
2315 }
2316
2317 if (channel->data_channel_type() == cricket::DCT_RTP) {
2318 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2319 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2320 << " already exists.";
2321 return nullptr;
2322 }
2323 rtp_data_channels_[channel->label()] = channel;
2324 } else {
2325 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2326 sctp_data_channels_.push_back(channel);
2327 channel->SignalClosed.connect(this,
2328 &PeerConnection::OnSctpDataChannelClosed);
2329 }
2330
hbos82ebe022016-11-14 01:41:09 -08002331 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002332 return channel;
2333}
2334
2335bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002336#ifdef HAVE_QUIC
2337 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2338 (session_->quic_data_transport() &&
2339 session_->quic_data_transport()->HasDataChannels());
2340#else
deadbeefab9b2d12015-10-14 11:33:11 -07002341 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002342#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002343}
2344
2345void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2346 for (const auto& channel : sctp_data_channels_) {
2347 if (channel->id() < 0) {
2348 int sid;
2349 if (!sid_allocator_.AllocateSid(role, &sid)) {
2350 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2351 continue;
2352 }
2353 channel->SetSctpSid(sid);
2354 }
2355 }
2356}
2357
2358void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002359 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002360 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2361 ++it) {
2362 if (it->get() == channel) {
2363 if (channel->id() >= 0) {
2364 sid_allocator_.ReleaseSid(channel->id());
2365 }
deadbeefbd292462015-12-14 18:15:29 -08002366 // Since this method is triggered by a signal from the DataChannel,
2367 // we can't free it directly here; we need to free it asynchronously.
2368 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002369 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002370 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2371 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002372 return;
2373 }
2374 }
2375}
2376
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002377void PeerConnection::OnVoiceChannelCreated() {
2378 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2379 session_->voice_channel(), senders_, receivers_,
2380 cricket::MEDIA_TYPE_AUDIO);
2381}
2382
deadbeefab9b2d12015-10-14 11:33:11 -07002383void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002384 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2385 cricket::VoiceChannel>(
2386 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2387}
2388
2389void PeerConnection::OnVideoChannelCreated() {
2390 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2391 session_->video_channel(), senders_, receivers_,
2392 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002393}
2394
2395void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002396 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2397 cricket::VideoChannel>(
2398 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002399}
2400
2401void PeerConnection::OnDataChannelCreated() {
2402 for (const auto& channel : sctp_data_channels_) {
2403 channel->OnTransportChannelCreated();
2404 }
2405}
2406
2407void PeerConnection::OnDataChannelDestroyed() {
2408 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2409 // DataChannel may callback to us and try to modify the list.
2410 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2411 temp_rtp_dcs.swap(rtp_data_channels_);
2412 for (const auto& kv : temp_rtp_dcs) {
2413 kv.second->OnTransportChannelDestroyed();
2414 }
2415
2416 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2417 temp_sctp_dcs.swap(sctp_data_channels_);
2418 for (const auto& channel : temp_sctp_dcs) {
2419 channel->OnTransportChannelDestroyed();
2420 }
2421}
2422
2423void PeerConnection::OnDataChannelOpenMessage(
2424 const std::string& label,
2425 const InternalDataChannelInit& config) {
2426 rtc::scoped_refptr<DataChannel> channel(
2427 InternalCreateDataChannel(label, &config));
2428 if (!channel.get()) {
2429 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2430 return;
2431 }
2432
deadbeefa601f5c2016-06-06 14:27:39 -07002433 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2434 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002435 // Call both the raw pointer and scoped_refptr versions of the method
2436 // for compatibility.
2437 observer_->OnDataChannel(proxy_channel.get());
2438 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002439}
2440
deadbeefa601f5c2016-06-06 14:27:39 -07002441RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2442 auto it = std::find_if(
2443 senders_.begin(), senders_.end(),
2444 [id](const rtc::scoped_refptr<
2445 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2446 return sender->id() == id;
2447 });
2448 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002449}
2450
deadbeefa601f5c2016-06-06 14:27:39 -07002451std::vector<
2452 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002453PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2454 return std::find_if(
2455 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002456 [track](const rtc::scoped_refptr<
2457 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002458 return sender->track() == track;
2459 });
2460}
2461
deadbeefa601f5c2016-06-06 14:27:39 -07002462std::vector<rtc::scoped_refptr<
2463 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002464PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002465 return std::find_if(
2466 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002467 [track_id](const rtc::scoped_refptr<
2468 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002469 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002470 });
2471}
2472
deadbeefab9b2d12015-10-14 11:33:11 -07002473PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2474 cricket::MediaType media_type) {
2475 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2476 media_type == cricket::MEDIA_TYPE_VIDEO);
2477 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2478 : &remote_video_tracks_;
2479}
2480
2481PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2482 cricket::MediaType media_type) {
2483 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2484 media_type == cricket::MEDIA_TYPE_VIDEO);
2485 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2486 : &local_video_tracks_;
2487}
2488
2489const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2490 const PeerConnection::TrackInfos& infos,
2491 const std::string& stream_label,
2492 const std::string track_id) const {
2493 for (const TrackInfo& track_info : infos) {
2494 if (track_info.stream_label == stream_label &&
2495 track_info.track_id == track_id) {
2496 return &track_info;
2497 }
2498 }
2499 return nullptr;
2500}
2501
2502DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2503 for (const auto& channel : sctp_data_channels_) {
2504 if (channel->id() == sid) {
2505 return channel;
2506 }
2507 }
2508 return nullptr;
2509}
2510
deadbeef91dd5672016-05-18 16:55:30 -07002511bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002512 const RTCConfiguration& configuration) {
2513 cricket::ServerAddresses stun_servers;
2514 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002515 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2516 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002517 return false;
2518 }
2519
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002520 port_allocator_->Initialize();
2521
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002522 // To handle both internal and externally created port allocator, we will
2523 // enable BUNDLE here.
2524 int portallocator_flags = port_allocator_->flags();
2525 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2526 cricket::PORTALLOCATOR_ENABLE_IPV6;
2527 // If the disable-IPv6 flag was specified, we'll not override it
2528 // by experiment.
2529 if (configuration.disable_ipv6) {
2530 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2531 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2532 "Disabled") {
2533 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2534 }
2535
2536 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2537 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2538 LOG(LS_INFO) << "TCP candidates are disabled.";
2539 }
2540
honghaiz60347052016-05-31 18:29:12 -07002541 if (configuration.candidate_network_policy ==
2542 kCandidateNetworkPolicyLowCost) {
2543 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2544 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2545 }
2546
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002547 port_allocator_->set_flags(portallocator_flags);
2548 // No step delay is used while allocating ports.
2549 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2550 port_allocator_->set_candidate_filter(
2551 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2552
2553 // Call this last since it may create pooled allocator sessions using the
2554 // properties set above.
2555 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002556 configuration.ice_candidate_pool_size,
2557 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002558 return true;
2559}
2560
deadbeef91dd5672016-05-18 16:55:30 -07002561bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002562 const cricket::ServerAddresses& stun_servers,
2563 const std::vector<cricket::RelayServerConfig>& turn_servers,
2564 IceTransportsType type,
2565 int candidate_pool_size,
2566 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002567 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002568 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002569 // Call this last since it may create pooled allocator sessions using the
2570 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002571 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002572 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002573}
2574
ivoc14d5dbe2016-07-04 07:06:55 -07002575bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2576 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002577 if (!event_log_) {
2578 return false;
2579 }
skvlad11a9cbf2016-10-07 11:53:05 -07002580 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002581}
2582
2583void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002584 if (event_log_) {
2585 event_log_->StopLogging();
2586 }
ivoc14d5dbe2016-07-04 07:06:55 -07002587}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002588} // namespace webrtc