blob: 3a38248b7b85b00a78354b898ce3750a92c90a33 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00003 * Copyright 2012 Google Inc.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/peerconnection.h"
29
deadbeefeb459812015-12-15 19:24:43 -080030#include <algorithm>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000031#include <vector>
deadbeef0a6c4ca2015-10-06 11:38:28 -070032#include <cctype> // for isdigit
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033
deadbeefab9b2d12015-10-14 11:33:11 -070034#include "talk/app/webrtc/audiotrack.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000035#include "talk/app/webrtc/dtmfsender.h"
36#include "talk/app/webrtc/jsepicecandidate.h"
37#include "talk/app/webrtc/jsepsessiondescription.h"
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +000038#include "talk/app/webrtc/mediaconstraintsinterface.h"
deadbeefab9b2d12015-10-14 11:33:11 -070039#include "talk/app/webrtc/mediastream.h"
deadbeefeb459812015-12-15 19:24:43 -080040#include "talk/app/webrtc/mediastreamobserver.h"
deadbeefab9b2d12015-10-14 11:33:11 -070041#include "talk/app/webrtc/mediastreamproxy.h"
42#include "talk/app/webrtc/mediastreamtrackproxy.h"
43#include "talk/app/webrtc/remoteaudiosource.h"
44#include "talk/app/webrtc/remotevideocapturer.h"
deadbeef70ab1a12015-09-28 16:53:55 -070045#include "talk/app/webrtc/rtpreceiver.h"
46#include "talk/app/webrtc/rtpsender.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047#include "talk/app/webrtc/streamcollection.h"
deadbeefab9b2d12015-10-14 11:33:11 -070048#include "talk/app/webrtc/videosource.h"
49#include "talk/app/webrtc/videotrack.h"
50#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051#include "talk/session/media/channelmanager.h"
tfarina5237aaf2015-11-10 23:44:30 -080052#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000053#include "webrtc/base/logging.h"
54#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070055#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010056#include "webrtc/base/trace_event.h"
tfarina5237aaf2015-11-10 23:44:30 -080057#include "webrtc/p2p/client/basicportallocator.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010058#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059
60namespace {
61
deadbeefab9b2d12015-10-14 11:33:11 -070062using webrtc::DataChannel;
63using webrtc::MediaConstraintsInterface;
64using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065using webrtc::PeerConnectionInterface;
deadbeeffac06552015-11-25 11:26:01 -080066using webrtc::RtpSenderInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070067using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070068using webrtc::StunConfigurations;
69using webrtc::TurnConfigurations;
70typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
71 StunConfiguration;
72typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
73 TurnConfiguration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
deadbeefab9b2d12015-10-14 11:33:11 -070075static const char kDefaultStreamLabel[] = "default";
76static const char kDefaultAudioTrackLabel[] = "defaulta0";
77static const char kDefaultVideoTrackLabel[] = "defaultv0";
78
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079// The min number of tokens must present in Turn host uri.
80// e.g. user@turn.example.org
81static const size_t kTurnHostTokensNum = 2;
82// Number of tokens must be preset when TURN uri has transport param.
83static const size_t kTurnTransportTokensNum = 2;
84// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000085static const int kDefaultStunPort = 3478;
86static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000088static const char kUdpTransportType[] = "udp";
89static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
91// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070092static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
deadbeef0a6c4ca2015-10-06 11:38:28 -070094// NOTE: A loop below assumes that the first value of this enum is 0 and all
95// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070097 STUN = 0, // Indicates a STUN server.
98 STUNS, // Indicates a STUN server used with a TLS session.
99 TURN, // Indicates a TURN server
100 TURNS, // Indicates a TURN server used with a TLS session.
101 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102};
tfarina5237aaf2015-11-10 23:44:30 -0800103static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -0700104 "kValidIceServiceTypes must have as many strings as ServiceType "
105 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106
107enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000108 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700110 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800112 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000113};
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
118 : observer(observer) {
119 }
120
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122 std::string error;
123};
124
deadbeefab9b2d12015-10-14 11:33:11 -0700125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 std::string error;
132};
133
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000134struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000139 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000140 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000141};
142
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000143// |in_str| should be of format
144// stunURI = scheme ":" stun-host [ ":" stun-port ]
145// scheme = "stun" / "stuns"
146// stun-host = IP-literal / IPv4address / reg-name
147// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700148//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000149// draft-petithuguenin-behave-turn-uris-01
150// turnURI = scheme ":" turn-host [ ":" turn-port ]
151// turn-host = username@IP-literal / IPv4address / reg-name
152bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
153 ServiceType* service_type,
154 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200155 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700156 if (colonpos == std::string::npos) {
157 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000158 return false;
159 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700160 if ((colonpos + 1) == in_str.length()) {
161 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
162 return false;
163 }
164 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800165 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700166 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000167 *service_type = static_cast<ServiceType>(i);
168 break;
169 }
170 }
171 if (*service_type == INVALID) {
172 return false;
173 }
174 *hostname = in_str.substr(colonpos + 1, std::string::npos);
175 return true;
176}
177
deadbeef0a6c4ca2015-10-06 11:38:28 -0700178bool ParsePort(const std::string& in_str, int* port) {
179 // Make sure port only contains digits. FromString doesn't check this.
180 for (const char& c : in_str) {
181 if (!std::isdigit(c)) {
182 return false;
183 }
184 }
185 return rtc::FromString(in_str, port);
186}
187
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000188// This method parses IPv6 and IPv4 literal strings, along with hostnames in
189// standard hostname:port format.
190// Consider following formats as correct.
191// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700192// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000193bool ParseHostnameAndPortFromString(const std::string& in_str,
194 std::string* host,
195 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700196 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000197 if (in_str.at(0) == '[') {
198 std::string::size_type closebracket = in_str.rfind(']');
199 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000200 std::string::size_type colonpos = in_str.find(':', closebracket);
201 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700202 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
203 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000204 return false;
205 }
206 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700207 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000208 } else {
209 return false;
210 }
211 } else {
212 std::string::size_type colonpos = in_str.find(':');
213 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700214 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000215 return false;
216 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700217 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000218 } else {
219 *host = in_str;
220 }
221 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700222 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000223}
224
deadbeef0a6c4ca2015-10-06 11:38:28 -0700225// Adds a StunConfiguration or TurnConfiguration to the appropriate list,
226// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200227bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
228 const std::string& url,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700229 StunConfigurations* stun_config,
230 TurnConfigurations* turn_config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231 // draft-nandakumar-rtcweb-stun-uri-01
232 // stunURI = scheme ":" stun-host [ ":" stun-port ]
233 // scheme = "stun" / "stuns"
234 // stun-host = IP-literal / IPv4address / reg-name
235 // stun-port = *DIGIT
236
237 // draft-petithuguenin-behave-turn-uris-01
238 // turnURI = scheme ":" turn-host [ ":" turn-port ]
239 // [ "?transport=" transport ]
240 // scheme = "turn" / "turns"
241 // transport = "udp" / "tcp" / transport-ext
242 // transport-ext = 1*unreserved
243 // turn-host = IP-literal / IPv4address / reg-name
244 // turn-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700245 RTC_DCHECK(stun_config != nullptr);
246 RTC_DCHECK(turn_config != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200247 std::vector<std::string> tokens;
248 std::string turn_transport_type = kUdpTransportType;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700249 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200250 rtc::tokenize(url, '?', &tokens);
251 std::string uri_without_transport = tokens[0];
252 // Let's look into transport= param, if it exists.
253 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
254 std::string uri_transport_param = tokens[1];
255 rtc::tokenize(uri_transport_param, '=', &tokens);
256 if (tokens[0] == kTransport) {
257 // As per above grammar transport param will be consist of lower case
258 // letters.
259 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
260 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200263 turn_transport_type = tokens[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200265 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200267 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700268 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200269 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
270 &service_type,
271 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700272 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
273 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200274 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000275
deadbeef0a6c4ca2015-10-06 11:38:28 -0700276 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
277 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200278
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200279 // Let's break hostname.
280 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700281 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
282
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200283 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700284 if (tokens.size() > kTurnHostTokensNum) {
285 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
286 return false;
287 }
288 if (tokens.size() == kTurnHostTokensNum) {
289 if (tokens[0].empty() || tokens[1].empty()) {
290 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
291 return false;
292 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200293 username.assign(rtc::s_url_decode(tokens[0]));
294 hoststring = tokens[1];
295 } else {
296 hoststring = tokens[0];
297 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000298
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 int port = kDefaultStunPort;
300 if (service_type == TURNS) {
301 port = kDefaultStunTlsPort;
302 turn_transport_type = kTcpTransportType;
303 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000304
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200305 std::string address;
306 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700307 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
308 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200309 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000310
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200311 if (port <= 0 || port > 0xffff) {
312 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700313 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200314 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000315
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200316 switch (service_type) {
317 case STUN:
318 case STUNS:
319 stun_config->push_back(StunConfiguration(address, port));
320 break;
321 case TURN:
322 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200323 bool secure = (service_type == TURNS);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200324 turn_config->push_back(TurnConfiguration(address, port,
325 username,
326 server.password,
327 turn_transport_type,
328 secure));
329 break;
330 }
331 case INVALID:
332 default:
333 LOG(WARNING) << "Configuration not supported: " << url;
334 return false;
335 }
336 return true;
337}
338
deadbeef653b8e02015-11-11 12:55:10 -0800339void ConvertToCricketIceServers(
340 const std::vector<StunConfiguration>& stuns,
341 const std::vector<TurnConfiguration>& turns,
342 cricket::ServerAddresses* cricket_stuns,
343 std::vector<cricket::RelayServerConfig>* cricket_turns) {
344 RTC_DCHECK(cricket_stuns && cricket_turns);
345 for (const StunConfiguration& stun : stuns) {
346 cricket_stuns->insert(stun.server);
347 }
348
349 int priority = static_cast<int>(turns.size() - 1);
350 for (const TurnConfiguration& turn : turns) {
351 cricket::RelayCredentials credentials(turn.username, turn.password);
352 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
353 cricket::ProtocolType protocol;
354 // Using VERIFY because ParseIceServers should have already caught an
355 // invalid transport type.
356 if (!VERIFY(
357 cricket::StringToProto(turn.transport_type.c_str(), &protocol))) {
358 LOG(LS_WARNING) << "Ignoring TURN server " << turn.server << ". "
359 << "Reason= Incorrect " << turn.transport_type
360 << " transport parameter.";
361 } else {
362 relay_server.ports.push_back(
363 cricket::ProtocolAddress(turn.server, protocol, turn.secure));
364 relay_server.credentials = credentials;
365 relay_server.priority = priority;
366 cricket_turns->push_back(relay_server);
367 }
368 // First in the list gets highest priority.
369 --priority;
370 }
371}
372
deadbeefab9b2d12015-10-14 11:33:11 -0700373// Check if we can send |new_stream| on a PeerConnection.
374bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
375 webrtc::MediaStreamInterface* new_stream) {
376 if (!new_stream || !current_streams) {
377 return false;
378 }
379 if (current_streams->find(new_stream->label()) != nullptr) {
380 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
381 << " is already added.";
382 return false;
383 }
384 return true;
385}
386
387bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
388 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
389}
390
deadbeef5e97fb52015-10-15 12:49:08 -0700391// If the direction is "recvonly" or "inactive", treat the description
392// as containing no streams.
393// See: https://code.google.com/p/webrtc/issues/detail?id=5054
394std::vector<cricket::StreamParams> GetActiveStreams(
395 const cricket::MediaContentDescription* desc) {
396 return MediaContentDirectionHasSend(desc->direction())
397 ? desc->streams()
398 : std::vector<cricket::StreamParams>();
399}
400
deadbeefab9b2d12015-10-14 11:33:11 -0700401bool IsValidOfferToReceiveMedia(int value) {
402 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
403 return (value >= Options::kUndefined) &&
404 (value <= Options::kMaxOfferToReceiveMedia);
405}
406
407// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800408void AddSendStreams(
409 cricket::MediaSessionOptions* session_options,
410 const std::vector<rtc::scoped_refptr<RtpSenderInterface>>& senders,
411 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
412 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700413 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800414 for (const auto& sender : senders) {
415 session_options->AddSendStream(sender->media_type(), sender->id(),
416 sender->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700417 }
418
419 // Check for data channels.
420 for (const auto& kv : rtp_data_channels) {
421 const DataChannel* channel = kv.second;
422 if (channel->state() == DataChannel::kConnecting ||
423 channel->state() == DataChannel::kOpen) {
424 // |streamid| and |sync_label| are both set to the DataChannel label
425 // here so they can be signaled the same way as MediaStreams and Tracks.
426 // For MediaStreams, the sync_label is the MediaStream label and the
427 // track label is the same as |streamid|.
428 const std::string& streamid = channel->label();
429 const std::string& sync_label = channel->label();
430 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
431 sync_label);
432 }
433 }
434}
435
deadbeef0a6c4ca2015-10-06 11:38:28 -0700436} // namespace
437
438namespace webrtc {
439
deadbeefab9b2d12015-10-14 11:33:11 -0700440// Factory class for creating remote MediaStreams and MediaStreamTracks.
441class RemoteMediaStreamFactory {
442 public:
443 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
444 cricket::ChannelManager* channel_manager)
445 : signaling_thread_(signaling_thread),
446 channel_manager_(channel_manager) {}
447
448 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
449 const std::string& stream_label) {
450 return MediaStreamProxy::Create(signaling_thread_,
451 MediaStream::Create(stream_label));
452 }
453
Tommif888bb52015-12-12 01:37:01 +0100454 AudioTrackInterface* AddAudioTrack(uint32_t ssrc,
455 AudioProviderInterface* provider,
456 webrtc::MediaStreamInterface* stream,
deadbeefab9b2d12015-10-14 11:33:11 -0700457 const std::string& track_id) {
tommi6eca7e32015-12-15 04:27:11 -0800458 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
Tommif888bb52015-12-12 01:37:01 +0100459 stream, track_id, RemoteAudioSource::Create(ssrc, provider));
deadbeefab9b2d12015-10-14 11:33:11 -0700460 }
461
462 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
463 const std::string& track_id) {
464 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
465 stream, track_id,
466 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
tommi6eca7e32015-12-15 04:27:11 -0800467 nullptr, true)
deadbeefab9b2d12015-10-14 11:33:11 -0700468 .get());
469 }
470
471 private:
472 template <typename TI, typename T, typename TP, typename S>
473 TI* AddTrack(MediaStreamInterface* stream,
474 const std::string& track_id,
Tommif888bb52015-12-12 01:37:01 +0100475 const S& source) {
deadbeefab9b2d12015-10-14 11:33:11 -0700476 rtc::scoped_refptr<TI> track(
477 TP::Create(signaling_thread_, T::Create(track_id, source)));
478 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
479 if (stream->AddTrack(track)) {
480 return track;
481 }
482 return nullptr;
483 }
484
485 rtc::Thread* signaling_thread_;
486 cricket::ChannelManager* channel_manager_;
487};
488
489bool ConvertRtcOptionsForOffer(
490 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
491 cricket::MediaSessionOptions* session_options) {
492 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
493 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
494 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
495 return false;
496 }
497
deadbeefc80741f2015-10-22 13:14:45 -0700498 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700499 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
500 }
deadbeefc80741f2015-10-22 13:14:45 -0700501 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700502 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
503 }
504
505 session_options->vad_enabled = rtc_options.voice_activity_detection;
506 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700507 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700508
509 return true;
510}
511
512bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
513 cricket::MediaSessionOptions* session_options) {
514 bool value = false;
515 size_t mandatory_constraints_satisfied = 0;
516
517 // kOfferToReceiveAudio defaults to true according to spec.
518 if (!FindConstraint(constraints,
519 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
520 &mandatory_constraints_satisfied) ||
521 value) {
522 session_options->recv_audio = true;
523 }
524
525 // kOfferToReceiveVideo defaults to false according to spec. But
526 // if it is an answer and video is offered, we should still accept video
527 // per default.
528 value = false;
529 if (!FindConstraint(constraints,
530 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
531 &mandatory_constraints_satisfied) ||
532 value) {
533 session_options->recv_video = true;
534 }
535
536 if (FindConstraint(constraints,
537 MediaConstraintsInterface::kVoiceActivityDetection, &value,
538 &mandatory_constraints_satisfied)) {
539 session_options->vad_enabled = value;
540 }
541
542 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
543 &mandatory_constraints_satisfied)) {
544 session_options->bundle_enabled = value;
545 } else {
546 // kUseRtpMux defaults to true according to spec.
547 session_options->bundle_enabled = true;
548 }
deadbeefab9b2d12015-10-14 11:33:11 -0700549
550 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
551 &value, &mandatory_constraints_satisfied)) {
552 session_options->transport_options.ice_restart = value;
553 } else {
554 // kIceRestart defaults to false according to spec.
555 session_options->transport_options.ice_restart = false;
556 }
557
558 if (!constraints) {
559 return true;
560 }
561 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
562}
563
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200564bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700565 StunConfigurations* stun_config,
566 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200567 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
568 if (!server.urls.empty()) {
569 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200570 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700571 LOG(LS_ERROR) << "Empty uri.";
572 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200573 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200574 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
575 return false;
576 }
577 }
578 } else if (!server.uri.empty()) {
579 // Fallback to old .uri if new .urls isn't present.
580 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000581 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200582 }
583 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700584 LOG(LS_ERROR) << "Empty uri.";
585 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586 }
587 }
588 return true;
589}
590
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591PeerConnection::PeerConnection(PeerConnectionFactory* factory)
592 : factory_(factory),
593 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000594 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595 signaling_state_(kStable),
596 ice_state_(kIceNew),
597 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700598 ice_gathering_state_(kIceGatheringNew),
599 local_streams_(StreamCollection::Create()),
600 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601
602PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100603 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700604 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700605 // Need to detach RTP senders/receivers from WebRtcSession,
606 // since it's about to be destroyed.
607 for (const auto& sender : senders_) {
608 sender->Stop();
609 }
610 for (const auto& receiver : receivers_) {
611 receiver->Stop();
612 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613}
614
615bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000616 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000617 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000618 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200619 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000620 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700621 RTC_DCHECK(observer != nullptr);
622 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000623 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700624 }
deadbeef653b8e02015-11-11 12:55:10 -0800625
626 // This Initialize function parses ICE servers an extra time, but it will
627 // be removed once all PortAllocaotrs support SetIceServers.
628 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
629 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
630 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
631 return false;
632 }
633 rtc::scoped_ptr<cricket::PortAllocator> allocator(
634 allocator_factory->CreatePortAllocator(stun_config, turn_config));
635 return Initialize(configuration, constraints, allocator.Pass(),
636 dtls_identity_store.Pass(), observer);
637}
638
639bool PeerConnection::Initialize(
640 const PeerConnectionInterface::RTCConfiguration& configuration,
641 const MediaConstraintsInterface* constraints,
642 rtc::scoped_ptr<cricket::PortAllocator> allocator,
643 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
644 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100645 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800646 RTC_DCHECK(observer != nullptr);
647 if (!observer) {
648 return false;
649 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000650 observer_ = observer;
651
deadbeef653b8e02015-11-11 12:55:10 -0800652 port_allocator_ = allocator.Pass();
653
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000654 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
655 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000656 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 return false;
658 }
deadbeef653b8e02015-11-11 12:55:10 -0800659
660 cricket::ServerAddresses cricket_stuns;
661 std::vector<cricket::RelayServerConfig> cricket_turns;
662 ConvertToCricketIceServers(stun_config, turn_config, &cricket_stuns,
663 &cricket_turns);
664 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000665
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000667 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000668 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700669 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000670 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000671 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000672 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700673 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
674 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000675 if (!value) {
676 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000677 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000678 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000679 "Disabled") {
680 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000681 }
682
Jiayang Liucac1b382015-04-30 12:35:24 -0700683 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
684 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
685 LOG(LS_INFO) << "TCP candidates are disabled.";
686 }
687
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000688 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 // No step delay is used while allocating ports.
690 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
691
stefanc1aeaf02015-10-15 07:26:07 -0700692 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693
stefanc1aeaf02015-10-15 07:26:07 -0700694 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
695 factory_->signaling_thread(), media_controller_->channel_manager()));
696
697 session_.reset(
698 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
699 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700700 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701
702 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000703 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700704 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700706 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708 // Register PeerConnection as receiver of local ice candidates.
709 // All the callbacks will be posted to the application from PeerConnection.
710 session_->RegisterIceObserver(this);
711 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700712 session_->SignalVoiceChannelDestroyed.connect(
713 this, &PeerConnection::OnVoiceChannelDestroyed);
714 session_->SignalVideoChannelDestroyed.connect(
715 this, &PeerConnection::OnVideoChannelDestroyed);
716 session_->SignalDataChannelCreated.connect(
717 this, &PeerConnection::OnDataChannelCreated);
718 session_->SignalDataChannelDestroyed.connect(
719 this, &PeerConnection::OnDataChannelDestroyed);
720 session_->SignalDataChannelOpenMessage.connect(
721 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 return true;
723}
724
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000725rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700727 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728}
729
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000730rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700732 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733}
734
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000735bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100736 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737 if (IsClosed()) {
738 return false;
739 }
deadbeefab9b2d12015-10-14 11:33:11 -0700740 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 return false;
742 }
deadbeefab9b2d12015-10-14 11:33:11 -0700743
744 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800745 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
746 observer->SignalAudioTrackAdded.connect(this,
747 &PeerConnection::OnAudioTrackAdded);
748 observer->SignalAudioTrackRemoved.connect(
749 this, &PeerConnection::OnAudioTrackRemoved);
750 observer->SignalVideoTrackAdded.connect(this,
751 &PeerConnection::OnVideoTrackAdded);
752 observer->SignalVideoTrackRemoved.connect(
753 this, &PeerConnection::OnVideoTrackRemoved);
754 stream_observers_.push_back(rtc::scoped_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700755
deadbeefab9b2d12015-10-14 11:33:11 -0700756 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800757 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700758 }
759 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800760 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700761 }
762
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000763 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764 observer_->OnRenegotiationNeeded();
765 return true;
766}
767
768void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100769 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700770 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800771 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700772 }
773 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800774 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700775 }
776
777 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800778 stream_observers_.erase(
779 std::remove_if(
780 stream_observers_.begin(), stream_observers_.end(),
781 [local_stream](const rtc::scoped_ptr<MediaStreamObserver>& observer) {
782 return observer->stream()->label().compare(local_stream->label()) ==
783 0;
784 }),
785 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700786
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000787 if (IsClosed()) {
788 return;
789 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790 observer_->OnRenegotiationNeeded();
791}
792
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000793rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100795 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 if (!track) {
797 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
798 return NULL;
799 }
deadbeefab9b2d12015-10-14 11:33:11 -0700800 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
802 return NULL;
803 }
804
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000805 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 DtmfSender::Create(track, signaling_thread(), session_.get()));
807 if (!sender.get()) {
808 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
809 return NULL;
810 }
811 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
812}
813
deadbeeffac06552015-11-25 11:26:01 -0800814rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
815 const std::string& kind) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100816 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeeffac06552015-11-25 11:26:01 -0800817 RtpSenderInterface* new_sender;
818 if (kind == MediaStreamTrackInterface::kAudioKind) {
819 new_sender = new AudioRtpSender(session_.get(), stats_.get());
820 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
821 new_sender = new VideoRtpSender(session_.get());
822 } else {
823 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
824 return rtc::scoped_refptr<RtpSenderInterface>();
825 }
826 senders_.push_back(new_sender);
827 return RtpSenderProxy::Create(signaling_thread(), new_sender);
828}
829
deadbeef70ab1a12015-09-28 16:53:55 -0700830std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
831 const {
832 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
833 for (const auto& sender : senders_) {
834 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
835 }
836 return senders;
837}
838
839std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
840PeerConnection::GetReceivers() const {
841 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
842 for (const auto& receiver : receivers_) {
843 receivers.push_back(
844 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
845 }
846 return receivers;
847}
848
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000850 MediaStreamTrackInterface* track,
851 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100852 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700853 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000854 if (!VERIFY(observer != NULL)) {
855 LOG(LS_ERROR) << "GetStats - observer is NULL.";
856 return false;
857 }
858
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000859 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000860 signaling_thread()->Post(this, MSG_GETSTATS,
861 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862 return true;
863}
864
865PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
866 return signaling_state_;
867}
868
869PeerConnectionInterface::IceState PeerConnection::ice_state() {
870 return ice_state_;
871}
872
873PeerConnectionInterface::IceConnectionState
874PeerConnection::ice_connection_state() {
875 return ice_connection_state_;
876}
877
878PeerConnectionInterface::IceGatheringState
879PeerConnection::ice_gathering_state() {
880 return ice_gathering_state_;
881}
882
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000883rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884PeerConnection::CreateDataChannel(
885 const std::string& label,
886 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100887 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700888 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000889
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000890 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000891 if (config) {
892 internal_config.reset(new InternalDataChannelInit(*config));
893 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000894 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700895 InternalCreateDataChannel(label, internal_config.get()));
896 if (!channel.get()) {
897 return nullptr;
898 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000900 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
901 // the first SCTP DataChannel.
902 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
903 observer_->OnRenegotiationNeeded();
904 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000905
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906 return DataChannelProxy::Create(signaling_thread(), channel.get());
907}
908
909void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
910 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100911 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700912 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
914 return;
915 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000916 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000917
918 bool value;
919 size_t mandatory_constraints = 0;
920
921 if (FindConstraint(constraints,
922 MediaConstraintsInterface::kOfferToReceiveAudio,
923 &value,
924 &mandatory_constraints)) {
925 options.offer_to_receive_audio =
926 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
927 }
928
929 if (FindConstraint(constraints,
930 MediaConstraintsInterface::kOfferToReceiveVideo,
931 &value,
932 &mandatory_constraints)) {
933 options.offer_to_receive_video =
934 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
935 }
936
937 if (FindConstraint(constraints,
938 MediaConstraintsInterface::kVoiceActivityDetection,
939 &value,
940 &mandatory_constraints)) {
941 options.voice_activity_detection = value;
942 }
943
944 if (FindConstraint(constraints,
945 MediaConstraintsInterface::kIceRestart,
946 &value,
947 &mandatory_constraints)) {
948 options.ice_restart = value;
949 }
950
951 if (FindConstraint(constraints,
952 MediaConstraintsInterface::kUseRtpMux,
953 &value,
954 &mandatory_constraints)) {
955 options.use_rtp_mux = value;
956 }
957
958 CreateOffer(observer, options);
959}
960
961void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
962 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100963 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700964 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000965 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
966 return;
967 }
deadbeefab9b2d12015-10-14 11:33:11 -0700968
969 cricket::MediaSessionOptions session_options;
970 if (!GetOptionsForOffer(options, &session_options)) {
971 std::string error = "CreateOffer called with invalid options.";
972 LOG(LS_ERROR) << error;
973 PostCreateSessionDescriptionFailure(observer, error);
974 return;
975 }
976
977 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978}
979
980void PeerConnection::CreateAnswer(
981 CreateSessionDescriptionObserver* observer,
982 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100983 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -0700984 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
986 return;
987 }
deadbeefab9b2d12015-10-14 11:33:11 -0700988
989 cricket::MediaSessionOptions session_options;
990 if (!GetOptionsForAnswer(constraints, &session_options)) {
991 std::string error = "CreateAnswer called with invalid constraints.";
992 LOG(LS_ERROR) << error;
993 PostCreateSessionDescriptionFailure(observer, error);
994 return;
995 }
996
997 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998}
999
1000void PeerConnection::SetLocalDescription(
1001 SetSessionDescriptionObserver* observer,
1002 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001003 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001004 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1006 return;
1007 }
1008 if (!desc) {
1009 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1010 return;
1011 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 // Update stats here so that we have the most recent stats for tracks and
1013 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001014 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 std::string error;
1016 if (!session_->SetLocalDescription(desc, &error)) {
1017 PostSetSessionDescriptionFailure(observer, error);
1018 return;
1019 }
deadbeefab9b2d12015-10-14 11:33:11 -07001020
1021 // If setting the description decided our SSL role, allocate any necessary
1022 // SCTP sids.
1023 rtc::SSLRole role;
1024 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1025 session_->GetSslRole(&role)) {
1026 AllocateSctpSids(role);
1027 }
1028
1029 // Update state and SSRC of local MediaStreams and DataChannels based on the
1030 // local session description.
1031 const cricket::ContentInfo* audio_content =
1032 GetFirstAudioContent(desc->description());
1033 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001034 if (audio_content->rejected) {
1035 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1036 } else {
1037 const cricket::AudioContentDescription* audio_desc =
1038 static_cast<const cricket::AudioContentDescription*>(
1039 audio_content->description);
1040 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1041 }
deadbeefab9b2d12015-10-14 11:33:11 -07001042 }
1043
1044 const cricket::ContentInfo* video_content =
1045 GetFirstVideoContent(desc->description());
1046 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001047 if (video_content->rejected) {
1048 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1049 } else {
1050 const cricket::VideoContentDescription* video_desc =
1051 static_cast<const cricket::VideoContentDescription*>(
1052 video_content->description);
1053 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1054 }
deadbeefab9b2d12015-10-14 11:33:11 -07001055 }
1056
1057 const cricket::ContentInfo* data_content =
1058 GetFirstDataContent(desc->description());
1059 if (data_content) {
1060 const cricket::DataContentDescription* data_desc =
1061 static_cast<const cricket::DataContentDescription*>(
1062 data_content->description);
1063 if (rtc::starts_with(data_desc->protocol().data(),
1064 cricket::kMediaProtocolRtpPrefix)) {
1065 UpdateLocalRtpDataChannels(data_desc->streams());
1066 }
1067 }
1068
1069 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001070 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001071
deadbeefcbecd352015-09-23 11:50:27 -07001072 // MaybeStartGathering needs to be called after posting
1073 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1074 // before signaling that SetLocalDescription completed.
1075 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001076}
1077
1078void PeerConnection::SetRemoteDescription(
1079 SetSessionDescriptionObserver* observer,
1080 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001081 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001082 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1084 return;
1085 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086 if (!desc) {
1087 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1088 return;
1089 }
1090 // Update stats here so that we have the most recent stats for tracks and
1091 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001092 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 std::string error;
1094 if (!session_->SetRemoteDescription(desc, &error)) {
1095 PostSetSessionDescriptionFailure(observer, error);
1096 return;
1097 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098
deadbeefab9b2d12015-10-14 11:33:11 -07001099 // If setting the description decided our SSL role, allocate any necessary
1100 // SCTP sids.
1101 rtc::SSLRole role;
1102 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1103 session_->GetSslRole(&role)) {
1104 AllocateSctpSids(role);
1105 }
1106
1107 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001108 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1109 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1110 const cricket::AudioContentDescription* audio_desc =
1111 GetFirstAudioContentDescription(remote_desc);
1112 const cricket::VideoContentDescription* video_desc =
1113 GetFirstVideoContentDescription(remote_desc);
1114 const cricket::DataContentDescription* data_desc =
1115 GetFirstDataContentDescription(remote_desc);
1116
1117 // Check if the descriptions include streams, just in case the peer supports
1118 // MSID, but doesn't indicate so with "a=msid-semantic".
1119 if (remote_desc->msid_supported() ||
1120 (audio_desc && !audio_desc->streams().empty()) ||
1121 (video_desc && !video_desc->streams().empty())) {
1122 remote_peer_supports_msid_ = true;
1123 }
deadbeefab9b2d12015-10-14 11:33:11 -07001124
1125 // We wait to signal new streams until we finish processing the description,
1126 // since only at that point will new streams have all their tracks.
1127 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1128
1129 // Find all audio rtp streams and create corresponding remote AudioTracks
1130 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001131 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001132 if (audio_content->rejected) {
1133 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1134 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001135 bool default_audio_track_needed =
1136 !remote_peer_supports_msid_ &&
1137 MediaContentDirectionHasSend(audio_desc->direction());
1138 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1139 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001140 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001141 }
deadbeefab9b2d12015-10-14 11:33:11 -07001142 }
1143
1144 // Find all video rtp streams and create corresponding remote VideoTracks
1145 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001146 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001147 if (video_content->rejected) {
1148 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1149 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001150 bool default_video_track_needed =
1151 !remote_peer_supports_msid_ &&
1152 MediaContentDirectionHasSend(video_desc->direction());
1153 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1154 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001155 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001156 }
deadbeefab9b2d12015-10-14 11:33:11 -07001157 }
1158
1159 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001160 if (data_desc) {
1161 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001162 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001163 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001164 }
1165 }
1166
1167 // Iterate new_streams and notify the observer about new MediaStreams.
1168 for (size_t i = 0; i < new_streams->count(); ++i) {
1169 MediaStreamInterface* new_stream = new_streams->at(i);
1170 stats_->AddStream(new_stream);
1171 observer_->OnAddStream(new_stream);
1172 }
1173
deadbeefbda7e0b2015-12-08 17:13:40 -08001174 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001175
1176 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1177 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001178}
1179
deadbeefa67696b2015-09-29 11:56:26 -07001180bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001181 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001182 if (port_allocator_) {
1183 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1184 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1185 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1186 return false;
1187 }
1188
deadbeef653b8e02015-11-11 12:55:10 -08001189 cricket::ServerAddresses cricket_stuns;
1190 std::vector<cricket::RelayServerConfig> cricket_turns;
1191 ConvertToCricketIceServers(stuns, turns, &cricket_stuns, &cricket_turns);
1192 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001193 }
honghaiz1f429e32015-09-28 07:57:34 -07001194 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001195 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001196}
1197
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001198bool PeerConnection::AddIceCandidate(
1199 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001200 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201 return session_->ProcessIceMessage(ice_candidate);
1202}
1203
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001204void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001205 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001206 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001207
1208 if (session_) {
1209 session_->set_metrics_observer(uma_observer_);
1210 }
1211
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001212 // Send information about IPv4/IPv6 status.
1213 if (uma_observer_ && port_allocator_) {
1214 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001215 uma_observer_->IncrementEnumCounter(
1216 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1217 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001218 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001219 uma_observer_->IncrementEnumCounter(
1220 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1221 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001222 }
1223 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001224}
1225
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001226const SessionDescriptionInterface* PeerConnection::local_description() const {
1227 return session_->local_description();
1228}
1229
1230const SessionDescriptionInterface* PeerConnection::remote_description() const {
1231 return session_->remote_description();
1232}
1233
1234void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001235 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236 // Update stats here so that we have the most recent stats for tracks and
1237 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001238 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239
deadbeefd59daf82015-10-14 15:02:44 -07001240 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241}
1242
deadbeefd59daf82015-10-14 15:02:44 -07001243void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1244 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001246 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001248 break;
deadbeefd59daf82015-10-14 15:02:44 -07001249 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1251 break;
deadbeefd59daf82015-10-14 15:02:44 -07001252 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001253 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1254 break;
deadbeefd59daf82015-10-14 15:02:44 -07001255 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1257 break;
deadbeefd59daf82015-10-14 15:02:44 -07001258 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1260 break;
deadbeefd59daf82015-10-14 15:02:44 -07001261 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001262 ChangeSignalingState(PeerConnectionInterface::kStable);
1263 break;
deadbeefd59daf82015-10-14 15:02:44 -07001264 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265 ChangeSignalingState(PeerConnectionInterface::kClosed);
1266 break;
1267 default:
1268 break;
1269 }
1270}
1271
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001272void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1275 SetSessionDescriptionMsg* param =
1276 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1277 param->observer->OnSuccess();
1278 delete param;
1279 break;
1280 }
1281 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1282 SetSessionDescriptionMsg* param =
1283 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1284 param->observer->OnFailure(param->error);
1285 delete param;
1286 break;
1287 }
deadbeefab9b2d12015-10-14 11:33:11 -07001288 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1289 CreateSessionDescriptionMsg* param =
1290 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1291 param->observer->OnFailure(param->error);
1292 delete param;
1293 break;
1294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 case MSG_GETSTATS: {
1296 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001297 StatsReports reports;
1298 stats_->GetStats(param->track, &reports);
1299 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300 delete param;
1301 break;
1302 }
deadbeefbd292462015-12-14 18:15:29 -08001303 case MSG_FREE_DATACHANNELS: {
1304 sctp_data_channels_to_free_.clear();
1305 break;
1306 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001308 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 break;
1310 }
1311}
1312
deadbeefab9b2d12015-10-14 11:33:11 -07001313void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1314 AudioTrackInterface* audio_track,
1315 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001316 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317}
1318
deadbeefab9b2d12015-10-14 11:33:11 -07001319void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1320 VideoTrackInterface* video_track,
1321 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001322 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323}
1324
deadbeef70ab1a12015-09-28 16:53:55 -07001325// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1326// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001327void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1328 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001329 auto it = FindReceiverForTrack(audio_track);
1330 if (it == receivers_.end()) {
1331 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1332 << " doesn't exist.";
1333 } else {
1334 (*it)->Stop();
1335 receivers_.erase(it);
1336 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337}
1338
deadbeefab9b2d12015-10-14 11:33:11 -07001339void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1340 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001341 auto it = FindReceiverForTrack(video_track);
1342 if (it == receivers_.end()) {
1343 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1344 << " doesn't exist.";
1345 } else {
1346 (*it)->Stop();
1347 receivers_.erase(it);
1348 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349}
deadbeef70ab1a12015-09-28 16:53:55 -07001350
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351void PeerConnection::OnIceConnectionChange(
1352 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001353 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001354 // After transitioning to "closed", ignore any additional states from
1355 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001356 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001357 return;
1358 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001360 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361}
1362
1363void PeerConnection::OnIceGatheringChange(
1364 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001365 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 if (IsClosed()) {
1367 return;
1368 }
1369 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001370 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371}
1372
1373void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001374 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001375 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376}
1377
1378void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001379 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001380 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381}
1382
Peter Thatcher54360512015-07-08 11:08:35 -07001383void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001384 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001385 observer_->OnIceConnectionReceivingChange(receiving);
1386}
1387
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388void PeerConnection::ChangeSignalingState(
1389 PeerConnectionInterface::SignalingState signaling_state) {
1390 signaling_state_ = signaling_state;
1391 if (signaling_state == kClosed) {
1392 ice_connection_state_ = kIceConnectionClosed;
1393 observer_->OnIceConnectionChange(ice_connection_state_);
1394 if (ice_gathering_state_ != kIceGatheringComplete) {
1395 ice_gathering_state_ = kIceGatheringComplete;
1396 observer_->OnIceGatheringChange(ice_gathering_state_);
1397 }
1398 }
1399 observer_->OnSignalingChange(signaling_state_);
1400 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1401}
1402
deadbeefeb459812015-12-15 19:24:43 -08001403void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1404 MediaStreamInterface* stream) {
1405 auto sender = FindSenderForTrack(track);
1406 if (sender != senders_.end()) {
1407 // We already have a sender for this track, so just change the stream_id
1408 // so that it's correct in the next call to CreateOffer.
1409 (*sender)->set_stream_id(stream->label());
1410 return;
1411 }
1412
1413 // Normal case; we've never seen this track before.
1414 AudioRtpSender* new_sender =
1415 new AudioRtpSender(track, stream->label(), session_.get(), stats_.get());
1416 senders_.push_back(new_sender);
1417 // If the sender has already been configured in SDP, we call SetSsrc,
1418 // which will connect the sender to the underlying transport. This can
1419 // occur if a local session description that contains the ID of the sender
1420 // is set before AddStream is called. It can also occur if the local
1421 // session description is not changed and RemoveStream is called, and
1422 // later AddStream is called again with the same stream.
1423 const TrackInfo* track_info =
1424 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1425 if (track_info) {
1426 new_sender->SetSsrc(track_info->ssrc);
1427 }
1428}
1429
1430// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1431// indefinitely, when we have unified plan SDP.
1432void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1433 MediaStreamInterface* stream) {
1434 auto sender = FindSenderForTrack(track);
1435 if (sender == senders_.end()) {
1436 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1437 << " doesn't exist.";
1438 return;
1439 }
1440 (*sender)->Stop();
1441 senders_.erase(sender);
1442}
1443
1444void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1445 MediaStreamInterface* stream) {
1446 auto sender = FindSenderForTrack(track);
1447 if (sender != senders_.end()) {
1448 // We already have a sender for this track, so just change the stream_id
1449 // so that it's correct in the next call to CreateOffer.
1450 (*sender)->set_stream_id(stream->label());
1451 return;
1452 }
1453
1454 // Normal case; we've never seen this track before.
1455 VideoRtpSender* new_sender =
1456 new VideoRtpSender(track, stream->label(), session_.get());
1457 senders_.push_back(new_sender);
1458 const TrackInfo* track_info =
1459 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1460 if (track_info) {
1461 new_sender->SetSsrc(track_info->ssrc);
1462 }
1463}
1464
1465void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1466 MediaStreamInterface* stream) {
1467 auto sender = FindSenderForTrack(track);
1468 if (sender == senders_.end()) {
1469 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1470 << " doesn't exist.";
1471 return;
1472 }
1473 (*sender)->Stop();
1474 senders_.erase(sender);
1475}
1476
deadbeefab9b2d12015-10-14 11:33:11 -07001477void PeerConnection::PostSetSessionDescriptionFailure(
1478 SetSessionDescriptionObserver* observer,
1479 const std::string& error) {
1480 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1481 msg->error = error;
1482 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1483}
1484
1485void PeerConnection::PostCreateSessionDescriptionFailure(
1486 CreateSessionDescriptionObserver* observer,
1487 const std::string& error) {
1488 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1489 msg->error = error;
1490 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1491}
1492
1493bool PeerConnection::GetOptionsForOffer(
1494 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1495 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001496 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1497 return false;
1498 }
1499
deadbeeffac06552015-11-25 11:26:01 -08001500 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001501 // Offer to receive audio/video if the constraint is not set and there are
1502 // send streams, or we're currently receiving.
1503 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1504 session_options->recv_audio =
1505 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1506 !remote_audio_tracks_.empty();
1507 }
1508 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1509 session_options->recv_video =
1510 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1511 !remote_video_tracks_.empty();
1512 }
1513 session_options->bundle_enabled =
1514 session_options->bundle_enabled &&
1515 (session_options->has_audio() || session_options->has_video() ||
1516 session_options->has_data());
1517
deadbeefab9b2d12015-10-14 11:33:11 -07001518 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1519 session_options->data_channel_type = cricket::DCT_SCTP;
1520 }
1521 return true;
1522}
1523
1524bool PeerConnection::GetOptionsForAnswer(
1525 const MediaConstraintsInterface* constraints,
1526 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001527 session_options->recv_audio = false;
1528 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001529 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1530 return false;
1531 }
1532
deadbeeffac06552015-11-25 11:26:01 -08001533 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001534 session_options->bundle_enabled =
1535 session_options->bundle_enabled &&
1536 (session_options->has_audio() || session_options->has_video() ||
1537 session_options->has_data());
1538
deadbeefab9b2d12015-10-14 11:33:11 -07001539 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1540 // are not signaled in the SDP so does not go through that path and must be
1541 // handled here.
1542 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1543 session_options->data_channel_type = cricket::DCT_SCTP;
1544 }
1545 return true;
1546}
1547
deadbeeffaac4972015-11-12 15:33:07 -08001548void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1549 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001550 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1551 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001552}
1553
deadbeefab9b2d12015-10-14 11:33:11 -07001554void PeerConnection::UpdateRemoteStreamsList(
1555 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001556 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001557 cricket::MediaType media_type,
1558 StreamCollection* new_streams) {
1559 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1560
1561 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001562 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001563 auto track_it = current_tracks->begin();
1564 while (track_it != current_tracks->end()) {
1565 const TrackInfo& info = *track_it;
1566 const cricket::StreamParams* params =
1567 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001568 bool track_exists = params && params->id == info.track_id;
1569 // If this is a default track, and we still need it, don't remove it.
1570 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1571 track_exists) {
1572 ++track_it;
1573 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001574 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1575 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001576 }
1577 }
1578
1579 // Find new and active tracks.
1580 for (const cricket::StreamParams& params : streams) {
1581 // The sync_label is the MediaStream label and the |stream.id| is the
1582 // track id.
1583 const std::string& stream_label = params.sync_label;
1584 const std::string& track_id = params.id;
1585 uint32_t ssrc = params.first_ssrc();
1586
1587 rtc::scoped_refptr<MediaStreamInterface> stream =
1588 remote_streams_->find(stream_label);
1589 if (!stream) {
1590 // This is a new MediaStream. Create a new remote MediaStream.
1591 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1592 remote_streams_->AddStream(stream);
1593 new_streams->AddStream(stream);
1594 }
1595
1596 const TrackInfo* track_info =
1597 FindTrackInfo(*current_tracks, stream_label, track_id);
1598 if (!track_info) {
1599 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1600 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1601 }
1602 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001603
1604 // Add default track if necessary.
1605 if (default_track_needed) {
1606 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1607 remote_streams_->find(kDefaultStreamLabel);
1608 if (!default_stream) {
1609 // Create the new default MediaStream.
1610 default_stream =
1611 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1612 remote_streams_->AddStream(default_stream);
1613 new_streams->AddStream(default_stream);
1614 }
1615 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1616 ? kDefaultAudioTrackLabel
1617 : kDefaultVideoTrackLabel;
1618 const TrackInfo* default_track_info =
1619 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1620 if (!default_track_info) {
1621 current_tracks->push_back(
1622 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1623 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1624 }
1625 }
deadbeefab9b2d12015-10-14 11:33:11 -07001626}
1627
1628void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1629 const std::string& track_id,
1630 uint32_t ssrc,
1631 cricket::MediaType media_type) {
1632 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1633
1634 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Tommif888bb52015-12-12 01:37:01 +01001635 AudioTrackInterface* audio_track = remote_stream_factory_->AddAudioTrack(
1636 ssrc, session_.get(), stream, track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001637 CreateAudioReceiver(stream, audio_track, ssrc);
1638 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1639 VideoTrackInterface* video_track =
1640 remote_stream_factory_->AddVideoTrack(stream, track_id);
1641 CreateVideoReceiver(stream, video_track, ssrc);
1642 } else {
1643 RTC_DCHECK(false && "Invalid media type");
1644 }
1645}
1646
1647void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1648 const std::string& track_id,
1649 cricket::MediaType media_type) {
1650 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1651
1652 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1653 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1654 stream->FindAudioTrack(track_id);
1655 if (audio_track) {
1656 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1657 stream->RemoveTrack(audio_track);
1658 DestroyAudioReceiver(stream, audio_track);
1659 }
1660 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1661 rtc::scoped_refptr<VideoTrackInterface> video_track =
1662 stream->FindVideoTrack(track_id);
1663 if (video_track) {
1664 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1665 stream->RemoveTrack(video_track);
1666 DestroyVideoReceiver(stream, video_track);
1667 }
1668 } else {
1669 ASSERT(false && "Invalid media type");
1670 }
1671}
1672
1673void PeerConnection::UpdateEndedRemoteMediaStreams() {
1674 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1675 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1676 MediaStreamInterface* stream = remote_streams_->at(i);
1677 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1678 streams_to_remove.push_back(stream);
1679 }
1680 }
1681
1682 for (const auto& stream : streams_to_remove) {
1683 remote_streams_->RemoveStream(stream);
1684 observer_->OnRemoveStream(stream);
1685 }
1686}
1687
deadbeefab9b2d12015-10-14 11:33:11 -07001688void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1689 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1690 for (TrackInfos::iterator track_it = current_tracks->begin();
1691 track_it != current_tracks->end(); ++track_it) {
1692 const TrackInfo& info = *track_it;
1693 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1694 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1695 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1696 // There's no guarantee the track is still available, e.g. the track may
1697 // have been removed from the stream by javascript.
1698 if (track) {
1699 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1700 }
1701 }
1702 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1703 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1704 // There's no guarantee the track is still available, e.g. the track may
1705 // have been removed from the stream by javascript.
1706 if (track) {
1707 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1708 }
1709 }
1710 }
1711}
1712
1713void PeerConnection::UpdateLocalTracks(
1714 const std::vector<cricket::StreamParams>& streams,
1715 cricket::MediaType media_type) {
1716 TrackInfos* current_tracks = GetLocalTracks(media_type);
1717
1718 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1719 // don't match the new StreamParam.
1720 TrackInfos::iterator track_it = current_tracks->begin();
1721 while (track_it != current_tracks->end()) {
1722 const TrackInfo& info = *track_it;
1723 const cricket::StreamParams* params =
1724 cricket::GetStreamBySsrc(streams, info.ssrc);
1725 if (!params || params->id != info.track_id ||
1726 params->sync_label != info.stream_label) {
1727 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1728 media_type);
1729 track_it = current_tracks->erase(track_it);
1730 } else {
1731 ++track_it;
1732 }
1733 }
1734
1735 // Find new and active tracks.
1736 for (const cricket::StreamParams& params : streams) {
1737 // The sync_label is the MediaStream label and the |stream.id| is the
1738 // track id.
1739 const std::string& stream_label = params.sync_label;
1740 const std::string& track_id = params.id;
1741 uint32_t ssrc = params.first_ssrc();
1742 const TrackInfo* track_info =
1743 FindTrackInfo(*current_tracks, stream_label, track_id);
1744 if (!track_info) {
1745 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1746 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1747 }
1748 }
1749}
1750
1751void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1752 const std::string& track_id,
1753 uint32_t ssrc,
1754 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001755 RtpSenderInterface* sender = FindSenderById(track_id);
1756 if (!sender) {
1757 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1758 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001759 return;
1760 }
1761
deadbeeffac06552015-11-25 11:26:01 -08001762 if (sender->media_type() != media_type) {
1763 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1764 << " description with an unexpected media type.";
1765 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001766 }
deadbeeffac06552015-11-25 11:26:01 -08001767
1768 sender->set_stream_id(stream_label);
1769 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001770}
1771
1772void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1773 const std::string& track_id,
1774 uint32_t ssrc,
1775 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001776 RtpSenderInterface* sender = FindSenderById(track_id);
1777 if (!sender) {
1778 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001779 // SessionDescriptions has been renegotiated.
1780 return;
1781 }
deadbeeffac06552015-11-25 11:26:01 -08001782
1783 // A sender has been removed from the SessionDescription but it's still
1784 // associated with the PeerConnection. This only occurs if the SDP doesn't
1785 // match with the calls to CreateSender, AddStream and RemoveStream.
1786 if (sender->media_type() != media_type) {
1787 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1788 << " description with an unexpected media type.";
1789 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001790 }
deadbeeffac06552015-11-25 11:26:01 -08001791
1792 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001793}
1794
1795void PeerConnection::UpdateLocalRtpDataChannels(
1796 const cricket::StreamParamsVec& streams) {
1797 std::vector<std::string> existing_channels;
1798
1799 // Find new and active data channels.
1800 for (const cricket::StreamParams& params : streams) {
1801 // |it->sync_label| is actually the data channel label. The reason is that
1802 // we use the same naming of data channels as we do for
1803 // MediaStreams and Tracks.
1804 // For MediaStreams, the sync_label is the MediaStream label and the
1805 // track label is the same as |streamid|.
1806 const std::string& channel_label = params.sync_label;
1807 auto data_channel_it = rtp_data_channels_.find(channel_label);
1808 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1809 continue;
1810 }
1811 // Set the SSRC the data channel should use for sending.
1812 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1813 existing_channels.push_back(data_channel_it->first);
1814 }
1815
1816 UpdateClosingRtpDataChannels(existing_channels, true);
1817}
1818
1819void PeerConnection::UpdateRemoteRtpDataChannels(
1820 const cricket::StreamParamsVec& streams) {
1821 std::vector<std::string> existing_channels;
1822
1823 // Find new and active data channels.
1824 for (const cricket::StreamParams& params : streams) {
1825 // The data channel label is either the mslabel or the SSRC if the mslabel
1826 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1827 std::string label = params.sync_label.empty()
1828 ? rtc::ToString(params.first_ssrc())
1829 : params.sync_label;
1830 auto data_channel_it = rtp_data_channels_.find(label);
1831 if (data_channel_it == rtp_data_channels_.end()) {
1832 // This is a new data channel.
1833 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1834 } else {
1835 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1836 }
1837 existing_channels.push_back(label);
1838 }
1839
1840 UpdateClosingRtpDataChannels(existing_channels, false);
1841}
1842
1843void PeerConnection::UpdateClosingRtpDataChannels(
1844 const std::vector<std::string>& active_channels,
1845 bool is_local_update) {
1846 auto it = rtp_data_channels_.begin();
1847 while (it != rtp_data_channels_.end()) {
1848 DataChannel* data_channel = it->second;
1849 if (std::find(active_channels.begin(), active_channels.end(),
1850 data_channel->label()) != active_channels.end()) {
1851 ++it;
1852 continue;
1853 }
1854
1855 if (is_local_update) {
1856 data_channel->SetSendSsrc(0);
1857 } else {
1858 data_channel->RemotePeerRequestClose();
1859 }
1860
1861 if (data_channel->state() == DataChannel::kClosed) {
1862 rtp_data_channels_.erase(it);
1863 it = rtp_data_channels_.begin();
1864 } else {
1865 ++it;
1866 }
1867 }
1868}
1869
1870void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1871 uint32_t remote_ssrc) {
1872 rtc::scoped_refptr<DataChannel> channel(
1873 InternalCreateDataChannel(label, nullptr));
1874 if (!channel.get()) {
1875 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1876 << "CreateDataChannel failed.";
1877 return;
1878 }
1879 channel->SetReceiveSsrc(remote_ssrc);
1880 observer_->OnDataChannel(
1881 DataChannelProxy::Create(signaling_thread(), channel));
1882}
1883
1884rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1885 const std::string& label,
1886 const InternalDataChannelInit* config) {
1887 if (IsClosed()) {
1888 return nullptr;
1889 }
1890 if (session_->data_channel_type() == cricket::DCT_NONE) {
1891 LOG(LS_ERROR)
1892 << "InternalCreateDataChannel: Data is not supported in this call.";
1893 return nullptr;
1894 }
1895 InternalDataChannelInit new_config =
1896 config ? (*config) : InternalDataChannelInit();
1897 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1898 if (new_config.id < 0) {
1899 rtc::SSLRole role;
1900 if (session_->GetSslRole(&role) &&
1901 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1902 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1903 return nullptr;
1904 }
1905 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1906 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1907 << "because the id is already in use or out of range.";
1908 return nullptr;
1909 }
1910 }
1911
1912 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1913 session_.get(), session_->data_channel_type(), label, new_config));
1914 if (!channel) {
1915 sid_allocator_.ReleaseSid(new_config.id);
1916 return nullptr;
1917 }
1918
1919 if (channel->data_channel_type() == cricket::DCT_RTP) {
1920 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1921 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1922 << " already exists.";
1923 return nullptr;
1924 }
1925 rtp_data_channels_[channel->label()] = channel;
1926 } else {
1927 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1928 sctp_data_channels_.push_back(channel);
1929 channel->SignalClosed.connect(this,
1930 &PeerConnection::OnSctpDataChannelClosed);
1931 }
1932
1933 return channel;
1934}
1935
1936bool PeerConnection::HasDataChannels() const {
1937 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1938}
1939
1940void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1941 for (const auto& channel : sctp_data_channels_) {
1942 if (channel->id() < 0) {
1943 int sid;
1944 if (!sid_allocator_.AllocateSid(role, &sid)) {
1945 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1946 continue;
1947 }
1948 channel->SetSctpSid(sid);
1949 }
1950 }
1951}
1952
1953void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08001954 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07001955 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1956 ++it) {
1957 if (it->get() == channel) {
1958 if (channel->id() >= 0) {
1959 sid_allocator_.ReleaseSid(channel->id());
1960 }
deadbeefbd292462015-12-14 18:15:29 -08001961 // Since this method is triggered by a signal from the DataChannel,
1962 // we can't free it directly here; we need to free it asynchronously.
1963 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07001964 sctp_data_channels_.erase(it);
deadbeefbd292462015-12-14 18:15:29 -08001965 signaling_thread()->Post(this, MSG_FREE_DATACHANNELS, nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07001966 return;
1967 }
1968 }
1969}
1970
1971void PeerConnection::OnVoiceChannelDestroyed() {
1972 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1973}
1974
1975void PeerConnection::OnVideoChannelDestroyed() {
1976 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1977}
1978
1979void PeerConnection::OnDataChannelCreated() {
1980 for (const auto& channel : sctp_data_channels_) {
1981 channel->OnTransportChannelCreated();
1982 }
1983}
1984
1985void PeerConnection::OnDataChannelDestroyed() {
1986 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1987 // DataChannel may callback to us and try to modify the list.
1988 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1989 temp_rtp_dcs.swap(rtp_data_channels_);
1990 for (const auto& kv : temp_rtp_dcs) {
1991 kv.second->OnTransportChannelDestroyed();
1992 }
1993
1994 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1995 temp_sctp_dcs.swap(sctp_data_channels_);
1996 for (const auto& channel : temp_sctp_dcs) {
1997 channel->OnTransportChannelDestroyed();
1998 }
1999}
2000
2001void PeerConnection::OnDataChannelOpenMessage(
2002 const std::string& label,
2003 const InternalDataChannelInit& config) {
2004 rtc::scoped_refptr<DataChannel> channel(
2005 InternalCreateDataChannel(label, &config));
2006 if (!channel.get()) {
2007 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2008 return;
2009 }
2010
2011 observer_->OnDataChannel(
2012 DataChannelProxy::Create(signaling_thread(), channel));
2013}
2014
deadbeeffac06552015-11-25 11:26:01 -08002015RtpSenderInterface* PeerConnection::FindSenderById(const std::string& id) {
2016 auto it =
2017 std::find_if(senders_.begin(), senders_.end(),
2018 [id](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
2019 return sender->id() == id;
2020 });
2021 return it != senders_.end() ? it->get() : nullptr;
2022}
2023
deadbeef70ab1a12015-09-28 16:53:55 -07002024std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
2025PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2026 return std::find_if(
2027 senders_.begin(), senders_.end(),
2028 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
2029 return sender->track() == track;
2030 });
2031}
2032
2033std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
2034PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
2035 return std::find_if(
2036 receivers_.begin(), receivers_.end(),
2037 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
2038 return receiver->track() == track;
2039 });
2040}
2041
deadbeefab9b2d12015-10-14 11:33:11 -07002042PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2043 cricket::MediaType media_type) {
2044 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2045 media_type == cricket::MEDIA_TYPE_VIDEO);
2046 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2047 : &remote_video_tracks_;
2048}
2049
2050PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2051 cricket::MediaType media_type) {
2052 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2053 media_type == cricket::MEDIA_TYPE_VIDEO);
2054 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2055 : &local_video_tracks_;
2056}
2057
2058const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2059 const PeerConnection::TrackInfos& infos,
2060 const std::string& stream_label,
2061 const std::string track_id) const {
2062 for (const TrackInfo& track_info : infos) {
2063 if (track_info.stream_label == stream_label &&
2064 track_info.track_id == track_id) {
2065 return &track_info;
2066 }
2067 }
2068 return nullptr;
2069}
2070
2071DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2072 for (const auto& channel : sctp_data_channels_) {
2073 if (channel->id() == sid) {
2074 return channel;
2075 }
2076 }
2077 return nullptr;
2078}
2079
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002080} // namespace webrtc