blob: ca646651ef59f32f3464bb32dbe37845f751d1ca [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
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/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/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070037#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010038#include "webrtc/base/trace_event.h"
ossuf515ab82016-12-07 04:52:58 -080039#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070040#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kjellandera96e2d72016-02-04 23:52:28 -080041#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010042#include "webrtc/pc/channelmanager.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
45namespace {
46
deadbeefab9b2d12015-10-14 11:33:11 -070047using webrtc::DataChannel;
48using webrtc::MediaConstraintsInterface;
49using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050using webrtc::PeerConnectionInterface;
deadbeef7a5fa6c2016-12-24 00:47:59 -080051using webrtc::RTCError;
52using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070053using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080054using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070055using webrtc::RtpSenderProxy;
56using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070057using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
deadbeefab9b2d12015-10-14 11:33:11 -070059static const char kDefaultStreamLabel[] = "default";
60static const char kDefaultAudioTrackLabel[] = "defaulta0";
61static const char kDefaultVideoTrackLabel[] = "defaultv0";
62
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063// The min number of tokens must present in Turn host uri.
64// e.g. user@turn.example.org
65static const size_t kTurnHostTokensNum = 2;
66// Number of tokens must be preset when TURN uri has transport param.
67static const size_t kTurnTransportTokensNum = 2;
68// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000069static const int kDefaultStunPort = 3478;
70static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
73// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070074static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075
zhihuang8f65cdf2016-05-06 18:40:30 -070076// The length of RTCP CNAMEs.
77static const int kRtcpCnameLength = 16;
78
deadbeef0a6c4ca2015-10-06 11:38:28 -070079// NOTE: A loop below assumes that the first value of this enum is 0 and all
80// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070082 STUN = 0, // Indicates a STUN server.
83 STUNS, // Indicates a STUN server used with a TLS session.
84 TURN, // Indicates a TURN server
85 TURNS, // Indicates a TURN server used with a TLS session.
86 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087};
tfarina5237aaf2015-11-10 23:44:30 -080088static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070089 "kValidIceServiceTypes must have as many strings as ServiceType "
90 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091
92enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000093 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070095 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080097 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098};
99
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000100struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101 explicit SetSessionDescriptionMsg(
102 webrtc::SetSessionDescriptionObserver* observer)
103 : observer(observer) {
104 }
105
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000106 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 std::string error;
108};
109
deadbeefab9b2d12015-10-14 11:33:11 -0700110struct CreateSessionDescriptionMsg : public rtc::MessageData {
111 explicit CreateSessionDescriptionMsg(
112 webrtc::CreateSessionDescriptionObserver* observer)
113 : observer(observer) {}
114
115 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
116 std::string error;
117};
118
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000119struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000120 GetStatsMsg(webrtc::StatsObserver* observer,
121 webrtc::MediaStreamTrackInterface* track)
122 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000123 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000124 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000125 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000126};
127
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000128// |in_str| should be of format
129// stunURI = scheme ":" stun-host [ ":" stun-port ]
130// scheme = "stun" / "stuns"
131// stun-host = IP-literal / IPv4address / reg-name
132// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700133//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000134// draft-petithuguenin-behave-turn-uris-01
135// turnURI = scheme ":" turn-host [ ":" turn-port ]
136// turn-host = username@IP-literal / IPv4address / reg-name
137bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
138 ServiceType* service_type,
139 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200140 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700141 if (colonpos == std::string::npos) {
142 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000143 return false;
144 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700145 if ((colonpos + 1) == in_str.length()) {
146 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
147 return false;
148 }
149 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800150 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700151 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000152 *service_type = static_cast<ServiceType>(i);
153 break;
154 }
155 }
156 if (*service_type == INVALID) {
157 return false;
158 }
159 *hostname = in_str.substr(colonpos + 1, std::string::npos);
160 return true;
161}
162
deadbeef0a6c4ca2015-10-06 11:38:28 -0700163bool ParsePort(const std::string& in_str, int* port) {
164 // Make sure port only contains digits. FromString doesn't check this.
165 for (const char& c : in_str) {
166 if (!std::isdigit(c)) {
167 return false;
168 }
169 }
170 return rtc::FromString(in_str, port);
171}
172
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000173// This method parses IPv6 and IPv4 literal strings, along with hostnames in
174// standard hostname:port format.
175// Consider following formats as correct.
176// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700177// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000178bool ParseHostnameAndPortFromString(const std::string& in_str,
179 std::string* host,
180 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700181 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000182 if (in_str.at(0) == '[') {
183 std::string::size_type closebracket = in_str.rfind(']');
184 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000185 std::string::size_type colonpos = in_str.find(':', closebracket);
186 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700187 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
188 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000189 return false;
190 }
191 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700192 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000193 } else {
194 return false;
195 }
196 } else {
197 std::string::size_type colonpos = in_str.find(':');
198 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700199 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000200 return false;
201 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700202 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000203 } else {
204 *host = in_str;
205 }
206 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700207 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000208}
209
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800210// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700211// by parsing |url| and using the username/password in |server|.
deadbeef7a5fa6c2016-12-24 00:47:59 -0800212RTCErrorType ParseIceServerUrl(
213 const PeerConnectionInterface::IceServer& server,
214 const std::string& url,
215 cricket::ServerAddresses* stun_servers,
216 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000217 // draft-nandakumar-rtcweb-stun-uri-01
218 // stunURI = scheme ":" stun-host [ ":" stun-port ]
219 // scheme = "stun" / "stuns"
220 // stun-host = IP-literal / IPv4address / reg-name
221 // stun-port = *DIGIT
222
223 // draft-petithuguenin-behave-turn-uris-01
224 // turnURI = scheme ":" turn-host [ ":" turn-port ]
225 // [ "?transport=" transport ]
226 // scheme = "turn" / "turns"
227 // transport = "udp" / "tcp" / transport-ext
228 // transport-ext = 1*unreserved
229 // turn-host = IP-literal / IPv4address / reg-name
230 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800231 RTC_DCHECK(stun_servers != nullptr);
232 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200233 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800234 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700235 RTC_DCHECK(!url.empty());
hnslbd44bb02016-12-12 03:14:30 -0800236 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200237 std::string uri_without_transport = tokens[0];
238 // Let's look into transport= param, if it exists.
239 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
240 std::string uri_transport_param = tokens[1];
hnslbd44bb02016-12-12 03:14:30 -0800241 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
242 if (tokens[0] != kTransport) {
243 LOG(LS_WARNING) << "Invalid transport parameter key.";
deadbeef7a5fa6c2016-12-24 00:47:59 -0800244 return RTCErrorType::SYNTAX_ERROR;
hnslbd44bb02016-12-12 03:14:30 -0800245 }
246 if (tokens.size() < 2 ||
247 !cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
248 (turn_transport_type != cricket::PROTO_UDP &&
249 turn_transport_type != cricket::PROTO_TCP)) {
250 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef7a5fa6c2016-12-24 00:47:59 -0800251 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000252 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200253 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200255 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700256 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200257 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
258 &service_type,
259 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700260 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
deadbeef7a5fa6c2016-12-24 00:47:59 -0800261 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200262 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000263
deadbeef0a6c4ca2015-10-06 11:38:28 -0700264 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
265 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200266
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200267 // Let's break hostname.
268 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
270
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200271 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700272 if (tokens.size() > kTurnHostTokensNum) {
273 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef7a5fa6c2016-12-24 00:47:59 -0800274 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700275 }
276 if (tokens.size() == kTurnHostTokensNum) {
277 if (tokens[0].empty() || tokens[1].empty()) {
278 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
deadbeef7a5fa6c2016-12-24 00:47:59 -0800279 return RTCErrorType::SYNTAX_ERROR;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700280 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200281 username.assign(rtc::s_url_decode(tokens[0]));
282 hoststring = tokens[1];
283 } else {
284 hoststring = tokens[0];
285 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000286
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200287 int port = kDefaultStunPort;
288 if (service_type == TURNS) {
289 port = kDefaultStunTlsPort;
hnsl277b2502016-12-13 05:17:23 -0800290 turn_transport_type = cricket::PROTO_TLS;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200291 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000292
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200293 std::string address;
294 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700295 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
deadbeef7a5fa6c2016-12-24 00:47:59 -0800296 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000298
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 if (port <= 0 || port > 0xffff) {
300 LOG(WARNING) << "Invalid port: " << port;
deadbeef7a5fa6c2016-12-24 00:47:59 -0800301 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000303
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200304 switch (service_type) {
305 case STUN:
306 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800307 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200308 break;
309 case TURN:
310 case TURNS: {
deadbeef7a5fa6c2016-12-24 00:47:59 -0800311 if (username.empty() || server.password.empty()) {
312 // The WebRTC spec requires throwing an InvalidAccessError when username
313 // or credential are ommitted; this is the native equivalent.
314 return RTCErrorType::INVALID_PARAMETER;
315 }
magjedd5236e22016-12-20 02:22:06 -0800316 turn_servers->push_back(cricket::RelayServerConfig(
317 address, port, username, server.password, turn_transport_type));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200318 break;
319 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200320 default:
deadbeef7a5fa6c2016-12-24 00:47:59 -0800321 // We shouldn't get to this point with an invalid service_type, we should
322 // have returned an error already.
323 RTC_DCHECK(false) << "Unexpected service type";
324 return RTCErrorType::INTERNAL_ERROR;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200325 }
deadbeef7a5fa6c2016-12-24 00:47:59 -0800326 return RTCErrorType::NONE;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200327}
328
deadbeefab9b2d12015-10-14 11:33:11 -0700329// Check if we can send |new_stream| on a PeerConnection.
330bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
331 webrtc::MediaStreamInterface* new_stream) {
332 if (!new_stream || !current_streams) {
333 return false;
334 }
335 if (current_streams->find(new_stream->label()) != nullptr) {
336 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
337 << " is already added.";
338 return false;
339 }
340 return true;
341}
342
343bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
344 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
345}
346
deadbeef5e97fb52015-10-15 12:49:08 -0700347// If the direction is "recvonly" or "inactive", treat the description
348// as containing no streams.
349// See: https://code.google.com/p/webrtc/issues/detail?id=5054
350std::vector<cricket::StreamParams> GetActiveStreams(
351 const cricket::MediaContentDescription* desc) {
352 return MediaContentDirectionHasSend(desc->direction())
353 ? desc->streams()
354 : std::vector<cricket::StreamParams>();
355}
356
deadbeefab9b2d12015-10-14 11:33:11 -0700357bool IsValidOfferToReceiveMedia(int value) {
358 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
359 return (value >= Options::kUndefined) &&
360 (value <= Options::kMaxOfferToReceiveMedia);
361}
362
363// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800364void AddSendStreams(
365 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700366 const std::vector<rtc::scoped_refptr<
367 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800368 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
369 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700370 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800371 for (const auto& sender : senders) {
372 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700373 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700374 }
375
376 // Check for data channels.
377 for (const auto& kv : rtp_data_channels) {
378 const DataChannel* channel = kv.second;
379 if (channel->state() == DataChannel::kConnecting ||
380 channel->state() == DataChannel::kOpen) {
381 // |streamid| and |sync_label| are both set to the DataChannel label
382 // here so they can be signaled the same way as MediaStreams and Tracks.
383 // For MediaStreams, the sync_label is the MediaStream label and the
384 // track label is the same as |streamid|.
385 const std::string& streamid = channel->label();
386 const std::string& sync_label = channel->label();
387 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
388 sync_label);
389 }
390 }
391}
392
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700393uint32_t ConvertIceTransportTypeToCandidateFilter(
394 PeerConnectionInterface::IceTransportsType type) {
395 switch (type) {
396 case PeerConnectionInterface::kNone:
397 return cricket::CF_NONE;
398 case PeerConnectionInterface::kRelay:
399 return cricket::CF_RELAY;
400 case PeerConnectionInterface::kNoHost:
401 return (cricket::CF_ALL & ~cricket::CF_HOST);
402 case PeerConnectionInterface::kAll:
403 return cricket::CF_ALL;
404 default:
405 ASSERT(false);
406 }
407 return cricket::CF_NONE;
408}
409
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700410// Helper method to set a voice/video channel on all applicable senders
411// and receivers when one is created/destroyed by WebRtcSession.
412//
413// Used by On(Voice|Video)Channel(Created|Destroyed)
414template <class SENDER,
415 class RECEIVER,
416 class CHANNEL,
417 class SENDERS,
418 class RECEIVERS>
419void SetChannelOnSendersAndReceivers(CHANNEL* channel,
420 SENDERS& senders,
421 RECEIVERS& receivers,
422 cricket::MediaType media_type) {
423 for (auto& sender : senders) {
424 if (sender->media_type() == media_type) {
425 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
426 }
427 }
428 for (auto& receiver : receivers) {
429 if (receiver->media_type() == media_type) {
430 if (!channel) {
431 receiver->internal()->Stop();
432 }
433 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
434 }
435 }
436}
437
deadbeef7a5fa6c2016-12-24 00:47:59 -0800438// Helper to set an error and return from a method.
439bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
440 if (error) {
441 error->set_type(type);
442 }
443 return type == webrtc::RTCErrorType::NONE;
444}
445
deadbeef0a6c4ca2015-10-06 11:38:28 -0700446} // namespace
447
448namespace webrtc {
449
deadbeef7a5fa6c2016-12-24 00:47:59 -0800450static const char* const kRTCErrorTypeNames[] = {
deadbeef3edec7c2016-12-10 11:44:26 -0800451 "NONE",
452 "UNSUPPORTED_PARAMETER",
453 "INVALID_PARAMETER",
454 "INVALID_RANGE",
455 "SYNTAX_ERROR",
456 "INVALID_STATE",
457 "INVALID_MODIFICATION",
458 "NETWORK_ERROR",
459 "INTERNAL_ERROR",
460};
deadbeef7a5fa6c2016-12-24 00:47:59 -0800461static_assert(static_cast<int>(RTCErrorType::INTERNAL_ERROR) ==
462 (arraysize(kRTCErrorTypeNames) - 1),
463 "kRTCErrorTypeNames must have as many strings as RTCErrorType "
464 "has values.");
deadbeef3edec7c2016-12-10 11:44:26 -0800465
deadbeef7a5fa6c2016-12-24 00:47:59 -0800466std::ostream& operator<<(std::ostream& stream, RTCErrorType error) {
deadbeef3edec7c2016-12-10 11:44:26 -0800467 int index = static_cast<int>(error);
deadbeef7a5fa6c2016-12-24 00:47:59 -0800468 return stream << kRTCErrorTypeNames[index];
469}
470
471bool PeerConnectionInterface::RTCConfiguration::operator==(
472 const PeerConnectionInterface::RTCConfiguration& o) const {
473 // This static_assert prevents us from accidentally breaking operator==.
474 struct stuff_being_tested_for_equality {
475 IceTransportsType type;
476 IceServers servers;
477 BundlePolicy bundle_policy;
478 RtcpMuxPolicy rtcp_mux_policy;
479 TcpCandidatePolicy tcp_candidate_policy;
480 CandidateNetworkPolicy candidate_network_policy;
481 int audio_jitter_buffer_max_packets;
482 bool audio_jitter_buffer_fast_accelerate;
483 int ice_connection_receiving_timeout;
484 int ice_backup_candidate_pair_ping_interval;
485 ContinualGatheringPolicy continual_gathering_policy;
486 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
487 bool prioritize_most_likely_ice_candidate_pairs;
488 struct cricket::MediaConfig media_config;
489 bool disable_ipv6;
490 bool enable_rtp_data_channel;
491 bool enable_quic;
492 rtc::Optional<int> screencast_min_bitrate;
493 rtc::Optional<bool> combined_audio_video_bwe;
494 rtc::Optional<bool> enable_dtls_srtp;
495 int ice_candidate_pool_size;
496 bool prune_turn_ports;
497 bool presume_writable_when_fully_relayed;
498 bool enable_ice_renomination;
499 bool redetermine_role_on_ice_restart;
500 };
501 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
502 "Did you add something to RTCConfiguration and forget to "
503 "update operator==?");
504 return type == o.type && servers == o.servers &&
505 bundle_policy == o.bundle_policy &&
506 rtcp_mux_policy == o.rtcp_mux_policy &&
507 tcp_candidate_policy == o.tcp_candidate_policy &&
508 candidate_network_policy == o.candidate_network_policy &&
509 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
510 audio_jitter_buffer_fast_accelerate ==
511 o.audio_jitter_buffer_fast_accelerate &&
512 ice_connection_receiving_timeout ==
513 o.ice_connection_receiving_timeout &&
514 ice_backup_candidate_pair_ping_interval ==
515 o.ice_backup_candidate_pair_ping_interval &&
516 continual_gathering_policy == o.continual_gathering_policy &&
517 certificates == o.certificates &&
518 prioritize_most_likely_ice_candidate_pairs ==
519 o.prioritize_most_likely_ice_candidate_pairs &&
520 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
521 enable_rtp_data_channel == o.enable_rtp_data_channel &&
522 enable_quic == o.enable_quic &&
523 screencast_min_bitrate == o.screencast_min_bitrate &&
524 combined_audio_video_bwe == o.combined_audio_video_bwe &&
525 enable_dtls_srtp == o.enable_dtls_srtp &&
526 ice_candidate_pool_size == o.ice_candidate_pool_size &&
527 prune_turn_ports == o.prune_turn_ports &&
528 presume_writable_when_fully_relayed ==
529 o.presume_writable_when_fully_relayed &&
530 enable_ice_renomination == o.enable_ice_renomination &&
531 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart;
532}
533
534bool PeerConnectionInterface::RTCConfiguration::operator!=(
535 const PeerConnectionInterface::RTCConfiguration& o) const {
536 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800537}
538
zhihuang8f65cdf2016-05-06 18:40:30 -0700539// Generate a RTCP CNAME when a PeerConnection is created.
540std::string GenerateRtcpCname() {
541 std::string cname;
542 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
543 LOG(LS_ERROR) << "Failed to generate CNAME.";
544 RTC_DCHECK(false);
545 }
546 return cname;
547}
548
htaa2a49d92016-03-04 02:51:39 -0800549bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700550 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800551 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700552 cricket::MediaSessionOptions* session_options) {
553 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
554 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
555 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
556 return false;
557 }
558
htaaac2dea2016-03-10 13:35:55 -0800559 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700560 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700561 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800562 } else {
563 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700564 }
htaaac2dea2016-03-10 13:35:55 -0800565 // For offers, we only offer video if we have it or it's forced by options.
566 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700567 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700568 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800569 } else if (is_offer) {
570 session_options->recv_video = false;
571 } else {
572 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700573 }
574
575 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700576 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800577 for (auto& kv : session_options->transport_options) {
578 kv.second.ice_restart = rtc_options.ice_restart;
579 }
deadbeefab9b2d12015-10-14 11:33:11 -0700580
581 return true;
582}
583
584bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
585 cricket::MediaSessionOptions* session_options) {
586 bool value = false;
587 size_t mandatory_constraints_satisfied = 0;
588
589 // kOfferToReceiveAudio defaults to true according to spec.
590 if (!FindConstraint(constraints,
591 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
592 &mandatory_constraints_satisfied) ||
593 value) {
594 session_options->recv_audio = true;
595 }
596
597 // kOfferToReceiveVideo defaults to false according to spec. But
598 // if it is an answer and video is offered, we should still accept video
599 // per default.
600 value = false;
601 if (!FindConstraint(constraints,
602 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
603 &mandatory_constraints_satisfied) ||
604 value) {
605 session_options->recv_video = true;
606 }
607
608 if (FindConstraint(constraints,
609 MediaConstraintsInterface::kVoiceActivityDetection, &value,
610 &mandatory_constraints_satisfied)) {
611 session_options->vad_enabled = value;
612 }
613
614 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
615 &mandatory_constraints_satisfied)) {
616 session_options->bundle_enabled = value;
617 } else {
618 // kUseRtpMux defaults to true according to spec.
619 session_options->bundle_enabled = true;
620 }
deadbeefab9b2d12015-10-14 11:33:11 -0700621
deadbeef0ed85b22016-02-23 17:24:52 -0800622 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700623 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
624 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700625 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800626 ice_restart = true;
627 }
628 for (auto& kv : session_options->transport_options) {
629 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700630 }
631
632 if (!constraints) {
633 return true;
634 }
635 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
636}
637
deadbeef7a5fa6c2016-12-24 00:47:59 -0800638RTCErrorType ParseIceServers(
639 const PeerConnectionInterface::IceServers& servers,
640 cricket::ServerAddresses* stun_servers,
641 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200642 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
643 if (!server.urls.empty()) {
644 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200645 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700646 LOG(LS_ERROR) << "Empty uri.";
deadbeef7a5fa6c2016-12-24 00:47:59 -0800647 return RTCErrorType::SYNTAX_ERROR;
Joachim Bauchd935f912015-05-29 22:14:21 +0200648 }
deadbeef7a5fa6c2016-12-24 00:47:59 -0800649 RTCErrorType err =
650 ParseIceServerUrl(server, url, stun_servers, turn_servers);
651 if (err != RTCErrorType::NONE) {
652 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200653 }
654 }
655 } else if (!server.uri.empty()) {
656 // Fallback to old .uri if new .urls isn't present.
deadbeef7a5fa6c2016-12-24 00:47:59 -0800657 RTCErrorType err =
658 ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
659 if (err != RTCErrorType::NONE) {
660 return err;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200661 }
662 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700663 LOG(LS_ERROR) << "Empty uri.";
deadbeef7a5fa6c2016-12-24 00:47:59 -0800664 return RTCErrorType::SYNTAX_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000665 }
666 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800667 // Candidates must have unique priorities, so that connectivity checks
668 // are performed in a well-defined order.
669 int priority = static_cast<int>(turn_servers->size() - 1);
670 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
671 // First in the list gets highest priority.
672 turn_server.priority = priority--;
673 }
deadbeef7a5fa6c2016-12-24 00:47:59 -0800674 return RTCErrorType::NONE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675}
676
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677PeerConnection::PeerConnection(PeerConnectionFactory* factory)
678 : factory_(factory),
679 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000680 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700683 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800684 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700685 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700686 local_streams_(StreamCollection::Create()),
687 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688
689PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100690 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700691 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700692 // Need to detach RTP senders/receivers from WebRtcSession,
693 // since it's about to be destroyed.
694 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700695 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700696 }
697 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700698 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700699 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700700 // Destroy stats_ because it depends on session_.
701 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800702 if (stats_collector_) {
703 stats_collector_->WaitForPendingRequest();
704 stats_collector_ = nullptr;
705 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700706 // Now destroy session_ before destroying other members,
707 // because its destruction fires signals (such as VoiceChannelDestroyed)
708 // which will trigger some final actions in PeerConnection...
709 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700710 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700711 network_thread()->Invoke<void>(RTC_FROM_HERE,
712 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000713}
714
715bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000716 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700717 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200718 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800719 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100720 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef7a5fa6c2016-12-24 00:47:59 -0800721 if (!allocator) {
722 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
723 << "This shouldn't happen if using PeerConnectionFactory.";
724 return false;
725 }
deadbeef653b8e02015-11-11 12:55:10 -0800726 if (!observer) {
deadbeef7a5fa6c2016-12-24 00:47:59 -0800727 // TODO(deadbeef): Why do we do this?
728 LOG(LS_ERROR) << "PeerConnection initialized without a "
729 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800730 return false;
731 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000732 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800733 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800734
deadbeef91dd5672016-05-18 16:55:30 -0700735 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700736 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700737 if (!network_thread()->Invoke<bool>(
738 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
739 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740 return false;
741 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742
skvlad11a9cbf2016-10-07 11:53:05 -0700743 media_controller_.reset(factory_->CreateMediaController(
744 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745
zhihuang29ff8442016-07-27 11:07:25 -0700746 session_.reset(new WebRtcSession(
747 media_controller_.get(), factory_->network_thread(),
748 factory_->worker_thread(), factory_->signaling_thread(),
749 port_allocator_.get(),
750 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700751 factory_->CreateTransportController(
752 port_allocator_.get(),
753 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700754
deadbeefab9b2d12015-10-14 11:33:11 -0700755 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700756 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000757
758 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200759 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800760 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700762 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764 // Register PeerConnection as receiver of local ice candidates.
765 // All the callbacks will be posted to the application from PeerConnection.
766 session_->RegisterIceObserver(this);
767 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700768 session_->SignalVoiceChannelCreated.connect(
769 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700770 session_->SignalVoiceChannelDestroyed.connect(
771 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700772 session_->SignalVideoChannelCreated.connect(
773 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700774 session_->SignalVideoChannelDestroyed.connect(
775 this, &PeerConnection::OnVideoChannelDestroyed);
776 session_->SignalDataChannelCreated.connect(
777 this, &PeerConnection::OnDataChannelCreated);
778 session_->SignalDataChannelDestroyed.connect(
779 this, &PeerConnection::OnDataChannelDestroyed);
780 session_->SignalDataChannelOpenMessage.connect(
781 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800782
783 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000784 return true;
785}
786
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000787rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000788PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700789 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790}
791
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000792rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700794 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795}
796
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000797bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100798 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799 if (IsClosed()) {
800 return false;
801 }
deadbeefab9b2d12015-10-14 11:33:11 -0700802 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000803 return false;
804 }
deadbeefab9b2d12015-10-14 11:33:11 -0700805
806 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800807 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
808 observer->SignalAudioTrackAdded.connect(this,
809 &PeerConnection::OnAudioTrackAdded);
810 observer->SignalAudioTrackRemoved.connect(
811 this, &PeerConnection::OnAudioTrackRemoved);
812 observer->SignalVideoTrackAdded.connect(this,
813 &PeerConnection::OnVideoTrackAdded);
814 observer->SignalVideoTrackRemoved.connect(
815 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700816 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700817
deadbeefab9b2d12015-10-14 11:33:11 -0700818 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800819 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700820 }
821 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800822 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700823 }
824
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000825 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 observer_->OnRenegotiationNeeded();
827 return true;
828}
829
830void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100831 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700832 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800833 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700834 }
835 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800836 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700837 }
838
839 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800840 stream_observers_.erase(
841 std::remove_if(
842 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700843 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800844 return observer->stream()->label().compare(local_stream->label()) ==
845 0;
846 }),
847 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700848
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849 if (IsClosed()) {
850 return;
851 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852 observer_->OnRenegotiationNeeded();
853}
854
deadbeefe1f9d832016-01-14 15:35:42 -0800855rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
856 MediaStreamTrackInterface* track,
857 std::vector<MediaStreamInterface*> streams) {
858 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
859 if (IsClosed()) {
860 return nullptr;
861 }
862 if (streams.size() >= 2) {
863 LOG(LS_ERROR)
864 << "Adding a track with two streams is not currently supported.";
865 return nullptr;
866 }
867 // TODO(deadbeef): Support adding a track to two different senders.
868 if (FindSenderForTrack(track) != senders_.end()) {
869 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
870 return nullptr;
871 }
872
873 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700874 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800875 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700876 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800877 signaling_thread(),
878 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700879 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800880 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700881 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800882 }
883 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700884 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800885 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700886 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800887 }
888 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700889 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800890 signaling_thread(),
891 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700892 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800893 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700894 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800895 }
896 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700897 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800898 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700899 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800900 }
901 } else {
902 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
903 return rtc::scoped_refptr<RtpSenderInterface>();
904 }
905
906 senders_.push_back(new_sender);
907 observer_->OnRenegotiationNeeded();
908 return new_sender;
909}
910
911bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
912 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
913 if (IsClosed()) {
914 return false;
915 }
916
917 auto it = std::find(senders_.begin(), senders_.end(), sender);
918 if (it == senders_.end()) {
919 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
920 return false;
921 }
deadbeefa601f5c2016-06-06 14:27:39 -0700922 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800923 senders_.erase(it);
924
925 observer_->OnRenegotiationNeeded();
926 return true;
927}
928
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000929rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100931 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700932 if (IsClosed()) {
933 return nullptr;
934 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 if (!track) {
936 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
937 return NULL;
938 }
deadbeefab9b2d12015-10-14 11:33:11 -0700939 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
941 return NULL;
942 }
943
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000944 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 DtmfSender::Create(track, signaling_thread(), session_.get()));
946 if (!sender.get()) {
947 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
948 return NULL;
949 }
950 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
951}
952
deadbeeffac06552015-11-25 11:26:01 -0800953rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800954 const std::string& kind,
955 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100956 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700957 if (IsClosed()) {
958 return nullptr;
959 }
deadbeefa601f5c2016-06-06 14:27:39 -0700960 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800961 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700962 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700963 signaling_thread(),
964 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800965 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700966 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700967 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800968 } else {
969 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800970 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800971 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800972 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700973 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800974 }
deadbeeffac06552015-11-25 11:26:01 -0800975 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800976 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800977}
978
deadbeef70ab1a12015-09-28 16:53:55 -0700979std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
980 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700981 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
982 for (const auto& sender : senders_) {
983 ret.push_back(sender.get());
984 }
985 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700986}
987
988std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
989PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700990 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
991 for (const auto& receiver : receivers_) {
992 ret.push_back(receiver.get());
993 }
994 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700995}
996
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000998 MediaStreamTrackInterface* track,
999 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001000 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001001 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 if (!VERIFY(observer != NULL)) {
1003 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1004 return false;
1005 }
1006
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001007 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001008 // The StatsCollector is used to tell if a track is valid because it may
1009 // remember tracks that the PeerConnection previously removed.
1010 if (track && !stats_->IsValidTrack(track->id())) {
1011 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1012 << track->id();
1013 return false;
1014 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001015 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001016 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017 return true;
1018}
1019
hbos74e1a4f2016-09-15 23:33:01 -07001020void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1021 RTC_DCHECK(stats_collector_);
1022 stats_collector_->GetStatsReport(callback);
1023}
1024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1026 return signaling_state_;
1027}
1028
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001029PeerConnectionInterface::IceConnectionState
1030PeerConnection::ice_connection_state() {
1031 return ice_connection_state_;
1032}
1033
1034PeerConnectionInterface::IceGatheringState
1035PeerConnection::ice_gathering_state() {
1036 return ice_gathering_state_;
1037}
1038
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001039rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001040PeerConnection::CreateDataChannel(
1041 const std::string& label,
1042 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001043 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001044#ifdef HAVE_QUIC
1045 if (session_->data_channel_type() == cricket::DCT_QUIC) {
1046 // TODO(zhihuang): Handle case when config is NULL.
1047 if (!config) {
1048 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
1049 return nullptr;
1050 }
1051 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
1052 if (!config->reliable || config->ordered) {
1053 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
1054 "ordered delivery.";
1055 return nullptr;
1056 }
1057 return session_->quic_data_transport()->CreateDataChannel(label, config);
1058 }
1059#endif // HAVE_QUIC
1060
deadbeefab9b2d12015-10-14 11:33:11 -07001061 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001062
kwibergd1fe2812016-04-27 06:47:29 -07001063 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001064 if (config) {
1065 internal_config.reset(new InternalDataChannelInit(*config));
1066 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001067 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001068 InternalCreateDataChannel(label, internal_config.get()));
1069 if (!channel.get()) {
1070 return nullptr;
1071 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001073 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1074 // the first SCTP DataChannel.
1075 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
1076 observer_->OnRenegotiationNeeded();
1077 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001078
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001079 return DataChannelProxy::Create(signaling_thread(), channel.get());
1080}
1081
1082void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1083 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001084 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001085 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1087 return;
1088 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001089 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001090
1091 bool value;
1092 size_t mandatory_constraints = 0;
1093
1094 if (FindConstraint(constraints,
1095 MediaConstraintsInterface::kOfferToReceiveAudio,
1096 &value,
1097 &mandatory_constraints)) {
1098 options.offer_to_receive_audio =
1099 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1100 }
1101
1102 if (FindConstraint(constraints,
1103 MediaConstraintsInterface::kOfferToReceiveVideo,
1104 &value,
1105 &mandatory_constraints)) {
1106 options.offer_to_receive_video =
1107 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1108 }
1109
1110 if (FindConstraint(constraints,
1111 MediaConstraintsInterface::kVoiceActivityDetection,
1112 &value,
1113 &mandatory_constraints)) {
1114 options.voice_activity_detection = value;
1115 }
1116
1117 if (FindConstraint(constraints,
1118 MediaConstraintsInterface::kIceRestart,
1119 &value,
1120 &mandatory_constraints)) {
1121 options.ice_restart = value;
1122 }
1123
1124 if (FindConstraint(constraints,
1125 MediaConstraintsInterface::kUseRtpMux,
1126 &value,
1127 &mandatory_constraints)) {
1128 options.use_rtp_mux = value;
1129 }
1130
1131 CreateOffer(observer, options);
1132}
1133
1134void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1135 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001136 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001137 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001138 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1139 return;
1140 }
deadbeefab9b2d12015-10-14 11:33:11 -07001141
1142 cricket::MediaSessionOptions session_options;
1143 if (!GetOptionsForOffer(options, &session_options)) {
1144 std::string error = "CreateOffer called with invalid options.";
1145 LOG(LS_ERROR) << error;
1146 PostCreateSessionDescriptionFailure(observer, error);
1147 return;
1148 }
1149
1150 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001151}
1152
1153void PeerConnection::CreateAnswer(
1154 CreateSessionDescriptionObserver* observer,
1155 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001156 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001157 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1159 return;
1160 }
deadbeefab9b2d12015-10-14 11:33:11 -07001161
1162 cricket::MediaSessionOptions session_options;
1163 if (!GetOptionsForAnswer(constraints, &session_options)) {
1164 std::string error = "CreateAnswer called with invalid constraints.";
1165 LOG(LS_ERROR) << error;
1166 PostCreateSessionDescriptionFailure(observer, error);
1167 return;
1168 }
1169
htaa2a49d92016-03-04 02:51:39 -08001170 session_->CreateAnswer(observer, session_options);
1171}
1172
1173void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1174 const RTCOfferAnswerOptions& options) {
1175 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1176 if (!VERIFY(observer != nullptr)) {
1177 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1178 return;
1179 }
1180
1181 cricket::MediaSessionOptions session_options;
1182 if (!GetOptionsForAnswer(options, &session_options)) {
1183 std::string error = "CreateAnswer called with invalid options.";
1184 LOG(LS_ERROR) << error;
1185 PostCreateSessionDescriptionFailure(observer, error);
1186 return;
1187 }
1188
1189 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190}
1191
1192void PeerConnection::SetLocalDescription(
1193 SetSessionDescriptionObserver* observer,
1194 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001195 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001196 if (IsClosed()) {
1197 return;
1198 }
deadbeefab9b2d12015-10-14 11:33:11 -07001199 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1201 return;
1202 }
1203 if (!desc) {
1204 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1205 return;
1206 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001207 // Update stats here so that we have the most recent stats for tracks and
1208 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001209 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001210 std::string error;
1211 if (!session_->SetLocalDescription(desc, &error)) {
1212 PostSetSessionDescriptionFailure(observer, error);
1213 return;
1214 }
deadbeefab9b2d12015-10-14 11:33:11 -07001215
1216 // If setting the description decided our SSL role, allocate any necessary
1217 // SCTP sids.
1218 rtc::SSLRole role;
1219 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001220 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001221 AllocateSctpSids(role);
1222 }
1223
1224 // Update state and SSRC of local MediaStreams and DataChannels based on the
1225 // local session description.
1226 const cricket::ContentInfo* audio_content =
1227 GetFirstAudioContent(desc->description());
1228 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001229 if (audio_content->rejected) {
1230 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1231 } else {
1232 const cricket::AudioContentDescription* audio_desc =
1233 static_cast<const cricket::AudioContentDescription*>(
1234 audio_content->description);
1235 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1236 }
deadbeefab9b2d12015-10-14 11:33:11 -07001237 }
1238
1239 const cricket::ContentInfo* video_content =
1240 GetFirstVideoContent(desc->description());
1241 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001242 if (video_content->rejected) {
1243 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1244 } else {
1245 const cricket::VideoContentDescription* video_desc =
1246 static_cast<const cricket::VideoContentDescription*>(
1247 video_content->description);
1248 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1249 }
deadbeefab9b2d12015-10-14 11:33:11 -07001250 }
1251
1252 const cricket::ContentInfo* data_content =
1253 GetFirstDataContent(desc->description());
1254 if (data_content) {
1255 const cricket::DataContentDescription* data_desc =
1256 static_cast<const cricket::DataContentDescription*>(
1257 data_content->description);
1258 if (rtc::starts_with(data_desc->protocol().data(),
1259 cricket::kMediaProtocolRtpPrefix)) {
1260 UpdateLocalRtpDataChannels(data_desc->streams());
1261 }
1262 }
1263
1264 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001265 signaling_thread()->Post(RTC_FROM_HERE, this,
1266 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001267
deadbeefcbecd352015-09-23 11:50:27 -07001268 // MaybeStartGathering needs to be called after posting
1269 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1270 // before signaling that SetLocalDescription completed.
1271 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272}
1273
1274void PeerConnection::SetRemoteDescription(
1275 SetSessionDescriptionObserver* observer,
1276 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001277 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001278 if (IsClosed()) {
1279 return;
1280 }
deadbeefab9b2d12015-10-14 11:33:11 -07001281 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1283 return;
1284 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 if (!desc) {
1286 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1287 return;
1288 }
1289 // Update stats here so that we have the most recent stats for tracks and
1290 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001291 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292 std::string error;
1293 if (!session_->SetRemoteDescription(desc, &error)) {
1294 PostSetSessionDescriptionFailure(observer, error);
1295 return;
1296 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297
deadbeefab9b2d12015-10-14 11:33:11 -07001298 // If setting the description decided our SSL role, allocate any necessary
1299 // SCTP sids.
1300 rtc::SSLRole role;
1301 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001302 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001303 AllocateSctpSids(role);
1304 }
1305
1306 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001307 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1308 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1309 const cricket::AudioContentDescription* audio_desc =
1310 GetFirstAudioContentDescription(remote_desc);
1311 const cricket::VideoContentDescription* video_desc =
1312 GetFirstVideoContentDescription(remote_desc);
1313 const cricket::DataContentDescription* data_desc =
1314 GetFirstDataContentDescription(remote_desc);
1315
1316 // Check if the descriptions include streams, just in case the peer supports
1317 // MSID, but doesn't indicate so with "a=msid-semantic".
1318 if (remote_desc->msid_supported() ||
1319 (audio_desc && !audio_desc->streams().empty()) ||
1320 (video_desc && !video_desc->streams().empty())) {
1321 remote_peer_supports_msid_ = true;
1322 }
deadbeefab9b2d12015-10-14 11:33:11 -07001323
1324 // We wait to signal new streams until we finish processing the description,
1325 // since only at that point will new streams have all their tracks.
1326 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1327
1328 // Find all audio rtp streams and create corresponding remote AudioTracks
1329 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001330 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001331 if (audio_content->rejected) {
1332 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1333 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001334 bool default_audio_track_needed =
1335 !remote_peer_supports_msid_ &&
1336 MediaContentDirectionHasSend(audio_desc->direction());
1337 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1338 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001339 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001340 }
deadbeefab9b2d12015-10-14 11:33:11 -07001341 }
1342
1343 // Find all video rtp streams and create corresponding remote VideoTracks
1344 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001345 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001346 if (video_content->rejected) {
1347 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1348 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001349 bool default_video_track_needed =
1350 !remote_peer_supports_msid_ &&
1351 MediaContentDirectionHasSend(video_desc->direction());
1352 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1353 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001354 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001355 }
deadbeefab9b2d12015-10-14 11:33:11 -07001356 }
1357
1358 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001359 if (data_desc) {
1360 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001361 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001362 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001363 }
1364 }
1365
1366 // Iterate new_streams and notify the observer about new MediaStreams.
1367 for (size_t i = 0; i < new_streams->count(); ++i) {
1368 MediaStreamInterface* new_stream = new_streams->at(i);
1369 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001370 // Call both the raw pointer and scoped_refptr versions of the method
1371 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001372 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001373 observer_->OnAddStream(
1374 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001375 }
1376
deadbeefbda7e0b2015-12-08 17:13:40 -08001377 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001378
1379 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001380 signaling_thread()->Post(RTC_FROM_HERE, this,
1381 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001382}
1383
deadbeef46c73892016-11-16 19:42:04 -08001384PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1385 return configuration_;
1386}
1387
deadbeef7a5fa6c2016-12-24 00:47:59 -08001388bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1389 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001390 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001391
1392 if (session_->local_description() &&
1393 configuration.ice_candidate_pool_size !=
1394 configuration_.ice_candidate_pool_size) {
1395 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1396 "SetLocalDescription.";
deadbeef7a5fa6c2016-12-24 00:47:59 -08001397 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001398 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001399
deadbeef7a5fa6c2016-12-24 00:47:59 -08001400 // The simplest (and most future-compatible) way to tell if the config was
1401 // modified in an invalid way is to copy each property we do support
1402 // modifying, then use operator==. There are far more properties we don't
1403 // support modifying than those we do, and more could be added.
1404 RTCConfiguration modified_config = configuration_;
1405 modified_config.servers = configuration.servers;
1406 modified_config.type = configuration.type;
1407 modified_config.ice_candidate_pool_size =
1408 configuration.ice_candidate_pool_size;
1409 modified_config.prune_turn_ports = configuration.prune_turn_ports;
1410 if (configuration != modified_config) {
1411 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1412 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1413 }
1414
1415 // Note that this isn't possible through chromium, since it's an unsigned
1416 // short in WebIDL.
1417 if (configuration.ice_candidate_pool_size < 0 ||
1418 configuration.ice_candidate_pool_size > UINT16_MAX) {
1419 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1420 }
1421
1422 // Parse ICE servers before hopping to network thread.
1423 cricket::ServerAddresses stun_servers;
1424 std::vector<cricket::RelayServerConfig> turn_servers;
1425 RTCErrorType parse_error =
1426 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1427 if (parse_error != RTCErrorType::NONE) {
1428 return SafeSetError(parse_error, error);
1429 }
1430
1431 // In theory this shouldn't fail.
1432 if (!network_thread()->Invoke<bool>(
1433 RTC_FROM_HERE,
1434 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1435 stun_servers, turn_servers, modified_config.type,
1436 modified_config.ice_candidate_pool_size,
1437 modified_config.prune_turn_ports))) {
1438 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1439 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1440 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001441
deadbeefd1a38b52016-12-10 13:15:33 -08001442 // As described in JSEP, calling setConfiguration with new ICE servers or
1443 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1444 // triggers an ICE restart which will pick up the changes.
deadbeef7a5fa6c2016-12-24 00:47:59 -08001445 if (modified_config.servers != configuration_.servers ||
1446 modified_config.type != configuration_.type ||
1447 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001448 session_->SetNeedsIceRestartFlag();
1449 }
deadbeef7a5fa6c2016-12-24 00:47:59 -08001450 configuration_ = modified_config;
1451 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001452}
1453
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454bool PeerConnection::AddIceCandidate(
1455 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001456 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001457 if (IsClosed()) {
1458 return false;
1459 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 return session_->ProcessIceMessage(ice_candidate);
1461}
1462
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001463bool PeerConnection::RemoveIceCandidates(
1464 const std::vector<cricket::Candidate>& candidates) {
1465 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1466 return session_->RemoveRemoteIceCandidates(candidates);
1467}
1468
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001469void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001470 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001471 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001472
1473 if (session_) {
1474 session_->set_metrics_observer(uma_observer_);
1475 }
1476
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001477 // Send information about IPv4/IPv6 status.
deadbeef7a5fa6c2016-12-24 00:47:59 -08001478 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001479 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001480 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001481 uma_observer_->IncrementEnumCounter(
1482 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1483 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001484 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001485 uma_observer_->IncrementEnumCounter(
1486 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1487 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001488 }
1489 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001490}
1491
ivoc14d5dbe2016-07-04 07:06:55 -07001492bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1493 int64_t max_size_bytes) {
1494 return factory_->worker_thread()->Invoke<bool>(
1495 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1496 max_size_bytes));
1497}
1498
1499void PeerConnection::StopRtcEventLog() {
1500 factory_->worker_thread()->Invoke<void>(
1501 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1502}
1503
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001504const SessionDescriptionInterface* PeerConnection::local_description() const {
1505 return session_->local_description();
1506}
1507
1508const SessionDescriptionInterface* PeerConnection::remote_description() const {
1509 return session_->remote_description();
1510}
1511
deadbeeffe4a8a42016-12-20 17:56:17 -08001512const SessionDescriptionInterface* PeerConnection::current_local_description()
1513 const {
1514 return session_->current_local_description();
1515}
1516
1517const SessionDescriptionInterface* PeerConnection::current_remote_description()
1518 const {
1519 return session_->current_remote_description();
1520}
1521
1522const SessionDescriptionInterface* PeerConnection::pending_local_description()
1523 const {
1524 return session_->pending_local_description();
1525}
1526
1527const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1528 const {
1529 return session_->pending_remote_description();
1530}
1531
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001532void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001533 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001534 // Update stats here so that we have the most recent stats for tracks and
1535 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001536 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537
deadbeefd59daf82015-10-14 15:02:44 -07001538 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001539}
1540
deadbeefd59daf82015-10-14 15:02:44 -07001541void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1542 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001543 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001544 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001546 break;
deadbeefd59daf82015-10-14 15:02:44 -07001547 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001548 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1549 break;
deadbeefd59daf82015-10-14 15:02:44 -07001550 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1552 break;
deadbeefd59daf82015-10-14 15:02:44 -07001553 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1555 break;
deadbeefd59daf82015-10-14 15:02:44 -07001556 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001557 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1558 break;
deadbeefd59daf82015-10-14 15:02:44 -07001559 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560 ChangeSignalingState(PeerConnectionInterface::kStable);
1561 break;
deadbeefd59daf82015-10-14 15:02:44 -07001562 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563 ChangeSignalingState(PeerConnectionInterface::kClosed);
1564 break;
1565 default:
1566 break;
1567 }
1568}
1569
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001570void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001572 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1573 SetSessionDescriptionMsg* param =
1574 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1575 param->observer->OnSuccess();
1576 delete param;
1577 break;
1578 }
1579 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1580 SetSessionDescriptionMsg* param =
1581 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1582 param->observer->OnFailure(param->error);
1583 delete param;
1584 break;
1585 }
deadbeefab9b2d12015-10-14 11:33:11 -07001586 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1587 CreateSessionDescriptionMsg* param =
1588 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1589 param->observer->OnFailure(param->error);
1590 delete param;
1591 break;
1592 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001593 case MSG_GETSTATS: {
1594 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nisseb36ee8d2016-12-20 03:30:00 -08001595 std::unique_ptr<StatsReports> reports(new StatsReports);
1596 stats_->GetStats(param->track, reports.get());
1597 param->observer->OnCompleteReports(std::move(reports));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001598 delete param;
1599 break;
1600 }
deadbeefbd292462015-12-14 18:15:29 -08001601 case MSG_FREE_DATACHANNELS: {
1602 sctp_data_channels_to_free_.clear();
1603 break;
1604 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001605 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001606 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607 break;
1608 }
1609}
1610
deadbeefab9b2d12015-10-14 11:33:11 -07001611void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001612 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001613 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001614 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1615 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001616 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001617 session_->voice_channel()));
1618
1619 receivers_.push_back(receiver);
1620 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1621 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1622 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001623}
1624
deadbeefab9b2d12015-10-14 11:33:11 -07001625void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001626 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001627 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001628 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1629 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001630 signaling_thread(),
1631 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001632 ssrc, session_->video_channel()));
1633 receivers_.push_back(receiver);
1634 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1635 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1636 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001637}
1638
deadbeef70ab1a12015-09-28 16:53:55 -07001639// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1640// description.
perkjd61bf802016-03-24 03:16:19 -07001641void PeerConnection::DestroyReceiver(const std::string& track_id) {
1642 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001643 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001644 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001645 << " doesn't exist.";
1646 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001647 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001648 receivers_.erase(it);
1649 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001650}
1651
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652void PeerConnection::OnIceConnectionChange(
1653 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001654 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001655 // After transitioning to "closed", ignore any additional states from
1656 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001657 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001658 return;
1659 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001660 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001661 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001662}
1663
1664void PeerConnection::OnIceGatheringChange(
1665 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001666 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001667 if (IsClosed()) {
1668 return;
1669 }
1670 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001671 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672}
1673
1674void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001675 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001676 if (IsClosed()) {
1677 return;
1678 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001679 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680}
1681
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001682void PeerConnection::OnIceCandidatesRemoved(
1683 const std::vector<cricket::Candidate>& candidates) {
1684 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001685 if (IsClosed()) {
1686 return;
1687 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001688 observer_->OnIceCandidatesRemoved(candidates);
1689}
1690
Peter Thatcher54360512015-07-08 11:08:35 -07001691void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001692 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001693 if (IsClosed()) {
1694 return;
1695 }
Peter Thatcher54360512015-07-08 11:08:35 -07001696 observer_->OnIceConnectionReceivingChange(receiving);
1697}
1698
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699void PeerConnection::ChangeSignalingState(
1700 PeerConnectionInterface::SignalingState signaling_state) {
1701 signaling_state_ = signaling_state;
1702 if (signaling_state == kClosed) {
1703 ice_connection_state_ = kIceConnectionClosed;
1704 observer_->OnIceConnectionChange(ice_connection_state_);
1705 if (ice_gathering_state_ != kIceGatheringComplete) {
1706 ice_gathering_state_ = kIceGatheringComplete;
1707 observer_->OnIceGatheringChange(ice_gathering_state_);
1708 }
1709 }
1710 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711}
1712
deadbeefeb459812015-12-15 19:24:43 -08001713void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1714 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001715 if (IsClosed()) {
1716 return;
1717 }
deadbeefeb459812015-12-15 19:24:43 -08001718 auto sender = FindSenderForTrack(track);
1719 if (sender != senders_.end()) {
1720 // We already have a sender for this track, so just change the stream_id
1721 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001722 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001723 return;
1724 }
1725
1726 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001727 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1728 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001729 signaling_thread(),
1730 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1731 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001732 senders_.push_back(new_sender);
1733 // If the sender has already been configured in SDP, we call SetSsrc,
1734 // which will connect the sender to the underlying transport. This can
1735 // occur if a local session description that contains the ID of the sender
1736 // is set before AddStream is called. It can also occur if the local
1737 // session description is not changed and RemoveStream is called, and
1738 // later AddStream is called again with the same stream.
1739 const TrackInfo* track_info =
1740 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1741 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001742 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001743 }
1744}
1745
1746// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1747// indefinitely, when we have unified plan SDP.
1748void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1749 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001750 if (IsClosed()) {
1751 return;
1752 }
deadbeefeb459812015-12-15 19:24:43 -08001753 auto sender = FindSenderForTrack(track);
1754 if (sender == senders_.end()) {
1755 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1756 << " doesn't exist.";
1757 return;
1758 }
deadbeefa601f5c2016-06-06 14:27:39 -07001759 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001760 senders_.erase(sender);
1761}
1762
1763void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1764 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001765 if (IsClosed()) {
1766 return;
1767 }
deadbeefeb459812015-12-15 19:24:43 -08001768 auto sender = FindSenderForTrack(track);
1769 if (sender != senders_.end()) {
1770 // We already have a sender for this track, so just change the stream_id
1771 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001772 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001773 return;
1774 }
1775
1776 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001777 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1778 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001779 signaling_thread(), new VideoRtpSender(track, stream->label(),
1780 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001781 senders_.push_back(new_sender);
1782 const TrackInfo* track_info =
1783 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1784 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001785 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001786 }
1787}
1788
1789void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1790 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001791 if (IsClosed()) {
1792 return;
1793 }
deadbeefeb459812015-12-15 19:24:43 -08001794 auto sender = FindSenderForTrack(track);
1795 if (sender == senders_.end()) {
1796 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1797 << " doesn't exist.";
1798 return;
1799 }
deadbeefa601f5c2016-06-06 14:27:39 -07001800 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001801 senders_.erase(sender);
1802}
1803
deadbeefab9b2d12015-10-14 11:33:11 -07001804void PeerConnection::PostSetSessionDescriptionFailure(
1805 SetSessionDescriptionObserver* observer,
1806 const std::string& error) {
1807 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1808 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001809 signaling_thread()->Post(RTC_FROM_HERE, this,
1810 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001811}
1812
1813void PeerConnection::PostCreateSessionDescriptionFailure(
1814 CreateSessionDescriptionObserver* observer,
1815 const std::string& error) {
1816 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1817 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001818 signaling_thread()->Post(RTC_FROM_HERE, this,
1819 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001820}
1821
1822bool PeerConnection::GetOptionsForOffer(
1823 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1824 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001825 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1826 // ContentInfos.
1827 if (session_->local_description()) {
1828 for (const cricket::ContentInfo& content :
1829 session_->local_description()->description()->contents()) {
1830 session_options->transport_options[content.name] =
1831 cricket::TransportOptions();
1832 }
1833 }
deadbeef46c73892016-11-16 19:42:04 -08001834 session_options->enable_ice_renomination =
1835 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001836
htaaac2dea2016-03-10 13:35:55 -08001837 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001838 return false;
1839 }
1840
deadbeeffac06552015-11-25 11:26:01 -08001841 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001842 // Offer to receive audio/video if the constraint is not set and there are
1843 // send streams, or we're currently receiving.
1844 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1845 session_options->recv_audio =
1846 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1847 !remote_audio_tracks_.empty();
1848 }
1849 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1850 session_options->recv_video =
1851 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1852 !remote_video_tracks_.empty();
1853 }
deadbeefc80741f2015-10-22 13:14:45 -07001854
zhihuang9763d562016-08-05 11:14:50 -07001855 // Intentionally unset the data channel type for RTP data channel with the
1856 // second condition. Otherwise the RTP data channels would be successfully
1857 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1858 // when building with chromium. We want to leave RTP data channels broken, so
1859 // people won't try to use them.
1860 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1861 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001862 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001863
zhihuangaf388472016-11-02 16:49:48 -07001864 session_options->bundle_enabled =
1865 session_options->bundle_enabled &&
1866 (session_options->has_audio() || session_options->has_video() ||
1867 session_options->has_data());
1868
zhihuang8f65cdf2016-05-06 18:40:30 -07001869 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001870 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001871 return true;
1872}
1873
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001874void PeerConnection::InitializeOptionsForAnswer(
1875 cricket::MediaSessionOptions* session_options) {
1876 session_options->recv_audio = false;
1877 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001878 session_options->enable_ice_renomination =
1879 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001880}
1881
htaa2a49d92016-03-04 02:51:39 -08001882void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001883 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001884 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1885 // ContentInfos.
1886 if (session_->remote_description()) {
1887 // Initialize the transport_options map.
1888 for (const cricket::ContentInfo& content :
1889 session_->remote_description()->description()->contents()) {
1890 session_options->transport_options[content.name] =
1891 cricket::TransportOptions();
1892 }
1893 }
deadbeeffac06552015-11-25 11:26:01 -08001894 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001895 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1896 // are not signaled in the SDP so does not go through that path and must be
1897 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001898 // Intentionally unset the data channel type for RTP data channel. Otherwise
1899 // the RTP data channels would be successfully negotiated by default and the
1900 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1901 // We want to leave RTP data channels broken, so people won't try to use them.
1902 if (session_->data_channel_type() != cricket::DCT_RTP) {
1903 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001904 }
zhihuangaf388472016-11-02 16:49:48 -07001905 session_options->bundle_enabled =
1906 session_options->bundle_enabled &&
1907 (session_options->has_audio() || session_options->has_video() ||
1908 session_options->has_data());
1909
jbauchcb560652016-08-04 05:20:32 -07001910 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001911}
1912
1913bool PeerConnection::GetOptionsForAnswer(
1914 const MediaConstraintsInterface* constraints,
1915 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001916 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001917 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1918 return false;
1919 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001920 session_options->rtcp_cname = rtcp_cname_;
1921
htaa2a49d92016-03-04 02:51:39 -08001922 FinishOptionsForAnswer(session_options);
1923 return true;
1924}
1925
1926bool PeerConnection::GetOptionsForAnswer(
1927 const RTCOfferAnswerOptions& options,
1928 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001929 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001930 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001931 return false;
1932 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001933 session_options->rtcp_cname = rtcp_cname_;
1934
htaa2a49d92016-03-04 02:51:39 -08001935 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001936 return true;
1937}
1938
deadbeeffaac4972015-11-12 15:33:07 -08001939void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1940 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001941 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1942 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001943}
1944
deadbeefab9b2d12015-10-14 11:33:11 -07001945void PeerConnection::UpdateRemoteStreamsList(
1946 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001947 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001948 cricket::MediaType media_type,
1949 StreamCollection* new_streams) {
1950 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1951
1952 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001953 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001954 auto track_it = current_tracks->begin();
1955 while (track_it != current_tracks->end()) {
1956 const TrackInfo& info = *track_it;
1957 const cricket::StreamParams* params =
1958 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001959 bool track_exists = params && params->id == info.track_id;
1960 // If this is a default track, and we still need it, don't remove it.
1961 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1962 track_exists) {
1963 ++track_it;
1964 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001965 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1966 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001967 }
1968 }
1969
1970 // Find new and active tracks.
1971 for (const cricket::StreamParams& params : streams) {
1972 // The sync_label is the MediaStream label and the |stream.id| is the
1973 // track id.
1974 const std::string& stream_label = params.sync_label;
1975 const std::string& track_id = params.id;
1976 uint32_t ssrc = params.first_ssrc();
1977
1978 rtc::scoped_refptr<MediaStreamInterface> stream =
1979 remote_streams_->find(stream_label);
1980 if (!stream) {
1981 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001982 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1983 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001984 remote_streams_->AddStream(stream);
1985 new_streams->AddStream(stream);
1986 }
1987
1988 const TrackInfo* track_info =
1989 FindTrackInfo(*current_tracks, stream_label, track_id);
1990 if (!track_info) {
1991 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1992 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1993 }
1994 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001995
1996 // Add default track if necessary.
1997 if (default_track_needed) {
1998 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1999 remote_streams_->find(kDefaultStreamLabel);
2000 if (!default_stream) {
2001 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002002 default_stream = MediaStreamProxy::Create(
2003 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002004 remote_streams_->AddStream(default_stream);
2005 new_streams->AddStream(default_stream);
2006 }
2007 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2008 ? kDefaultAudioTrackLabel
2009 : kDefaultVideoTrackLabel;
2010 const TrackInfo* default_track_info =
2011 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2012 if (!default_track_info) {
2013 current_tracks->push_back(
2014 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2015 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2016 }
2017 }
deadbeefab9b2d12015-10-14 11:33:11 -07002018}
2019
2020void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2021 const std::string& track_id,
2022 uint32_t ssrc,
2023 cricket::MediaType media_type) {
2024 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2025
2026 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002027 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002028 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002029 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002030 } else {
2031 RTC_DCHECK(false && "Invalid media type");
2032 }
2033}
2034
2035void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2036 const std::string& track_id,
2037 cricket::MediaType media_type) {
2038 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2039
2040 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002041 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2042 // will be notified which will end the AudioRtpReceiver::track().
2043 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002044 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2045 stream->FindAudioTrack(track_id);
2046 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002047 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002048 }
2049 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002050 // Stopping or destroying a VideoRtpReceiver will end the
2051 // VideoRtpReceiver::track().
2052 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002053 rtc::scoped_refptr<VideoTrackInterface> video_track =
2054 stream->FindVideoTrack(track_id);
2055 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002056 // There's no guarantee the track is still available, e.g. the track may
2057 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002058 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002059 }
2060 } else {
2061 ASSERT(false && "Invalid media type");
2062 }
2063}
2064
2065void PeerConnection::UpdateEndedRemoteMediaStreams() {
2066 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2067 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2068 MediaStreamInterface* stream = remote_streams_->at(i);
2069 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2070 streams_to_remove.push_back(stream);
2071 }
2072 }
2073
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002074 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002075 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002076 // Call both the raw pointer and scoped_refptr versions of the method
2077 // for compatibility.
2078 observer_->OnRemoveStream(stream.get());
2079 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002080 }
2081}
2082
deadbeefab9b2d12015-10-14 11:33:11 -07002083void PeerConnection::UpdateLocalTracks(
2084 const std::vector<cricket::StreamParams>& streams,
2085 cricket::MediaType media_type) {
2086 TrackInfos* current_tracks = GetLocalTracks(media_type);
2087
2088 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2089 // don't match the new StreamParam.
2090 TrackInfos::iterator track_it = current_tracks->begin();
2091 while (track_it != current_tracks->end()) {
2092 const TrackInfo& info = *track_it;
2093 const cricket::StreamParams* params =
2094 cricket::GetStreamBySsrc(streams, info.ssrc);
2095 if (!params || params->id != info.track_id ||
2096 params->sync_label != info.stream_label) {
2097 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2098 media_type);
2099 track_it = current_tracks->erase(track_it);
2100 } else {
2101 ++track_it;
2102 }
2103 }
2104
2105 // Find new and active tracks.
2106 for (const cricket::StreamParams& params : streams) {
2107 // The sync_label is the MediaStream label and the |stream.id| is the
2108 // track id.
2109 const std::string& stream_label = params.sync_label;
2110 const std::string& track_id = params.id;
2111 uint32_t ssrc = params.first_ssrc();
2112 const TrackInfo* track_info =
2113 FindTrackInfo(*current_tracks, stream_label, track_id);
2114 if (!track_info) {
2115 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2116 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2117 }
2118 }
2119}
2120
2121void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2122 const std::string& track_id,
2123 uint32_t ssrc,
2124 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002125 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002126 if (!sender) {
2127 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2128 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002129 return;
2130 }
2131
deadbeeffac06552015-11-25 11:26:01 -08002132 if (sender->media_type() != media_type) {
2133 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2134 << " description with an unexpected media type.";
2135 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002136 }
deadbeeffac06552015-11-25 11:26:01 -08002137
2138 sender->set_stream_id(stream_label);
2139 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002140}
2141
2142void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2143 const std::string& track_id,
2144 uint32_t ssrc,
2145 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002146 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002147 if (!sender) {
2148 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002149 // SessionDescriptions has been renegotiated.
2150 return;
2151 }
deadbeeffac06552015-11-25 11:26:01 -08002152
2153 // A sender has been removed from the SessionDescription but it's still
2154 // associated with the PeerConnection. This only occurs if the SDP doesn't
2155 // match with the calls to CreateSender, AddStream and RemoveStream.
2156 if (sender->media_type() != media_type) {
2157 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2158 << " description with an unexpected media type.";
2159 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002160 }
deadbeeffac06552015-11-25 11:26:01 -08002161
2162 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002163}
2164
2165void PeerConnection::UpdateLocalRtpDataChannels(
2166 const cricket::StreamParamsVec& streams) {
2167 std::vector<std::string> existing_channels;
2168
2169 // Find new and active data channels.
2170 for (const cricket::StreamParams& params : streams) {
2171 // |it->sync_label| is actually the data channel label. The reason is that
2172 // we use the same naming of data channels as we do for
2173 // MediaStreams and Tracks.
2174 // For MediaStreams, the sync_label is the MediaStream label and the
2175 // track label is the same as |streamid|.
2176 const std::string& channel_label = params.sync_label;
2177 auto data_channel_it = rtp_data_channels_.find(channel_label);
2178 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
2179 continue;
2180 }
2181 // Set the SSRC the data channel should use for sending.
2182 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2183 existing_channels.push_back(data_channel_it->first);
2184 }
2185
2186 UpdateClosingRtpDataChannels(existing_channels, true);
2187}
2188
2189void PeerConnection::UpdateRemoteRtpDataChannels(
2190 const cricket::StreamParamsVec& streams) {
2191 std::vector<std::string> existing_channels;
2192
2193 // Find new and active data channels.
2194 for (const cricket::StreamParams& params : streams) {
2195 // The data channel label is either the mslabel or the SSRC if the mslabel
2196 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2197 std::string label = params.sync_label.empty()
2198 ? rtc::ToString(params.first_ssrc())
2199 : params.sync_label;
2200 auto data_channel_it = rtp_data_channels_.find(label);
2201 if (data_channel_it == rtp_data_channels_.end()) {
2202 // This is a new data channel.
2203 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2204 } else {
2205 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2206 }
2207 existing_channels.push_back(label);
2208 }
2209
2210 UpdateClosingRtpDataChannels(existing_channels, false);
2211}
2212
2213void PeerConnection::UpdateClosingRtpDataChannels(
2214 const std::vector<std::string>& active_channels,
2215 bool is_local_update) {
2216 auto it = rtp_data_channels_.begin();
2217 while (it != rtp_data_channels_.end()) {
2218 DataChannel* data_channel = it->second;
2219 if (std::find(active_channels.begin(), active_channels.end(),
2220 data_channel->label()) != active_channels.end()) {
2221 ++it;
2222 continue;
2223 }
2224
2225 if (is_local_update) {
2226 data_channel->SetSendSsrc(0);
2227 } else {
2228 data_channel->RemotePeerRequestClose();
2229 }
2230
2231 if (data_channel->state() == DataChannel::kClosed) {
2232 rtp_data_channels_.erase(it);
2233 it = rtp_data_channels_.begin();
2234 } else {
2235 ++it;
2236 }
2237 }
2238}
2239
2240void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2241 uint32_t remote_ssrc) {
2242 rtc::scoped_refptr<DataChannel> channel(
2243 InternalCreateDataChannel(label, nullptr));
2244 if (!channel.get()) {
2245 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2246 << "CreateDataChannel failed.";
2247 return;
2248 }
2249 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002250 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2251 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002252 // Call both the raw pointer and scoped_refptr versions of the method
2253 // for compatibility.
2254 observer_->OnDataChannel(proxy_channel.get());
2255 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002256}
2257
2258rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2259 const std::string& label,
2260 const InternalDataChannelInit* config) {
2261 if (IsClosed()) {
2262 return nullptr;
2263 }
2264 if (session_->data_channel_type() == cricket::DCT_NONE) {
2265 LOG(LS_ERROR)
2266 << "InternalCreateDataChannel: Data is not supported in this call.";
2267 return nullptr;
2268 }
2269 InternalDataChannelInit new_config =
2270 config ? (*config) : InternalDataChannelInit();
2271 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2272 if (new_config.id < 0) {
2273 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002274 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002275 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2276 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2277 return nullptr;
2278 }
2279 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2280 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2281 << "because the id is already in use or out of range.";
2282 return nullptr;
2283 }
2284 }
2285
2286 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2287 session_.get(), session_->data_channel_type(), label, new_config));
2288 if (!channel) {
2289 sid_allocator_.ReleaseSid(new_config.id);
2290 return nullptr;
2291 }
2292
2293 if (channel->data_channel_type() == cricket::DCT_RTP) {
2294 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2295 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2296 << " already exists.";
2297 return nullptr;
2298 }
2299 rtp_data_channels_[channel->label()] = channel;
2300 } else {
2301 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2302 sctp_data_channels_.push_back(channel);
2303 channel->SignalClosed.connect(this,
2304 &PeerConnection::OnSctpDataChannelClosed);
2305 }
2306
hbos82ebe022016-11-14 01:41:09 -08002307 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002308 return channel;
2309}
2310
2311bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002312#ifdef HAVE_QUIC
2313 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2314 (session_->quic_data_transport() &&
2315 session_->quic_data_transport()->HasDataChannels());
2316#else
deadbeefab9b2d12015-10-14 11:33:11 -07002317 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002318#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002319}
2320
2321void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2322 for (const auto& channel : sctp_data_channels_) {
2323 if (channel->id() < 0) {
2324 int sid;
2325 if (!sid_allocator_.AllocateSid(role, &sid)) {
2326 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2327 continue;
2328 }
2329 channel->SetSctpSid(sid);
2330 }
2331 }
2332}
2333
2334void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002335 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002336 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2337 ++it) {
2338 if (it->get() == channel) {
2339 if (channel->id() >= 0) {
2340 sid_allocator_.ReleaseSid(channel->id());
2341 }
deadbeefbd292462015-12-14 18:15:29 -08002342 // Since this method is triggered by a signal from the DataChannel,
2343 // we can't free it directly here; we need to free it asynchronously.
2344 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002345 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002346 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2347 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002348 return;
2349 }
2350 }
2351}
2352
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002353void PeerConnection::OnVoiceChannelCreated() {
2354 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2355 session_->voice_channel(), senders_, receivers_,
2356 cricket::MEDIA_TYPE_AUDIO);
2357}
2358
deadbeefab9b2d12015-10-14 11:33:11 -07002359void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002360 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2361 cricket::VoiceChannel>(
2362 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2363}
2364
2365void PeerConnection::OnVideoChannelCreated() {
2366 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2367 session_->video_channel(), senders_, receivers_,
2368 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002369}
2370
2371void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002372 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2373 cricket::VideoChannel>(
2374 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002375}
2376
2377void PeerConnection::OnDataChannelCreated() {
2378 for (const auto& channel : sctp_data_channels_) {
2379 channel->OnTransportChannelCreated();
2380 }
2381}
2382
2383void PeerConnection::OnDataChannelDestroyed() {
2384 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2385 // DataChannel may callback to us and try to modify the list.
2386 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2387 temp_rtp_dcs.swap(rtp_data_channels_);
2388 for (const auto& kv : temp_rtp_dcs) {
2389 kv.second->OnTransportChannelDestroyed();
2390 }
2391
2392 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2393 temp_sctp_dcs.swap(sctp_data_channels_);
2394 for (const auto& channel : temp_sctp_dcs) {
2395 channel->OnTransportChannelDestroyed();
2396 }
2397}
2398
2399void PeerConnection::OnDataChannelOpenMessage(
2400 const std::string& label,
2401 const InternalDataChannelInit& config) {
2402 rtc::scoped_refptr<DataChannel> channel(
2403 InternalCreateDataChannel(label, &config));
2404 if (!channel.get()) {
2405 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2406 return;
2407 }
2408
deadbeefa601f5c2016-06-06 14:27:39 -07002409 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2410 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002411 // Call both the raw pointer and scoped_refptr versions of the method
2412 // for compatibility.
2413 observer_->OnDataChannel(proxy_channel.get());
2414 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002415}
2416
deadbeefa601f5c2016-06-06 14:27:39 -07002417RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2418 auto it = std::find_if(
2419 senders_.begin(), senders_.end(),
2420 [id](const rtc::scoped_refptr<
2421 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2422 return sender->id() == id;
2423 });
2424 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002425}
2426
deadbeefa601f5c2016-06-06 14:27:39 -07002427std::vector<
2428 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002429PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2430 return std::find_if(
2431 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002432 [track](const rtc::scoped_refptr<
2433 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002434 return sender->track() == track;
2435 });
2436}
2437
deadbeefa601f5c2016-06-06 14:27:39 -07002438std::vector<rtc::scoped_refptr<
2439 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002440PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002441 return std::find_if(
2442 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002443 [track_id](const rtc::scoped_refptr<
2444 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002445 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002446 });
2447}
2448
deadbeefab9b2d12015-10-14 11:33:11 -07002449PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2450 cricket::MediaType media_type) {
2451 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2452 media_type == cricket::MEDIA_TYPE_VIDEO);
2453 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2454 : &remote_video_tracks_;
2455}
2456
2457PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2458 cricket::MediaType media_type) {
2459 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2460 media_type == cricket::MEDIA_TYPE_VIDEO);
2461 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2462 : &local_video_tracks_;
2463}
2464
2465const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2466 const PeerConnection::TrackInfos& infos,
2467 const std::string& stream_label,
2468 const std::string track_id) const {
2469 for (const TrackInfo& track_info : infos) {
2470 if (track_info.stream_label == stream_label &&
2471 track_info.track_id == track_id) {
2472 return &track_info;
2473 }
2474 }
2475 return nullptr;
2476}
2477
2478DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2479 for (const auto& channel : sctp_data_channels_) {
2480 if (channel->id() == sid) {
2481 return channel;
2482 }
2483 }
2484 return nullptr;
2485}
2486
deadbeef91dd5672016-05-18 16:55:30 -07002487bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002488 const RTCConfiguration& configuration) {
2489 cricket::ServerAddresses stun_servers;
2490 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef7a5fa6c2016-12-24 00:47:59 -08002491 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2492 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002493 return false;
2494 }
2495
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002496 port_allocator_->Initialize();
2497
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002498 // To handle both internal and externally created port allocator, we will
2499 // enable BUNDLE here.
2500 int portallocator_flags = port_allocator_->flags();
2501 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2502 cricket::PORTALLOCATOR_ENABLE_IPV6;
2503 // If the disable-IPv6 flag was specified, we'll not override it
2504 // by experiment.
2505 if (configuration.disable_ipv6) {
2506 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2507 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2508 "Disabled") {
2509 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2510 }
2511
2512 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2513 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2514 LOG(LS_INFO) << "TCP candidates are disabled.";
2515 }
2516
honghaiz60347052016-05-31 18:29:12 -07002517 if (configuration.candidate_network_policy ==
2518 kCandidateNetworkPolicyLowCost) {
2519 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2520 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2521 }
2522
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002523 port_allocator_->set_flags(portallocator_flags);
2524 // No step delay is used while allocating ports.
2525 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2526 port_allocator_->set_candidate_filter(
2527 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2528
2529 // Call this last since it may create pooled allocator sessions using the
2530 // properties set above.
2531 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002532 configuration.ice_candidate_pool_size,
2533 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002534 return true;
2535}
2536
deadbeef91dd5672016-05-18 16:55:30 -07002537bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef7a5fa6c2016-12-24 00:47:59 -08002538 const cricket::ServerAddresses& stun_servers,
2539 const std::vector<cricket::RelayServerConfig>& turn_servers,
2540 IceTransportsType type,
2541 int candidate_pool_size,
2542 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002543 port_allocator_->set_candidate_filter(
deadbeef7a5fa6c2016-12-24 00:47:59 -08002544 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002545 // Call this last since it may create pooled allocator sessions using the
2546 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002547 return port_allocator_->SetConfiguration(
deadbeef7a5fa6c2016-12-24 00:47:59 -08002548 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002549}
2550
ivoc14d5dbe2016-07-04 07:06:55 -07002551bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2552 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002553 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002554}
2555
2556void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002557 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002558}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559} // namespace webrtc