blob: d79868d1027c540f0470dc0a5af29315932a8834 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
ossu7bb87ee2017-01-23 04:56:25 -080011#include "webrtc/pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/jsepicecandidate.h"
19#include "webrtc/api/jsepsessiondescription.h"
20#include "webrtc/api/mediaconstraintsinterface.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010021#include "webrtc/api/mediastreamproxy.h"
22#include "webrtc/api/mediastreamtrackproxy.h"
tfarina5237aaf2015-11-10 23:44:30 -080023#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070024#include "webrtc/base/bind.h"
nissec80e7412017-01-11 05:56:46 -080025#include "webrtc/base/checks.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000026#include "webrtc/base/logging.h"
27#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070028#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010029#include "webrtc/base/trace_event.h"
ossuf515ab82016-12-07 04:52:58 -080030#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070031#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
deadbeef953c2ce2017-01-09 14:53:41 -080032#include "webrtc/media/sctp/sctptransport.h"
ossu7bb87ee2017-01-23 04:56:25 -080033#include "webrtc/pc/audiotrack.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010034#include "webrtc/pc/channelmanager.h"
ossu7bb87ee2017-01-23 04:56:25 -080035#include "webrtc/pc/dtmfsender.h"
36#include "webrtc/pc/mediastream.h"
37#include "webrtc/pc/mediastreamobserver.h"
38#include "webrtc/pc/remoteaudiosource.h"
39#include "webrtc/pc/rtpreceiver.h"
40#include "webrtc/pc/rtpsender.h"
41#include "webrtc/pc/streamcollection.h"
42#include "webrtc/pc/videocapturertracksource.h"
43#include "webrtc/pc/videotrack.h"
44#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010045#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046
47namespace {
48
deadbeefab9b2d12015-10-14 11:33:11 -070049using webrtc::DataChannel;
50using webrtc::MediaConstraintsInterface;
51using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080053using webrtc::RTCError;
54using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070055using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080056using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070057using webrtc::RtpSenderProxy;
58using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070059using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
deadbeefab9b2d12015-10-14 11:33:11 -070061static const char kDefaultStreamLabel[] = "default";
62static const char kDefaultAudioTrackLabel[] = "defaulta0";
63static const char kDefaultVideoTrackLabel[] = "defaultv0";
64
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065// The min number of tokens must present in Turn host uri.
66// e.g. user@turn.example.org
67static const size_t kTurnHostTokensNum = 2;
68// Number of tokens must be preset when TURN uri has transport param.
69static const size_t kTurnTransportTokensNum = 2;
70// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000071static const int kDefaultStunPort = 3478;
72static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
75// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070076static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077
zhihuang8f65cdf2016-05-06 18:40:30 -070078// The length of RTCP CNAMEs.
79static const int kRtcpCnameLength = 16;
80
deadbeef0a6c4ca2015-10-06 11:38:28 -070081// NOTE: A loop below assumes that the first value of this enum is 0 and all
82// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070084 STUN = 0, // Indicates a STUN server.
85 STUNS, // Indicates a STUN server used with a TLS session.
86 TURN, // Indicates a TURN server
87 TURNS, // Indicates a TURN server used with a TLS session.
88 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089};
tfarina5237aaf2015-11-10 23:44:30 -080090static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070091 "kValidIceServiceTypes must have as many strings as ServiceType "
92 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
94enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000095 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070097 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080099 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100};
101
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000102struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103 explicit SetSessionDescriptionMsg(
104 webrtc::SetSessionDescriptionObserver* observer)
105 : observer(observer) {
106 }
107
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000108 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 std::string error;
110};
111
deadbeefab9b2d12015-10-14 11:33:11 -0700112struct CreateSessionDescriptionMsg : public rtc::MessageData {
113 explicit CreateSessionDescriptionMsg(
114 webrtc::CreateSessionDescriptionObserver* observer)
115 : observer(observer) {}
116
117 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
118 std::string error;
119};
120
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000121struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000122 GetStatsMsg(webrtc::StatsObserver* observer,
123 webrtc::MediaStreamTrackInterface* track)
124 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000126 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000127 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000128};
129
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000130// |in_str| should be of format
131// stunURI = scheme ":" stun-host [ ":" stun-port ]
132// scheme = "stun" / "stuns"
133// stun-host = IP-literal / IPv4address / reg-name
134// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700135//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000136// draft-petithuguenin-behave-turn-uris-01
137// turnURI = scheme ":" turn-host [ ":" turn-port ]
138// turn-host = username@IP-literal / IPv4address / reg-name
139bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
140 ServiceType* service_type,
141 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200142 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700143 if (colonpos == std::string::npos) {
144 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000145 return false;
146 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700147 if ((colonpos + 1) == in_str.length()) {
148 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
149 return false;
150 }
151 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800152 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700153 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000154 *service_type = static_cast<ServiceType>(i);
155 break;
156 }
157 }
158 if (*service_type == INVALID) {
159 return false;
160 }
161 *hostname = in_str.substr(colonpos + 1, std::string::npos);
162 return true;
163}
164
deadbeef0a6c4ca2015-10-06 11:38:28 -0700165bool ParsePort(const std::string& in_str, int* port) {
166 // Make sure port only contains digits. FromString doesn't check this.
167 for (const char& c : in_str) {
168 if (!std::isdigit(c)) {
169 return false;
170 }
171 }
172 return rtc::FromString(in_str, port);
173}
174
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000175// This method parses IPv6 and IPv4 literal strings, along with hostnames in
176// standard hostname:port format.
177// Consider following formats as correct.
178// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700179// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000180bool ParseHostnameAndPortFromString(const std::string& in_str,
181 std::string* host,
182 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700183 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 if (in_str.at(0) == '[') {
185 std::string::size_type closebracket = in_str.rfind(']');
186 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000187 std::string::size_type colonpos = in_str.find(':', closebracket);
188 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700189 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
190 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000191 return false;
192 }
193 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700194 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000195 } else {
196 return false;
197 }
198 } else {
199 std::string::size_type colonpos = in_str.find(':');
200 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 return false;
203 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700204 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000205 } else {
206 *host = in_str;
207 }
208 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700209 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000210}
211
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800212// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700213// by parsing |url| and using the username/password in |server|.
deadbeef293e9262017-01-11 12:28:30 -0800214RTCErrorType ParseIceServerUrl(
215 const PeerConnectionInterface::IceServer& server,
216 const std::string& url,
217 cricket::ServerAddresses* stun_servers,
218 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219 // draft-nandakumar-rtcweb-stun-uri-01
220 // stunURI = scheme ":" stun-host [ ":" stun-port ]
221 // scheme = "stun" / "stuns"
222 // stun-host = IP-literal / IPv4address / reg-name
223 // stun-port = *DIGIT
224
225 // draft-petithuguenin-behave-turn-uris-01
226 // turnURI = scheme ":" turn-host [ ":" turn-port ]
227 // [ "?transport=" transport ]
228 // scheme = "turn" / "turns"
229 // transport = "udp" / "tcp" / transport-ext
230 // transport-ext = 1*unreserved
231 // turn-host = IP-literal / IPv4address / reg-name
232 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800233 RTC_DCHECK(stun_servers != nullptr);
234 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200235 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800236 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700237 RTC_DCHECK(!url.empty());
hnslbd44bb02016-12-12 03:14:30 -0800238 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200239 std::string uri_without_transport = tokens[0];
240 // Let's look into transport= param, if it exists.
241 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
242 std::string uri_transport_param = tokens[1];
hnslbd44bb02016-12-12 03:14:30 -0800243 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
244 if (tokens[0] != kTransport) {
245 LOG(LS_WARNING) << "Invalid transport parameter key.";
deadbeef293e9262017-01-11 12:28:30 -0800246 return RTCErrorType::SYNTAX_ERROR;
hnslbd44bb02016-12-12 03:14:30 -0800247 }
zstein9dd77ba2017-02-07 15:09:50 -0800248 if (tokens.size() < 2) {
249 LOG(LS_WARNING) << "Transport parameter missing value.";
250 return RTCErrorType::SYNTAX_ERROR;
251 }
252 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
hnslbd44bb02016-12-12 03:14:30 -0800253 (turn_transport_type != cricket::PROTO_UDP &&
254 turn_transport_type != cricket::PROTO_TCP)) {
zstein9dd77ba2017-02-07 15:09:50 -0800255 LOG(LS_WARNING) << "Transport parameter should always be udp or tcp.";
deadbeef293e9262017-01-11 12:28:30 -0800256 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200258 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200262 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
263 &service_type,
264 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
deadbeef293e9262017-01-11 12:28:30 -0800266 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200267 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000268
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
270 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200271
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200272 // Let's break hostname.
273 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700274 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
275
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200276 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700277 if (tokens.size() > kTurnHostTokensNum) {
278 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800279 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700280 }
281 if (tokens.size() == kTurnHostTokensNum) {
282 if (tokens[0].empty() || tokens[1].empty()) {
283 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef293e9262017-01-11 12:28:30 -0800284 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700285 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200286 username.assign(rtc::s_url_decode(tokens[0]));
287 hoststring = tokens[1];
288 } else {
289 hoststring = tokens[0];
290 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000291
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200292 int port = kDefaultStunPort;
293 if (service_type == TURNS) {
294 port = kDefaultStunTlsPort;
hnsl277b2502016-12-13 05:17:23 -0800295 turn_transport_type = cricket::PROTO_TLS;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200296 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000297
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200298 std::string address;
299 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700300 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
deadbeef293e9262017-01-11 12:28:30 -0800301 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200302 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000303
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200304 if (port <= 0 || port > 0xffff) {
305 LOG(WARNING) << "Invalid port: " << port;
deadbeef293e9262017-01-11 12:28:30 -0800306 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000308
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200309 switch (service_type) {
310 case STUN:
311 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800312 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200313 break;
314 case TURN:
315 case TURNS: {
deadbeef293e9262017-01-11 12:28:30 -0800316 if (username.empty() || server.password.empty()) {
317 // The WebRTC spec requires throwing an InvalidAccessError when username
318 // or credential are ommitted; this is the native equivalent.
319 return RTCErrorType::INVALID_PARAMETER;
320 }
hnsl04833622017-01-09 08:35:45 -0800321 cricket::RelayServerConfig config = cricket::RelayServerConfig(
322 address, port, username, server.password, turn_transport_type);
323 if (server.tls_cert_policy ==
324 PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
325 config.tls_cert_policy =
326 cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
327 }
328 turn_servers->push_back(config);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200329 break;
330 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200331 default:
deadbeef293e9262017-01-11 12:28:30 -0800332 // We shouldn't get to this point with an invalid service_type, we should
333 // have returned an error already.
nisseeb4ca4e2017-01-12 02:24:27 -0800334 RTC_NOTREACHED() << "Unexpected service type";
deadbeef293e9262017-01-11 12:28:30 -0800335 return RTCErrorType::INTERNAL_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200336 }
deadbeef293e9262017-01-11 12:28:30 -0800337 return RTCErrorType::NONE;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200338}
339
deadbeefab9b2d12015-10-14 11:33:11 -0700340// Check if we can send |new_stream| on a PeerConnection.
341bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
342 webrtc::MediaStreamInterface* new_stream) {
343 if (!new_stream || !current_streams) {
344 return false;
345 }
346 if (current_streams->find(new_stream->label()) != nullptr) {
347 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
348 << " is already added.";
349 return false;
350 }
351 return true;
352}
353
354bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
355 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
356}
357
deadbeef5e97fb52015-10-15 12:49:08 -0700358// If the direction is "recvonly" or "inactive", treat the description
359// as containing no streams.
360// See: https://code.google.com/p/webrtc/issues/detail?id=5054
361std::vector<cricket::StreamParams> GetActiveStreams(
362 const cricket::MediaContentDescription* desc) {
363 return MediaContentDirectionHasSend(desc->direction())
364 ? desc->streams()
365 : std::vector<cricket::StreamParams>();
366}
367
deadbeefab9b2d12015-10-14 11:33:11 -0700368bool IsValidOfferToReceiveMedia(int value) {
369 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
370 return (value >= Options::kUndefined) &&
371 (value <= Options::kMaxOfferToReceiveMedia);
372}
373
374// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800375void AddSendStreams(
376 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700377 const std::vector<rtc::scoped_refptr<
378 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800379 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
380 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700381 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800382 for (const auto& sender : senders) {
383 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700384 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700385 }
386
387 // Check for data channels.
388 for (const auto& kv : rtp_data_channels) {
389 const DataChannel* channel = kv.second;
390 if (channel->state() == DataChannel::kConnecting ||
391 channel->state() == DataChannel::kOpen) {
392 // |streamid| and |sync_label| are both set to the DataChannel label
393 // here so they can be signaled the same way as MediaStreams and Tracks.
394 // For MediaStreams, the sync_label is the MediaStream label and the
395 // track label is the same as |streamid|.
396 const std::string& streamid = channel->label();
397 const std::string& sync_label = channel->label();
398 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
399 sync_label);
400 }
401 }
402}
403
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700404uint32_t ConvertIceTransportTypeToCandidateFilter(
405 PeerConnectionInterface::IceTransportsType type) {
406 switch (type) {
407 case PeerConnectionInterface::kNone:
408 return cricket::CF_NONE;
409 case PeerConnectionInterface::kRelay:
410 return cricket::CF_RELAY;
411 case PeerConnectionInterface::kNoHost:
412 return (cricket::CF_ALL & ~cricket::CF_HOST);
413 case PeerConnectionInterface::kAll:
414 return cricket::CF_ALL;
415 default:
nissec80e7412017-01-11 05:56:46 -0800416 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700417 }
418 return cricket::CF_NONE;
419}
420
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700421// Helper method to set a voice/video channel on all applicable senders
422// and receivers when one is created/destroyed by WebRtcSession.
423//
424// Used by On(Voice|Video)Channel(Created|Destroyed)
425template <class SENDER,
426 class RECEIVER,
427 class CHANNEL,
428 class SENDERS,
429 class RECEIVERS>
430void SetChannelOnSendersAndReceivers(CHANNEL* channel,
431 SENDERS& senders,
432 RECEIVERS& receivers,
433 cricket::MediaType media_type) {
434 for (auto& sender : senders) {
435 if (sender->media_type() == media_type) {
436 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
437 }
438 }
439 for (auto& receiver : receivers) {
440 if (receiver->media_type() == media_type) {
441 if (!channel) {
442 receiver->internal()->Stop();
443 }
444 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
445 }
446 }
447}
448
deadbeef293e9262017-01-11 12:28:30 -0800449// Helper to set an error and return from a method.
450bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
451 if (error) {
452 error->set_type(type);
453 }
454 return type == webrtc::RTCErrorType::NONE;
455}
456
deadbeef0a6c4ca2015-10-06 11:38:28 -0700457} // namespace
458
459namespace webrtc {
460
deadbeef293e9262017-01-11 12:28:30 -0800461bool PeerConnectionInterface::RTCConfiguration::operator==(
462 const PeerConnectionInterface::RTCConfiguration& o) const {
463 // This static_assert prevents us from accidentally breaking operator==.
464 struct stuff_being_tested_for_equality {
465 IceTransportsType type;
466 IceServers servers;
467 BundlePolicy bundle_policy;
468 RtcpMuxPolicy rtcp_mux_policy;
469 TcpCandidatePolicy tcp_candidate_policy;
470 CandidateNetworkPolicy candidate_network_policy;
471 int audio_jitter_buffer_max_packets;
472 bool audio_jitter_buffer_fast_accelerate;
473 int ice_connection_receiving_timeout;
474 int ice_backup_candidate_pair_ping_interval;
475 ContinualGatheringPolicy continual_gathering_policy;
476 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
477 bool prioritize_most_likely_ice_candidate_pairs;
478 struct cricket::MediaConfig media_config;
479 bool disable_ipv6;
zhihuangb09b3f92017-03-07 14:40:51 -0800480 bool disable_ipv6_on_wifi;
deadbeef293e9262017-01-11 12:28:30 -0800481 bool enable_rtp_data_channel;
482 bool enable_quic;
483 rtc::Optional<int> screencast_min_bitrate;
484 rtc::Optional<bool> combined_audio_video_bwe;
485 rtc::Optional<bool> enable_dtls_srtp;
486 int ice_candidate_pool_size;
487 bool prune_turn_ports;
488 bool presume_writable_when_fully_relayed;
489 bool enable_ice_renomination;
490 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800491 rtc::Optional<int> ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800492 };
493 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
494 "Did you add something to RTCConfiguration and forget to "
495 "update operator==?");
496 return type == o.type && servers == o.servers &&
497 bundle_policy == o.bundle_policy &&
498 rtcp_mux_policy == o.rtcp_mux_policy &&
499 tcp_candidate_policy == o.tcp_candidate_policy &&
500 candidate_network_policy == o.candidate_network_policy &&
501 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
502 audio_jitter_buffer_fast_accelerate ==
503 o.audio_jitter_buffer_fast_accelerate &&
504 ice_connection_receiving_timeout ==
505 o.ice_connection_receiving_timeout &&
506 ice_backup_candidate_pair_ping_interval ==
507 o.ice_backup_candidate_pair_ping_interval &&
508 continual_gathering_policy == o.continual_gathering_policy &&
509 certificates == o.certificates &&
510 prioritize_most_likely_ice_candidate_pairs ==
511 o.prioritize_most_likely_ice_candidate_pairs &&
512 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800513 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeef293e9262017-01-11 12:28:30 -0800514 enable_rtp_data_channel == o.enable_rtp_data_channel &&
515 enable_quic == o.enable_quic &&
516 screencast_min_bitrate == o.screencast_min_bitrate &&
517 combined_audio_video_bwe == o.combined_audio_video_bwe &&
518 enable_dtls_srtp == o.enable_dtls_srtp &&
519 ice_candidate_pool_size == o.ice_candidate_pool_size &&
520 prune_turn_ports == o.prune_turn_ports &&
521 presume_writable_when_fully_relayed ==
522 o.presume_writable_when_fully_relayed &&
523 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800524 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
525 ice_check_min_interval == o.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800526}
527
528bool PeerConnectionInterface::RTCConfiguration::operator!=(
529 const PeerConnectionInterface::RTCConfiguration& o) const {
530 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800531}
532
zhihuang8f65cdf2016-05-06 18:40:30 -0700533// Generate a RTCP CNAME when a PeerConnection is created.
534std::string GenerateRtcpCname() {
535 std::string cname;
536 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
537 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800538 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700539 }
540 return cname;
541}
542
htaa2a49d92016-03-04 02:51:39 -0800543bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700544 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800545 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700546 cricket::MediaSessionOptions* session_options) {
547 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
548 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
549 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
550 return false;
551 }
552
htaaac2dea2016-03-10 13:35:55 -0800553 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700554 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700555 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800556 } else {
557 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700558 }
htaaac2dea2016-03-10 13:35:55 -0800559 // For offers, we only offer video if we have it or it's forced by options.
560 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700561 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700562 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800563 } else if (is_offer) {
564 session_options->recv_video = false;
565 } else {
566 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700567 }
568
569 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700570 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800571 for (auto& kv : session_options->transport_options) {
572 kv.second.ice_restart = rtc_options.ice_restart;
573 }
deadbeefab9b2d12015-10-14 11:33:11 -0700574
575 return true;
576}
577
578bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
579 cricket::MediaSessionOptions* session_options) {
580 bool value = false;
581 size_t mandatory_constraints_satisfied = 0;
582
583 // kOfferToReceiveAudio defaults to true according to spec.
584 if (!FindConstraint(constraints,
585 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
586 &mandatory_constraints_satisfied) ||
587 value) {
588 session_options->recv_audio = true;
589 }
590
591 // kOfferToReceiveVideo defaults to false according to spec. But
592 // if it is an answer and video is offered, we should still accept video
593 // per default.
594 value = false;
595 if (!FindConstraint(constraints,
596 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
597 &mandatory_constraints_satisfied) ||
598 value) {
599 session_options->recv_video = true;
600 }
601
602 if (FindConstraint(constraints,
603 MediaConstraintsInterface::kVoiceActivityDetection, &value,
604 &mandatory_constraints_satisfied)) {
605 session_options->vad_enabled = value;
606 }
607
608 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
609 &mandatory_constraints_satisfied)) {
610 session_options->bundle_enabled = value;
611 } else {
612 // kUseRtpMux defaults to true according to spec.
613 session_options->bundle_enabled = true;
614 }
deadbeefab9b2d12015-10-14 11:33:11 -0700615
deadbeef0ed85b22016-02-23 17:24:52 -0800616 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700617 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
618 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700619 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800620 ice_restart = true;
621 }
622 for (auto& kv : session_options->transport_options) {
623 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700624 }
625
626 if (!constraints) {
627 return true;
628 }
629 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
630}
631
deadbeef293e9262017-01-11 12:28:30 -0800632RTCErrorType ParseIceServers(
633 const PeerConnectionInterface::IceServers& servers,
634 cricket::ServerAddresses* stun_servers,
635 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200636 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
637 if (!server.urls.empty()) {
638 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200639 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700640 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800641 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200642 }
deadbeef293e9262017-01-11 12:28:30 -0800643 RTCErrorType err =
644 ParseIceServerUrl(server, url, stun_servers, turn_servers);
645 if (err != RTCErrorType::NONE) {
646 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200647 }
648 }
649 } else if (!server.uri.empty()) {
650 // Fallback to old .uri if new .urls isn't present.
deadbeef293e9262017-01-11 12:28:30 -0800651 RTCErrorType err =
652 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
653 if (err != RTCErrorType::NONE) {
654 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200655 }
656 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700657 LOG(LS_ERROR) << "Empty uri.";
deadbeef293e9262017-01-11 12:28:30 -0800658 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659 }
660 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800661 // Candidates must have unique priorities, so that connectivity checks
662 // are performed in a well-defined order.
663 int priority = static_cast<int>(turn_servers->size() - 1);
664 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
665 // First in the list gets highest priority.
666 turn_server.priority = priority--;
667 }
deadbeef293e9262017-01-11 12:28:30 -0800668 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669}
670
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671PeerConnection::PeerConnection(PeerConnectionFactory* factory)
672 : factory_(factory),
673 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000674 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700677 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800678 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700679 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700680 local_streams_(StreamCollection::Create()),
681 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682
683PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100684 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700685 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700686 // Need to detach RTP senders/receivers from WebRtcSession,
687 // since it's about to be destroyed.
688 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700689 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700690 }
691 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700692 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700693 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700694 // Destroy stats_ because it depends on session_.
695 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800696 if (stats_collector_) {
697 stats_collector_->WaitForPendingRequest();
698 stats_collector_ = nullptr;
699 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700700 // Now destroy session_ before destroying other members,
701 // because its destruction fires signals (such as VoiceChannelDestroyed)
702 // which will trigger some final actions in PeerConnection...
703 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700704 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700705 network_thread()->Invoke<void>(RTC_FROM_HERE,
706 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707}
708
709bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000710 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700711 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200712 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800713 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100714 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800715 if (!allocator) {
716 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
717 << "This shouldn't happen if using PeerConnectionFactory.";
718 return false;
719 }
deadbeef653b8e02015-11-11 12:55:10 -0800720 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800721 // TODO(deadbeef): Why do we do this?
722 LOG(LS_ERROR) << "PeerConnection initialized without a "
723 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800724 return false;
725 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000726 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800727 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800728
deadbeef91dd5672016-05-18 16:55:30 -0700729 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700730 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700731 if (!network_thread()->Invoke<bool>(
732 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
733 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734 return false;
735 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736
skvlad11a9cbf2016-10-07 11:53:05 -0700737 media_controller_.reset(factory_->CreateMediaController(
738 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000739
zhihuang29ff8442016-07-27 11:07:25 -0700740 session_.reset(new WebRtcSession(
741 media_controller_.get(), factory_->network_thread(),
742 factory_->worker_thread(), factory_->signaling_thread(),
743 port_allocator_.get(),
744 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700745 factory_->CreateTransportController(
746 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800747 configuration.redetermine_role_on_ice_restart)),
748#ifdef HAVE_SCTP
749 std::unique_ptr<cricket::SctpTransportInternalFactory>(
750 new cricket::SctpTransportFactory(factory_->network_thread()))
751#else
752 nullptr
753#endif
754 ));
zhihuang29ff8442016-07-27 11:07:25 -0700755
deadbeefab9b2d12015-10-14 11:33:11 -0700756 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700757 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758
759 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200760 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800761 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700763 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765 // Register PeerConnection as receiver of local ice candidates.
766 // All the callbacks will be posted to the application from PeerConnection.
767 session_->RegisterIceObserver(this);
768 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700769 session_->SignalVoiceChannelCreated.connect(
770 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700771 session_->SignalVoiceChannelDestroyed.connect(
772 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700773 session_->SignalVideoChannelCreated.connect(
774 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700775 session_->SignalVideoChannelDestroyed.connect(
776 this, &PeerConnection::OnVideoChannelDestroyed);
777 session_->SignalDataChannelCreated.connect(
778 this, &PeerConnection::OnDataChannelCreated);
779 session_->SignalDataChannelDestroyed.connect(
780 this, &PeerConnection::OnDataChannelDestroyed);
781 session_->SignalDataChannelOpenMessage.connect(
782 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800783
784 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785 return true;
786}
787
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000788rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000789PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700790 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000791}
792
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000793rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700795 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796}
797
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000798bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100799 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800 if (IsClosed()) {
801 return false;
802 }
deadbeefab9b2d12015-10-14 11:33:11 -0700803 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 return false;
805 }
deadbeefab9b2d12015-10-14 11:33:11 -0700806
807 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800808 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
809 observer->SignalAudioTrackAdded.connect(this,
810 &PeerConnection::OnAudioTrackAdded);
811 observer->SignalAudioTrackRemoved.connect(
812 this, &PeerConnection::OnAudioTrackRemoved);
813 observer->SignalVideoTrackAdded.connect(this,
814 &PeerConnection::OnVideoTrackAdded);
815 observer->SignalVideoTrackRemoved.connect(
816 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700817 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700818
deadbeefab9b2d12015-10-14 11:33:11 -0700819 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800820 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700821 }
822 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800823 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700824 }
825
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000826 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 observer_->OnRenegotiationNeeded();
828 return true;
829}
830
831void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100832 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700833 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800834 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700835 }
836 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800837 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700838 }
839
840 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800841 stream_observers_.erase(
842 std::remove_if(
843 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700844 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800845 return observer->stream()->label().compare(local_stream->label()) ==
846 0;
847 }),
848 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700849
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 if (IsClosed()) {
851 return;
852 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853 observer_->OnRenegotiationNeeded();
854}
855
deadbeefe1f9d832016-01-14 15:35:42 -0800856rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
857 MediaStreamTrackInterface* track,
858 std::vector<MediaStreamInterface*> streams) {
859 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
860 if (IsClosed()) {
861 return nullptr;
862 }
863 if (streams.size() >= 2) {
864 LOG(LS_ERROR)
865 << "Adding a track with two streams is not currently supported.";
866 return nullptr;
867 }
868 // TODO(deadbeef): Support adding a track to two different senders.
869 if (FindSenderForTrack(track) != senders_.end()) {
870 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
871 return nullptr;
872 }
873
874 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700875 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800876 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700877 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800878 signaling_thread(),
879 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700880 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800881 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700882 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800883 }
884 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700885 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800886 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700887 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800888 }
889 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700890 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800891 signaling_thread(),
892 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700893 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800894 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700895 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800896 }
897 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700898 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800899 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700900 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800901 }
902 } else {
903 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
904 return rtc::scoped_refptr<RtpSenderInterface>();
905 }
906
907 senders_.push_back(new_sender);
908 observer_->OnRenegotiationNeeded();
909 return new_sender;
910}
911
912bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
913 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
914 if (IsClosed()) {
915 return false;
916 }
917
918 auto it = std::find(senders_.begin(), senders_.end(), sender);
919 if (it == senders_.end()) {
920 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
921 return false;
922 }
deadbeefa601f5c2016-06-06 14:27:39 -0700923 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800924 senders_.erase(it);
925
926 observer_->OnRenegotiationNeeded();
927 return true;
928}
929
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000930rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100932 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700933 if (IsClosed()) {
934 return nullptr;
935 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936 if (!track) {
937 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800938 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939 }
deadbeef20cb0c12017-02-01 20:27:00 -0800940 auto it = FindSenderForTrack(track);
941 if (it == senders_.end()) {
942 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
943 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944 }
945
deadbeef20cb0c12017-02-01 20:27:00 -0800946 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947}
948
deadbeeffac06552015-11-25 11:26:01 -0800949rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800950 const std::string& kind,
951 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100952 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700953 if (IsClosed()) {
954 return nullptr;
955 }
deadbeefa601f5c2016-06-06 14:27:39 -0700956 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800957 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700958 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700959 signaling_thread(),
960 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800961 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700962 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700963 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800964 } else {
965 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800966 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800967 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800968 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700969 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800970 }
deadbeeffac06552015-11-25 11:26:01 -0800971 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800972 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800973}
974
deadbeef70ab1a12015-09-28 16:53:55 -0700975std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
976 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700977 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
978 for (const auto& sender : senders_) {
979 ret.push_back(sender.get());
980 }
981 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700982}
983
984std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
985PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700986 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
987 for (const auto& receiver : receivers_) {
988 ret.push_back(receiver.get());
989 }
990 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700991}
992
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000994 MediaStreamTrackInterface* track,
995 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100996 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700997 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800998 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1000 return false;
1001 }
1002
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001003 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001004 // The StatsCollector is used to tell if a track is valid because it may
1005 // remember tracks that the PeerConnection previously removed.
1006 if (track && !stats_->IsValidTrack(track->id())) {
1007 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1008 << track->id();
1009 return false;
1010 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001011 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001012 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 return true;
1014}
1015
hbos74e1a4f2016-09-15 23:33:01 -07001016void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1017 RTC_DCHECK(stats_collector_);
1018 stats_collector_->GetStatsReport(callback);
1019}
1020
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1022 return signaling_state_;
1023}
1024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025PeerConnectionInterface::IceConnectionState
1026PeerConnection::ice_connection_state() {
1027 return ice_connection_state_;
1028}
1029
1030PeerConnectionInterface::IceGatheringState
1031PeerConnection::ice_gathering_state() {
1032 return ice_gathering_state_;
1033}
1034
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001035rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036PeerConnection::CreateDataChannel(
1037 const std::string& label,
1038 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001039 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001040#ifdef HAVE_QUIC
1041 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1042 // TODO(zhihuang): Handle case when config is NULL.
1043 if (!config) {
1044 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1045 return nullptr;
1046 }
1047 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1048 if (!config->reliable || config->ordered) {
1049 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1050 "ordered delivery.";
1051 return nullptr;
1052 }
1053 return session_->quic_data_transport()->CreateDataChannel(label, config);
1054 }
1055#endif // HAVE_QUIC
1056
deadbeefab9b2d12015-10-14 11:33:11 -07001057 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001058
kwibergd1fe2812016-04-27 06:47:29 -07001059 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001060 if (config) {
1061 internal_config.reset(new InternalDataChannelInit(*config));
1062 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001063 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001064 InternalCreateDataChannel(label, internal_config.get()));
1065 if (!channel.get()) {
1066 return nullptr;
1067 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001069 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1070 // the first SCTP DataChannel.
1071 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1072 observer_->OnRenegotiationNeeded();
1073 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001074
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 return DataChannelProxy::Create(signaling_thread(), channel.get());
1076}
1077
1078void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1079 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001080 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001081 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1083 return;
1084 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001085 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001086
1087 bool value;
1088 size_t mandatory_constraints = 0;
1089
1090 if (FindConstraint(constraints,
1091 MediaConstraintsInterface::kOfferToReceiveAudio,
1092 &value,
1093 &mandatory_constraints)) {
1094 options.offer_to_receive_audio =
1095 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1096 }
1097
1098 if (FindConstraint(constraints,
1099 MediaConstraintsInterface::kOfferToReceiveVideo,
1100 &value,
1101 &mandatory_constraints)) {
1102 options.offer_to_receive_video =
1103 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1104 }
1105
1106 if (FindConstraint(constraints,
1107 MediaConstraintsInterface::kVoiceActivityDetection,
1108 &value,
1109 &mandatory_constraints)) {
1110 options.voice_activity_detection = value;
1111 }
1112
1113 if (FindConstraint(constraints,
1114 MediaConstraintsInterface::kIceRestart,
1115 &value,
1116 &mandatory_constraints)) {
1117 options.ice_restart = value;
1118 }
1119
1120 if (FindConstraint(constraints,
1121 MediaConstraintsInterface::kUseRtpMux,
1122 &value,
1123 &mandatory_constraints)) {
1124 options.use_rtp_mux = value;
1125 }
1126
1127 CreateOffer(observer, options);
1128}
1129
1130void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1131 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001132 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -08001133 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001134 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1135 return;
1136 }
deadbeefab9b2d12015-10-14 11:33:11 -07001137
1138 cricket::MediaSessionOptions session_options;
1139 if (!GetOptionsForOffer(options, &session_options)) {
1140 std::string error = "CreateOffer called with invalid options.";
1141 LOG(LS_ERROR) << error;
1142 PostCreateSessionDescriptionFailure(observer, error);
1143 return;
1144 }
1145
1146 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147}
1148
1149void PeerConnection::CreateAnswer(
1150 CreateSessionDescriptionObserver* observer,
1151 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001152 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001153 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1155 return;
1156 }
deadbeefab9b2d12015-10-14 11:33:11 -07001157
1158 cricket::MediaSessionOptions session_options;
1159 if (!GetOptionsForAnswer(constraints, &session_options)) {
1160 std::string error = "CreateAnswer called with invalid constraints.";
1161 LOG(LS_ERROR) << error;
1162 PostCreateSessionDescriptionFailure(observer, error);
1163 return;
1164 }
1165
htaa2a49d92016-03-04 02:51:39 -08001166 session_->CreateAnswer(observer, session_options);
1167}
1168
1169void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1170 const RTCOfferAnswerOptions& options) {
1171 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001172 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -08001173 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1174 return;
1175 }
1176
1177 cricket::MediaSessionOptions session_options;
1178 if (!GetOptionsForAnswer(options, &session_options)) {
1179 std::string error = "CreateAnswer called with invalid options.";
1180 LOG(LS_ERROR) << error;
1181 PostCreateSessionDescriptionFailure(observer, error);
1182 return;
1183 }
1184
1185 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186}
1187
1188void PeerConnection::SetLocalDescription(
1189 SetSessionDescriptionObserver* observer,
1190 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001191 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001192 if (IsClosed()) {
1193 return;
1194 }
nisse7ce109a2017-01-31 00:57:56 -08001195 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001196 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1197 return;
1198 }
1199 if (!desc) {
1200 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1201 return;
1202 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203 // Update stats here so that we have the most recent stats for tracks and
1204 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001205 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 std::string error;
1207 if (!session_->SetLocalDescription(desc, &error)) {
1208 PostSetSessionDescriptionFailure(observer, error);
1209 return;
1210 }
deadbeefab9b2d12015-10-14 11:33:11 -07001211
1212 // If setting the description decided our SSL role, allocate any necessary
1213 // SCTP sids.
1214 rtc::SSLRole role;
1215 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001216 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001217 AllocateSctpSids(role);
1218 }
1219
1220 // Update state and SSRC of local MediaStreams and DataChannels based on the
1221 // local session description.
1222 const cricket::ContentInfo* audio_content =
1223 GetFirstAudioContent(desc->description());
1224 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001225 if (audio_content->rejected) {
1226 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1227 } else {
1228 const cricket::AudioContentDescription* audio_desc =
1229 static_cast<const cricket::AudioContentDescription*>(
1230 audio_content->description);
1231 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1232 }
deadbeefab9b2d12015-10-14 11:33:11 -07001233 }
1234
1235 const cricket::ContentInfo* video_content =
1236 GetFirstVideoContent(desc->description());
1237 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001238 if (video_content->rejected) {
1239 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1240 } else {
1241 const cricket::VideoContentDescription* video_desc =
1242 static_cast<const cricket::VideoContentDescription*>(
1243 video_content->description);
1244 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1245 }
deadbeefab9b2d12015-10-14 11:33:11 -07001246 }
1247
1248 const cricket::ContentInfo* data_content =
1249 GetFirstDataContent(desc->description());
1250 if (data_content) {
1251 const cricket::DataContentDescription* data_desc =
1252 static_cast<const cricket::DataContentDescription*>(
1253 data_content->description);
1254 if (rtc::starts_with(data_desc->protocol().data(),
1255 cricket::kMediaProtocolRtpPrefix)) {
1256 UpdateLocalRtpDataChannels(data_desc->streams());
1257 }
1258 }
1259
1260 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001261 signaling_thread()->Post(RTC_FROM_HERE, this,
1262 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001263
deadbeef42a42632017-03-10 15:18:00 -08001264 // According to JSEP, after setLocalDescription, changing the candidate pool
1265 // size is not allowed, and changing the set of ICE servers will not result
1266 // in new candidates being gathered.
1267 port_allocator_->FreezeCandidatePool();
1268
deadbeefcbecd352015-09-23 11:50:27 -07001269 // MaybeStartGathering needs to be called after posting
1270 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1271 // before signaling that SetLocalDescription completed.
1272 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001273
1274 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1275 // TODO(deadbeef): We already had to hop to the network thread for
1276 // MaybeStartGathering...
1277 network_thread()->Invoke<void>(
1278 RTC_FROM_HERE,
1279 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1280 port_allocator_.get()));
1281 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282}
1283
1284void PeerConnection::SetRemoteDescription(
1285 SetSessionDescriptionObserver* observer,
1286 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001287 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001288 if (IsClosed()) {
1289 return;
1290 }
nisse7ce109a2017-01-31 00:57:56 -08001291 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1293 return;
1294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 if (!desc) {
1296 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1297 return;
1298 }
1299 // Update stats here so that we have the most recent stats for tracks and
1300 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001301 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 std::string error;
1303 if (!session_->SetRemoteDescription(desc, &error)) {
1304 PostSetSessionDescriptionFailure(observer, error);
1305 return;
1306 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307
deadbeefab9b2d12015-10-14 11:33:11 -07001308 // If setting the description decided our SSL role, allocate any necessary
1309 // SCTP sids.
1310 rtc::SSLRole role;
1311 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001312 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001313 AllocateSctpSids(role);
1314 }
1315
1316 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001317 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1318 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1319 const cricket::AudioContentDescription* audio_desc =
1320 GetFirstAudioContentDescription(remote_desc);
1321 const cricket::VideoContentDescription* video_desc =
1322 GetFirstVideoContentDescription(remote_desc);
1323 const cricket::DataContentDescription* data_desc =
1324 GetFirstDataContentDescription(remote_desc);
1325
1326 // Check if the descriptions include streams, just in case the peer supports
1327 // MSID, but doesn't indicate so with "a=msid-semantic".
1328 if (remote_desc->msid_supported() ||
1329 (audio_desc && !audio_desc->streams().empty()) ||
1330 (video_desc && !video_desc->streams().empty())) {
1331 remote_peer_supports_msid_ = true;
1332 }
deadbeefab9b2d12015-10-14 11:33:11 -07001333
1334 // We wait to signal new streams until we finish processing the description,
1335 // since only at that point will new streams have all their tracks.
1336 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1337
1338 // Find all audio rtp streams and create corresponding remote AudioTracks
1339 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001340 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001341 if (audio_content->rejected) {
1342 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1343 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001344 bool default_audio_track_needed =
1345 !remote_peer_supports_msid_ &&
1346 MediaContentDirectionHasSend(audio_desc->direction());
1347 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1348 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001349 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001350 }
deadbeefab9b2d12015-10-14 11:33:11 -07001351 }
1352
1353 // Find all video rtp streams and create corresponding remote VideoTracks
1354 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001355 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001356 if (video_content->rejected) {
1357 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1358 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001359 bool default_video_track_needed =
1360 !remote_peer_supports_msid_ &&
1361 MediaContentDirectionHasSend(video_desc->direction());
1362 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1363 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001364 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001365 }
deadbeefab9b2d12015-10-14 11:33:11 -07001366 }
1367
1368 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001369 if (data_desc) {
1370 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001371 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001372 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001373 }
1374 }
1375
1376 // Iterate new_streams and notify the observer about new MediaStreams.
1377 for (size_t i = 0; i < new_streams->count(); ++i) {
1378 MediaStreamInterface* new_stream = new_streams->at(i);
1379 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001380 observer_->OnAddStream(
1381 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001382 }
1383
deadbeefbda7e0b2015-12-08 17:13:40 -08001384 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001385
1386 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001387 signaling_thread()->Post(RTC_FROM_HERE, this,
1388 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001389
1390 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1391 // TODO(deadbeef): We already had to hop to the network thread for
1392 // MaybeStartGathering...
1393 network_thread()->Invoke<void>(
1394 RTC_FROM_HERE,
1395 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1396 port_allocator_.get()));
1397 }
deadbeeffc648b62015-10-13 16:42:33 -07001398}
1399
deadbeef46c73892016-11-16 19:42:04 -08001400PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1401 return configuration_;
1402}
1403
deadbeef293e9262017-01-11 12:28:30 -08001404bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1405 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001406 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001407
1408 if (session_->local_description() &&
1409 configuration.ice_candidate_pool_size !=
1410 configuration_.ice_candidate_pool_size) {
1411 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1412 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001413 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001414 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001415
deadbeef293e9262017-01-11 12:28:30 -08001416 // The simplest (and most future-compatible) way to tell if the config was
1417 // modified in an invalid way is to copy each property we do support
1418 // modifying, then use operator==. There are far more properties we don't
1419 // support modifying than those we do, and more could be added.
1420 RTCConfiguration modified_config = configuration_;
1421 modified_config.servers = configuration.servers;
1422 modified_config.type = configuration.type;
1423 modified_config.ice_candidate_pool_size =
1424 configuration.ice_candidate_pool_size;
1425 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001426 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001427 if (configuration != modified_config) {
1428 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1429 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1430 }
1431
1432 // Note that this isn't possible through chromium, since it's an unsigned
1433 // short in WebIDL.
1434 if (configuration.ice_candidate_pool_size < 0 ||
1435 configuration.ice_candidate_pool_size > UINT16_MAX) {
1436 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1437 }
1438
1439 // Parse ICE servers before hopping to network thread.
1440 cricket::ServerAddresses stun_servers;
1441 std::vector<cricket::RelayServerConfig> turn_servers;
1442 RTCErrorType parse_error =
1443 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1444 if (parse_error != RTCErrorType::NONE) {
1445 return SafeSetError(parse_error, error);
1446 }
1447
1448 // In theory this shouldn't fail.
1449 if (!network_thread()->Invoke<bool>(
1450 RTC_FROM_HERE,
1451 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1452 stun_servers, turn_servers, modified_config.type,
1453 modified_config.ice_candidate_pool_size,
1454 modified_config.prune_turn_ports))) {
1455 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1456 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1457 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001458
deadbeefd1a38b52016-12-10 13:15:33 -08001459 // As described in JSEP, calling setConfiguration with new ICE servers or
1460 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1461 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001462 if (modified_config.servers != configuration_.servers ||
1463 modified_config.type != configuration_.type ||
1464 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001465 session_->SetNeedsIceRestartFlag();
1466 }
skvladd1f5fda2017-02-03 16:54:05 -08001467
1468 if (modified_config.ice_check_min_interval !=
1469 configuration_.ice_check_min_interval) {
1470 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1471 }
1472
deadbeef293e9262017-01-11 12:28:30 -08001473 configuration_ = modified_config;
1474 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001475}
1476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477bool PeerConnection::AddIceCandidate(
1478 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001479 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001480 if (IsClosed()) {
1481 return false;
1482 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 return session_->ProcessIceMessage(ice_candidate);
1484}
1485
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001486bool PeerConnection::RemoveIceCandidates(
1487 const std::vector<cricket::Candidate>& candidates) {
1488 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1489 return session_->RemoveRemoteIceCandidates(candidates);
1490}
1491
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001492void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001493 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001494 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001495
1496 if (session_) {
1497 session_->set_metrics_observer(uma_observer_);
1498 }
1499
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001500 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001501 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001502 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001503 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001504 uma_observer_->IncrementEnumCounter(
1505 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1506 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001507 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001508 uma_observer_->IncrementEnumCounter(
1509 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1510 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001511 }
1512 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001513}
1514
ivoc14d5dbe2016-07-04 07:06:55 -07001515bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1516 int64_t max_size_bytes) {
1517 return factory_->worker_thread()->Invoke<bool>(
1518 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1519 max_size_bytes));
1520}
1521
1522void PeerConnection::StopRtcEventLog() {
1523 factory_->worker_thread()->Invoke<void>(
1524 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1525}
1526
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001527const SessionDescriptionInterface* PeerConnection::local_description() const {
1528 return session_->local_description();
1529}
1530
1531const SessionDescriptionInterface* PeerConnection::remote_description() const {
1532 return session_->remote_description();
1533}
1534
deadbeeffe4a8a42016-12-20 17:56:17 -08001535const SessionDescriptionInterface* PeerConnection::current_local_description()
1536 const {
1537 return session_->current_local_description();
1538}
1539
1540const SessionDescriptionInterface* PeerConnection::current_remote_description()
1541 const {
1542 return session_->current_remote_description();
1543}
1544
1545const SessionDescriptionInterface* PeerConnection::pending_local_description()
1546 const {
1547 return session_->pending_local_description();
1548}
1549
1550const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1551 const {
1552 return session_->pending_remote_description();
1553}
1554
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001555void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001556 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001557 // Update stats here so that we have the most recent stats for tracks and
1558 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001559 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560
deadbeefd59daf82015-10-14 15:02:44 -07001561 session_->Close();
zhihuang77985012017-02-07 15:45:16 -08001562 event_log_.reset();
deadbeef42a42632017-03-10 15:18:00 -08001563 network_thread()->Invoke<void>(
1564 RTC_FROM_HERE,
1565 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1566 port_allocator_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567}
1568
deadbeefd59daf82015-10-14 15:02:44 -07001569void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1570 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001572 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001574 break;
deadbeefd59daf82015-10-14 15:02:44 -07001575 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1577 break;
deadbeefd59daf82015-10-14 15:02:44 -07001578 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1580 break;
deadbeefd59daf82015-10-14 15:02:44 -07001581 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1583 break;
deadbeefd59daf82015-10-14 15:02:44 -07001584 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1586 break;
deadbeefd59daf82015-10-14 15:02:44 -07001587 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001588 ChangeSignalingState(PeerConnectionInterface::kStable);
1589 break;
deadbeefd59daf82015-10-14 15:02:44 -07001590 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591 ChangeSignalingState(PeerConnectionInterface::kClosed);
1592 break;
1593 default:
1594 break;
1595 }
1596}
1597
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001598void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001599 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1601 SetSessionDescriptionMsg* param =
1602 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1603 param->observer->OnSuccess();
1604 delete param;
1605 break;
1606 }
1607 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1608 SetSessionDescriptionMsg* param =
1609 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1610 param->observer->OnFailure(param->error);
1611 delete param;
1612 break;
1613 }
deadbeefab9b2d12015-10-14 11:33:11 -07001614 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1615 CreateSessionDescriptionMsg* param =
1616 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1617 param->observer->OnFailure(param->error);
1618 delete param;
1619 break;
1620 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 case MSG_GETSTATS: {
1622 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001623 StatsReports reports;
1624 stats_->GetStats(param->track, &reports);
1625 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626 delete param;
1627 break;
1628 }
deadbeefbd292462015-12-14 18:15:29 -08001629 case MSG_FREE_DATACHANNELS: {
1630 sctp_data_channels_to_free_.clear();
1631 break;
1632 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001633 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001634 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001635 break;
1636 }
1637}
1638
deadbeefab9b2d12015-10-14 11:33:11 -07001639void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001640 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001641 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001642 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1643 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001644 signaling_thread(),
1645 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1646 stream->AddTrack(
1647 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001648 receivers_.push_back(receiver);
1649 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1650 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1651 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652}
1653
deadbeefab9b2d12015-10-14 11:33:11 -07001654void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001655 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001656 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001657 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1658 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001659 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001660 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1661 session_->video_channel()));
1662 stream->AddTrack(
1663 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001664 receivers_.push_back(receiver);
1665 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1666 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1667 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001668}
1669
deadbeef70ab1a12015-09-28 16:53:55 -07001670// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1671// description.
perkjd61bf802016-03-24 03:16:19 -07001672void PeerConnection::DestroyReceiver(const std::string& track_id) {
1673 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001674 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001675 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001676 << " doesn't exist.";
1677 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001678 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001679 receivers_.erase(it);
1680 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681}
1682
zstein6dfd53a2017-03-06 13:49:03 -08001683void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001685 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001686 // After transitioning to "closed", ignore any additional states from
1687 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001688 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001689 return;
1690 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001691 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001692 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001693}
1694
1695void PeerConnection::OnIceGatheringChange(
1696 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001697 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698 if (IsClosed()) {
1699 return;
1700 }
1701 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001702 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001703}
1704
1705void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001706 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001707 if (IsClosed()) {
1708 return;
1709 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001710 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711}
1712
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001713void PeerConnection::OnIceCandidatesRemoved(
1714 const std::vector<cricket::Candidate>& candidates) {
1715 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001716 if (IsClosed()) {
1717 return;
1718 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001719 observer_->OnIceCandidatesRemoved(candidates);
1720}
1721
Peter Thatcher54360512015-07-08 11:08:35 -07001722void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001723 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001724 if (IsClosed()) {
1725 return;
1726 }
Peter Thatcher54360512015-07-08 11:08:35 -07001727 observer_->OnIceConnectionReceivingChange(receiving);
1728}
1729
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001730void PeerConnection::ChangeSignalingState(
1731 PeerConnectionInterface::SignalingState signaling_state) {
1732 signaling_state_ = signaling_state;
1733 if (signaling_state == kClosed) {
1734 ice_connection_state_ = kIceConnectionClosed;
1735 observer_->OnIceConnectionChange(ice_connection_state_);
1736 if (ice_gathering_state_ != kIceGatheringComplete) {
1737 ice_gathering_state_ = kIceGatheringComplete;
1738 observer_->OnIceGatheringChange(ice_gathering_state_);
1739 }
1740 }
1741 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742}
1743
deadbeefeb459812015-12-15 19:24:43 -08001744void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1745 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001746 if (IsClosed()) {
1747 return;
1748 }
deadbeefeb459812015-12-15 19:24:43 -08001749 auto sender = FindSenderForTrack(track);
1750 if (sender != senders_.end()) {
1751 // We already have a sender for this track, so just change the stream_id
1752 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001753 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001754 return;
1755 }
1756
1757 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001758 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1759 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001760 signaling_thread(),
1761 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1762 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001763 senders_.push_back(new_sender);
1764 // If the sender has already been configured in SDP, we call SetSsrc,
1765 // which will connect the sender to the underlying transport. This can
1766 // occur if a local session description that contains the ID of the sender
1767 // is set before AddStream is called. It can also occur if the local
1768 // session description is not changed and RemoveStream is called, and
1769 // later AddStream is called again with the same stream.
1770 const TrackInfo* track_info =
1771 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1772 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001773 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001774 }
1775}
1776
1777// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1778// indefinitely, when we have unified plan SDP.
1779void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1780 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001781 if (IsClosed()) {
1782 return;
1783 }
deadbeefeb459812015-12-15 19:24:43 -08001784 auto sender = FindSenderForTrack(track);
1785 if (sender == senders_.end()) {
1786 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1787 << " doesn't exist.";
1788 return;
1789 }
deadbeefa601f5c2016-06-06 14:27:39 -07001790 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001791 senders_.erase(sender);
1792}
1793
1794void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1795 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001796 if (IsClosed()) {
1797 return;
1798 }
deadbeefeb459812015-12-15 19:24:43 -08001799 auto sender = FindSenderForTrack(track);
1800 if (sender != senders_.end()) {
1801 // We already have a sender for this track, so just change the stream_id
1802 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001803 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001804 return;
1805 }
1806
1807 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001808 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1809 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001810 signaling_thread(), new VideoRtpSender(track, stream->label(),
1811 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001812 senders_.push_back(new_sender);
1813 const TrackInfo* track_info =
1814 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1815 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001816 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001817 }
1818}
1819
1820void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1821 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001822 if (IsClosed()) {
1823 return;
1824 }
deadbeefeb459812015-12-15 19:24:43 -08001825 auto sender = FindSenderForTrack(track);
1826 if (sender == senders_.end()) {
1827 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1828 << " doesn't exist.";
1829 return;
1830 }
deadbeefa601f5c2016-06-06 14:27:39 -07001831 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001832 senders_.erase(sender);
1833}
1834
deadbeefab9b2d12015-10-14 11:33:11 -07001835void PeerConnection::PostSetSessionDescriptionFailure(
1836 SetSessionDescriptionObserver* observer,
1837 const std::string& error) {
1838 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1839 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001840 signaling_thread()->Post(RTC_FROM_HERE, this,
1841 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001842}
1843
1844void PeerConnection::PostCreateSessionDescriptionFailure(
1845 CreateSessionDescriptionObserver* observer,
1846 const std::string& error) {
1847 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1848 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001849 signaling_thread()->Post(RTC_FROM_HERE, this,
1850 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001851}
1852
1853bool PeerConnection::GetOptionsForOffer(
1854 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1855 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001856 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1857 // ContentInfos.
1858 if (session_->local_description()) {
1859 for (const cricket::ContentInfo& content :
1860 session_->local_description()->description()->contents()) {
1861 session_options->transport_options[content.name] =
1862 cricket::TransportOptions();
1863 }
1864 }
deadbeef46c73892016-11-16 19:42:04 -08001865 session_options->enable_ice_renomination =
1866 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001867
htaaac2dea2016-03-10 13:35:55 -08001868 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001869 return false;
1870 }
1871
deadbeeffac06552015-11-25 11:26:01 -08001872 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001873 // Offer to receive audio/video if the constraint is not set and there are
1874 // send streams, or we're currently receiving.
1875 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1876 session_options->recv_audio =
1877 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1878 !remote_audio_tracks_.empty();
1879 }
1880 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1881 session_options->recv_video =
1882 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1883 !remote_video_tracks_.empty();
1884 }
deadbeefc80741f2015-10-22 13:14:45 -07001885
zhihuang9763d562016-08-05 11:14:50 -07001886 // Intentionally unset the data channel type for RTP data channel with the
1887 // second condition. Otherwise the RTP data channels would be successfully
1888 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1889 // when building with chromium. We want to leave RTP data channels broken, so
1890 // people won't try to use them.
1891 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1892 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001893 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001894
zhihuangaf388472016-11-02 16:49:48 -07001895 session_options->bundle_enabled =
1896 session_options->bundle_enabled &&
1897 (session_options->has_audio() || session_options->has_video() ||
1898 session_options->has_data());
1899
zhihuang8f65cdf2016-05-06 18:40:30 -07001900 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001901 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001902 return true;
1903}
1904
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001905void PeerConnection::InitializeOptionsForAnswer(
1906 cricket::MediaSessionOptions* session_options) {
1907 session_options->recv_audio = false;
1908 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001909 session_options->enable_ice_renomination =
1910 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001911}
1912
htaa2a49d92016-03-04 02:51:39 -08001913void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001914 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001915 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1916 // ContentInfos.
1917 if (session_->remote_description()) {
1918 // Initialize the transport_options map.
1919 for (const cricket::ContentInfo& content :
1920 session_->remote_description()->description()->contents()) {
1921 session_options->transport_options[content.name] =
1922 cricket::TransportOptions();
1923 }
1924 }
deadbeeffac06552015-11-25 11:26:01 -08001925 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001926 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1927 // are not signaled in the SDP so does not go through that path and must be
1928 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001929 // Intentionally unset the data channel type for RTP data channel. Otherwise
1930 // the RTP data channels would be successfully negotiated by default and the
1931 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1932 // We want to leave RTP data channels broken, so people won't try to use them.
1933 if (session_->data_channel_type() != cricket::DCT_RTP) {
1934 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001935 }
zhihuangaf388472016-11-02 16:49:48 -07001936 session_options->bundle_enabled =
1937 session_options->bundle_enabled &&
1938 (session_options->has_audio() || session_options->has_video() ||
1939 session_options->has_data());
1940
jbauchcb560652016-08-04 05:20:32 -07001941 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001942}
1943
1944bool PeerConnection::GetOptionsForAnswer(
1945 const MediaConstraintsInterface* constraints,
1946 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001947 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001948 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1949 return false;
1950 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001951 session_options->rtcp_cname = rtcp_cname_;
1952
htaa2a49d92016-03-04 02:51:39 -08001953 FinishOptionsForAnswer(session_options);
1954 return true;
1955}
1956
1957bool PeerConnection::GetOptionsForAnswer(
1958 const RTCOfferAnswerOptions& options,
1959 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001960 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001961 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001962 return false;
1963 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001964 session_options->rtcp_cname = rtcp_cname_;
1965
htaa2a49d92016-03-04 02:51:39 -08001966 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001967 return true;
1968}
1969
deadbeeffaac4972015-11-12 15:33:07 -08001970void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1971 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001972 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1973 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001974}
1975
deadbeefab9b2d12015-10-14 11:33:11 -07001976void PeerConnection::UpdateRemoteStreamsList(
1977 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001978 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001979 cricket::MediaType media_type,
1980 StreamCollection* new_streams) {
1981 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1982
1983 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001984 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001985 auto track_it = current_tracks->begin();
1986 while (track_it != current_tracks->end()) {
1987 const TrackInfo& info = *track_it;
1988 const cricket::StreamParams* params =
1989 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001990 bool track_exists = params && params->id == info.track_id;
1991 // If this is a default track, and we still need it, don't remove it.
1992 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1993 track_exists) {
1994 ++track_it;
1995 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001996 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1997 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001998 }
1999 }
2000
2001 // Find new and active tracks.
2002 for (const cricket::StreamParams& params : streams) {
2003 // The sync_label is the MediaStream label and the |stream.id| is the
2004 // track id.
2005 const std::string& stream_label = params.sync_label;
2006 const std::string& track_id = params.id;
2007 uint32_t ssrc = params.first_ssrc();
2008
2009 rtc::scoped_refptr<MediaStreamInterface> stream =
2010 remote_streams_->find(stream_label);
2011 if (!stream) {
2012 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002013 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2014 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002015 remote_streams_->AddStream(stream);
2016 new_streams->AddStream(stream);
2017 }
2018
2019 const TrackInfo* track_info =
2020 FindTrackInfo(*current_tracks, stream_label, track_id);
2021 if (!track_info) {
2022 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2023 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2024 }
2025 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002026
2027 // Add default track if necessary.
2028 if (default_track_needed) {
2029 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2030 remote_streams_->find(kDefaultStreamLabel);
2031 if (!default_stream) {
2032 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002033 default_stream = MediaStreamProxy::Create(
2034 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002035 remote_streams_->AddStream(default_stream);
2036 new_streams->AddStream(default_stream);
2037 }
2038 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2039 ? kDefaultAudioTrackLabel
2040 : kDefaultVideoTrackLabel;
2041 const TrackInfo* default_track_info =
2042 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2043 if (!default_track_info) {
2044 current_tracks->push_back(
2045 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2046 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2047 }
2048 }
deadbeefab9b2d12015-10-14 11:33:11 -07002049}
2050
2051void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2052 const std::string& track_id,
2053 uint32_t ssrc,
2054 cricket::MediaType media_type) {
2055 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2056
2057 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002058 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002059 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002060 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002061 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002062 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002063 }
2064}
2065
2066void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2067 const std::string& track_id,
2068 cricket::MediaType media_type) {
2069 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2070
2071 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002072 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2073 // will be notified which will end the AudioRtpReceiver::track().
2074 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002075 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2076 stream->FindAudioTrack(track_id);
2077 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002078 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002079 }
2080 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002081 // Stopping or destroying a VideoRtpReceiver will end the
2082 // VideoRtpReceiver::track().
2083 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002084 rtc::scoped_refptr<VideoTrackInterface> video_track =
2085 stream->FindVideoTrack(track_id);
2086 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002087 // There's no guarantee the track is still available, e.g. the track may
2088 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002089 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002090 }
2091 } else {
nisseede5da42017-01-12 05:15:36 -08002092 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002093 }
2094}
2095
2096void PeerConnection::UpdateEndedRemoteMediaStreams() {
2097 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2098 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2099 MediaStreamInterface* stream = remote_streams_->at(i);
2100 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2101 streams_to_remove.push_back(stream);
2102 }
2103 }
2104
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002105 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002106 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002107 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002108 }
2109}
2110
deadbeefab9b2d12015-10-14 11:33:11 -07002111void PeerConnection::UpdateLocalTracks(
2112 const std::vector<cricket::StreamParams>& streams,
2113 cricket::MediaType media_type) {
2114 TrackInfos* current_tracks = GetLocalTracks(media_type);
2115
2116 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2117 // don't match the new StreamParam.
2118 TrackInfos::iterator track_it = current_tracks->begin();
2119 while (track_it != current_tracks->end()) {
2120 const TrackInfo& info = *track_it;
2121 const cricket::StreamParams* params =
2122 cricket::GetStreamBySsrc(streams, info.ssrc);
2123 if (!params || params->id != info.track_id ||
2124 params->sync_label != info.stream_label) {
2125 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2126 media_type);
2127 track_it = current_tracks->erase(track_it);
2128 } else {
2129 ++track_it;
2130 }
2131 }
2132
2133 // Find new and active tracks.
2134 for (const cricket::StreamParams& params : streams) {
2135 // The sync_label is the MediaStream label and the |stream.id| is the
2136 // track id.
2137 const std::string& stream_label = params.sync_label;
2138 const std::string& track_id = params.id;
2139 uint32_t ssrc = params.first_ssrc();
2140 const TrackInfo* track_info =
2141 FindTrackInfo(*current_tracks, stream_label, track_id);
2142 if (!track_info) {
2143 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2144 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2145 }
2146 }
2147}
2148
2149void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2150 const std::string& track_id,
2151 uint32_t ssrc,
2152 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002153 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002154 if (!sender) {
2155 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2156 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002157 return;
2158 }
2159
deadbeeffac06552015-11-25 11:26:01 -08002160 if (sender->media_type() != media_type) {
2161 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2162 << " description with an unexpected media type.";
2163 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002164 }
deadbeeffac06552015-11-25 11:26:01 -08002165
2166 sender->set_stream_id(stream_label);
2167 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002168}
2169
2170void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2171 const std::string& track_id,
2172 uint32_t ssrc,
2173 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002174 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002175 if (!sender) {
2176 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002177 // SessionDescriptions has been renegotiated.
2178 return;
2179 }
deadbeeffac06552015-11-25 11:26:01 -08002180
2181 // A sender has been removed from the SessionDescription but it's still
2182 // associated with the PeerConnection. This only occurs if the SDP doesn't
2183 // match with the calls to CreateSender, AddStream and RemoveStream.
2184 if (sender->media_type() != media_type) {
2185 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2186 << " description with an unexpected media type.";
2187 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002188 }
deadbeeffac06552015-11-25 11:26:01 -08002189
2190 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002191}
2192
2193void PeerConnection::UpdateLocalRtpDataChannels(
2194 const cricket::StreamParamsVec& streams) {
2195 std::vector<std::string> existing_channels;
2196
2197 // Find new and active data channels.
2198 for (const cricket::StreamParams& params : streams) {
2199 // |it->sync_label| is actually the data channel label. The reason is that
2200 // we use the same naming of data channels as we do for
2201 // MediaStreams and Tracks.
2202 // For MediaStreams, the sync_label is the MediaStream label and the
2203 // track label is the same as |streamid|.
2204 const std::string& channel_label = params.sync_label;
2205 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002206 if (data_channel_it == rtp_data_channels_.end()) {
2207 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002208 continue;
2209 }
2210 // Set the SSRC the data channel should use for sending.
2211 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2212 existing_channels.push_back(data_channel_it->first);
2213 }
2214
2215 UpdateClosingRtpDataChannels(existing_channels, true);
2216}
2217
2218void PeerConnection::UpdateRemoteRtpDataChannels(
2219 const cricket::StreamParamsVec& streams) {
2220 std::vector<std::string> existing_channels;
2221
2222 // Find new and active data channels.
2223 for (const cricket::StreamParams& params : streams) {
2224 // The data channel label is either the mslabel or the SSRC if the mslabel
2225 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2226 std::string label = params.sync_label.empty()
2227 ? rtc::ToString(params.first_ssrc())
2228 : params.sync_label;
2229 auto data_channel_it = rtp_data_channels_.find(label);
2230 if (data_channel_it == rtp_data_channels_.end()) {
2231 // This is a new data channel.
2232 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2233 } else {
2234 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2235 }
2236 existing_channels.push_back(label);
2237 }
2238
2239 UpdateClosingRtpDataChannels(existing_channels, false);
2240}
2241
2242void PeerConnection::UpdateClosingRtpDataChannels(
2243 const std::vector<std::string>& active_channels,
2244 bool is_local_update) {
2245 auto it = rtp_data_channels_.begin();
2246 while (it != rtp_data_channels_.end()) {
2247 DataChannel* data_channel = it->second;
2248 if (std::find(active_channels.begin(), active_channels.end(),
2249 data_channel->label()) != active_channels.end()) {
2250 ++it;
2251 continue;
2252 }
2253
2254 if (is_local_update) {
2255 data_channel->SetSendSsrc(0);
2256 } else {
2257 data_channel->RemotePeerRequestClose();
2258 }
2259
2260 if (data_channel->state() == DataChannel::kClosed) {
2261 rtp_data_channels_.erase(it);
2262 it = rtp_data_channels_.begin();
2263 } else {
2264 ++it;
2265 }
2266 }
2267}
2268
2269void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2270 uint32_t remote_ssrc) {
2271 rtc::scoped_refptr<DataChannel> channel(
2272 InternalCreateDataChannel(label, nullptr));
2273 if (!channel.get()) {
2274 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2275 << "CreateDataChannel failed.";
2276 return;
2277 }
2278 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002279 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2280 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002281 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002282}
2283
2284rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2285 const std::string& label,
2286 const InternalDataChannelInit* config) {
2287 if (IsClosed()) {
2288 return nullptr;
2289 }
2290 if (session_->data_channel_type() == cricket::DCT_NONE) {
2291 LOG(LS_ERROR)
2292 << "InternalCreateDataChannel: Data is not supported in this call.";
2293 return nullptr;
2294 }
2295 InternalDataChannelInit new_config =
2296 config ? (*config) : InternalDataChannelInit();
2297 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2298 if (new_config.id < 0) {
2299 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002300 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002301 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2302 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2303 return nullptr;
2304 }
2305 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2306 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2307 << "because the id is already in use or out of range.";
2308 return nullptr;
2309 }
2310 }
2311
2312 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2313 session_.get(), session_->data_channel_type(), label, new_config));
2314 if (!channel) {
2315 sid_allocator_.ReleaseSid(new_config.id);
2316 return nullptr;
2317 }
2318
2319 if (channel->data_channel_type() == cricket::DCT_RTP) {
2320 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2321 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2322 << " already exists.";
2323 return nullptr;
2324 }
2325 rtp_data_channels_[channel->label()] = channel;
2326 } else {
2327 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2328 sctp_data_channels_.push_back(channel);
2329 channel->SignalClosed.connect(this,
2330 &PeerConnection::OnSctpDataChannelClosed);
2331 }
2332
hbos82ebe022016-11-14 01:41:09 -08002333 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002334 return channel;
2335}
2336
2337bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002338#ifdef HAVE_QUIC
2339 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2340 (session_->quic_data_transport() &&
2341 session_->quic_data_transport()->HasDataChannels());
2342#else
deadbeefab9b2d12015-10-14 11:33:11 -07002343 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002344#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002345}
2346
2347void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2348 for (const auto& channel : sctp_data_channels_) {
2349 if (channel->id() < 0) {
2350 int sid;
2351 if (!sid_allocator_.AllocateSid(role, &sid)) {
2352 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2353 continue;
2354 }
2355 channel->SetSctpSid(sid);
2356 }
2357 }
2358}
2359
2360void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002361 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002362 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2363 ++it) {
2364 if (it->get() == channel) {
2365 if (channel->id() >= 0) {
2366 sid_allocator_.ReleaseSid(channel->id());
2367 }
deadbeefbd292462015-12-14 18:15:29 -08002368 // Since this method is triggered by a signal from the DataChannel,
2369 // we can't free it directly here; we need to free it asynchronously.
2370 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002371 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002372 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2373 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002374 return;
2375 }
2376 }
2377}
2378
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002379void PeerConnection::OnVoiceChannelCreated() {
2380 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2381 session_->voice_channel(), senders_, receivers_,
2382 cricket::MEDIA_TYPE_AUDIO);
2383}
2384
deadbeefab9b2d12015-10-14 11:33:11 -07002385void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002386 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2387 cricket::VoiceChannel>(
2388 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2389}
2390
2391void PeerConnection::OnVideoChannelCreated() {
2392 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2393 session_->video_channel(), senders_, receivers_,
2394 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002395}
2396
2397void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002398 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2399 cricket::VideoChannel>(
2400 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002401}
2402
2403void PeerConnection::OnDataChannelCreated() {
2404 for (const auto& channel : sctp_data_channels_) {
2405 channel->OnTransportChannelCreated();
2406 }
2407}
2408
2409void PeerConnection::OnDataChannelDestroyed() {
2410 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2411 // DataChannel may callback to us and try to modify the list.
2412 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2413 temp_rtp_dcs.swap(rtp_data_channels_);
2414 for (const auto& kv : temp_rtp_dcs) {
2415 kv.second->OnTransportChannelDestroyed();
2416 }
2417
2418 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2419 temp_sctp_dcs.swap(sctp_data_channels_);
2420 for (const auto& channel : temp_sctp_dcs) {
2421 channel->OnTransportChannelDestroyed();
2422 }
2423}
2424
2425void PeerConnection::OnDataChannelOpenMessage(
2426 const std::string& label,
2427 const InternalDataChannelInit& config) {
2428 rtc::scoped_refptr<DataChannel> channel(
2429 InternalCreateDataChannel(label, &config));
2430 if (!channel.get()) {
2431 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2432 return;
2433 }
2434
deadbeefa601f5c2016-06-06 14:27:39 -07002435 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2436 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002437 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002438}
2439
deadbeefa601f5c2016-06-06 14:27:39 -07002440RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2441 auto it = std::find_if(
2442 senders_.begin(), senders_.end(),
2443 [id](const rtc::scoped_refptr<
2444 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2445 return sender->id() == id;
2446 });
2447 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002448}
2449
deadbeefa601f5c2016-06-06 14:27:39 -07002450std::vector<
2451 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002452PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2453 return std::find_if(
2454 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002455 [track](const rtc::scoped_refptr<
2456 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002457 return sender->track() == track;
2458 });
2459}
2460
deadbeefa601f5c2016-06-06 14:27:39 -07002461std::vector<rtc::scoped_refptr<
2462 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002463PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002464 return std::find_if(
2465 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002466 [track_id](const rtc::scoped_refptr<
2467 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002468 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002469 });
2470}
2471
deadbeefab9b2d12015-10-14 11:33:11 -07002472PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2473 cricket::MediaType media_type) {
2474 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2475 media_type == cricket::MEDIA_TYPE_VIDEO);
2476 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2477 : &remote_video_tracks_;
2478}
2479
2480PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2481 cricket::MediaType media_type) {
2482 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2483 media_type == cricket::MEDIA_TYPE_VIDEO);
2484 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2485 : &local_video_tracks_;
2486}
2487
2488const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2489 const PeerConnection::TrackInfos& infos,
2490 const std::string& stream_label,
2491 const std::string track_id) const {
2492 for (const TrackInfo& track_info : infos) {
2493 if (track_info.stream_label == stream_label &&
2494 track_info.track_id == track_id) {
2495 return &track_info;
2496 }
2497 }
2498 return nullptr;
2499}
2500
2501DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2502 for (const auto& channel : sctp_data_channels_) {
2503 if (channel->id() == sid) {
2504 return channel;
2505 }
2506 }
2507 return nullptr;
2508}
2509
deadbeef91dd5672016-05-18 16:55:30 -07002510bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002511 const RTCConfiguration& configuration) {
2512 cricket::ServerAddresses stun_servers;
2513 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002514 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2515 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002516 return false;
2517 }
2518
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002519 port_allocator_->Initialize();
2520
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002521 // To handle both internal and externally created port allocator, we will
2522 // enable BUNDLE here.
2523 int portallocator_flags = port_allocator_->flags();
2524 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002525 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2526 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002527 // 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);
sprangc1b57a12017-02-28 08:50:47 -08002531 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2532 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002533 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2534 }
2535
zhihuangb09b3f92017-03-07 14:40:51 -08002536 if (configuration.disable_ipv6_on_wifi) {
2537 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2538 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2539 }
2540
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002541 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2542 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2543 LOG(LS_INFO) << "TCP candidates are disabled.";
2544 }
2545
honghaiz60347052016-05-31 18:29:12 -07002546 if (configuration.candidate_network_policy ==
2547 kCandidateNetworkPolicyLowCost) {
2548 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2549 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2550 }
2551
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002552 port_allocator_->set_flags(portallocator_flags);
2553 // No step delay is used while allocating ports.
2554 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2555 port_allocator_->set_candidate_filter(
2556 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2557
2558 // Call this last since it may create pooled allocator sessions using the
2559 // properties set above.
2560 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002561 configuration.ice_candidate_pool_size,
2562 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002563 return true;
2564}
2565
deadbeef91dd5672016-05-18 16:55:30 -07002566bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002567 const cricket::ServerAddresses& stun_servers,
2568 const std::vector<cricket::RelayServerConfig>& turn_servers,
2569 IceTransportsType type,
2570 int candidate_pool_size,
2571 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002572 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002573 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002574 // Call this last since it may create pooled allocator sessions using the
2575 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002576 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002577 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002578}
2579
ivoc14d5dbe2016-07-04 07:06:55 -07002580bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2581 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002582 if (!event_log_) {
2583 return false;
2584 }
skvlad11a9cbf2016-10-07 11:53:05 -07002585 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002586}
2587
2588void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002589 if (event_log_) {
2590 event_log_->StopLogging();
2591 }
ivoc14d5dbe2016-07-04 07:06:55 -07002592}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593} // namespace webrtc