blob: 933dc83c25642278d49a9491c2818a57f74fd217 [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
30#include <vector>
deadbeef0a6c4ca2015-10-06 11:38:28 -070031#include <cctype> // for isdigit
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032
deadbeefab9b2d12015-10-14 11:33:11 -070033#include "talk/app/webrtc/audiotrack.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034#include "talk/app/webrtc/dtmfsender.h"
35#include "talk/app/webrtc/jsepicecandidate.h"
36#include "talk/app/webrtc/jsepsessiondescription.h"
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +000037#include "talk/app/webrtc/mediaconstraintsinterface.h"
deadbeefab9b2d12015-10-14 11:33:11 -070038#include "talk/app/webrtc/mediastream.h"
39#include "talk/app/webrtc/mediastreamproxy.h"
40#include "talk/app/webrtc/mediastreamtrackproxy.h"
41#include "talk/app/webrtc/remoteaudiosource.h"
42#include "talk/app/webrtc/remotevideocapturer.h"
deadbeef70ab1a12015-09-28 16:53:55 -070043#include "talk/app/webrtc/rtpreceiver.h"
44#include "talk/app/webrtc/rtpsender.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045#include "talk/app/webrtc/streamcollection.h"
deadbeefab9b2d12015-10-14 11:33:11 -070046#include "talk/app/webrtc/videosource.h"
47#include "talk/app/webrtc/videotrack.h"
48#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049#include "talk/session/media/channelmanager.h"
tfarina5237aaf2015-11-10 23:44:30 -080050#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000051#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070053#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010054#include "webrtc/base/trace_event.h"
tfarina5237aaf2015-11-10 23:44:30 -080055#include "webrtc/p2p/client/basicportallocator.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010056#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
58namespace {
59
deadbeefab9b2d12015-10-14 11:33:11 -070060using webrtc::DataChannel;
61using webrtc::MediaConstraintsInterface;
62using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063using webrtc::PeerConnectionInterface;
deadbeeffac06552015-11-25 11:26:01 -080064using webrtc::RtpSenderInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070065using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070066using webrtc::StunConfigurations;
67using webrtc::TurnConfigurations;
68typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
69 StunConfiguration;
70typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
71 TurnConfiguration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
deadbeefab9b2d12015-10-14 11:33:11 -070073static const char kDefaultStreamLabel[] = "default";
74static const char kDefaultAudioTrackLabel[] = "defaulta0";
75static const char kDefaultVideoTrackLabel[] = "defaultv0";
76
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077// The min number of tokens must present in Turn host uri.
78// e.g. user@turn.example.org
79static const size_t kTurnHostTokensNum = 2;
80// Number of tokens must be preset when TURN uri has transport param.
81static const size_t kTurnTransportTokensNum = 2;
82// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000083static const int kDefaultStunPort = 3478;
84static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000086static const char kUdpTransportType[] = "udp";
87static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
89// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070090static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091
deadbeef0a6c4ca2015-10-06 11:38:28 -070092// NOTE: A loop below assumes that the first value of this enum is 0 and all
93// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070095 STUN = 0, // Indicates a STUN server.
96 STUNS, // Indicates a STUN server used with a TLS session.
97 TURN, // Indicates a TURN server
98 TURNS, // Indicates a TURN server used with a TLS session.
99 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100};
tfarina5237aaf2015-11-10 23:44:30 -0800101static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -0700102 "kValidIceServiceTypes must have as many strings as ServiceType "
103 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104
105enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 MSG_GETSTATS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110};
111
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000112struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000113 explicit SetSessionDescriptionMsg(
114 webrtc::SetSessionDescriptionObserver* observer)
115 : observer(observer) {
116 }
117
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000118 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119 std::string error;
120};
121
deadbeefab9b2d12015-10-14 11:33:11 -0700122struct CreateSessionDescriptionMsg : public rtc::MessageData {
123 explicit CreateSessionDescriptionMsg(
124 webrtc::CreateSessionDescriptionObserver* observer)
125 : observer(observer) {}
126
127 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
128 std::string error;
129};
130
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000131struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000132 GetStatsMsg(webrtc::StatsObserver* observer,
133 webrtc::MediaStreamTrackInterface* track)
134 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000136 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000137 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138};
139
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000140// |in_str| should be of format
141// stunURI = scheme ":" stun-host [ ":" stun-port ]
142// scheme = "stun" / "stuns"
143// stun-host = IP-literal / IPv4address / reg-name
144// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700145//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000146// draft-petithuguenin-behave-turn-uris-01
147// turnURI = scheme ":" turn-host [ ":" turn-port ]
148// turn-host = username@IP-literal / IPv4address / reg-name
149bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
150 ServiceType* service_type,
151 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200152 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700153 if (colonpos == std::string::npos) {
154 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000155 return false;
156 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700157 if ((colonpos + 1) == in_str.length()) {
158 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
159 return false;
160 }
161 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800162 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700163 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000164 *service_type = static_cast<ServiceType>(i);
165 break;
166 }
167 }
168 if (*service_type == INVALID) {
169 return false;
170 }
171 *hostname = in_str.substr(colonpos + 1, std::string::npos);
172 return true;
173}
174
deadbeef0a6c4ca2015-10-06 11:38:28 -0700175bool ParsePort(const std::string& in_str, int* port) {
176 // Make sure port only contains digits. FromString doesn't check this.
177 for (const char& c : in_str) {
178 if (!std::isdigit(c)) {
179 return false;
180 }
181 }
182 return rtc::FromString(in_str, port);
183}
184
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000185// This method parses IPv6 and IPv4 literal strings, along with hostnames in
186// standard hostname:port format.
187// Consider following formats as correct.
188// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700189// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000190bool ParseHostnameAndPortFromString(const std::string& in_str,
191 std::string* host,
192 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700193 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000194 if (in_str.at(0) == '[') {
195 std::string::size_type closebracket = in_str.rfind(']');
196 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000197 std::string::size_type colonpos = in_str.find(':', closebracket);
198 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700199 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
200 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000201 return false;
202 }
203 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700204 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000205 } else {
206 return false;
207 }
208 } else {
209 std::string::size_type colonpos = in_str.find(':');
210 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700211 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000212 return false;
213 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700214 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000215 } else {
216 *host = in_str;
217 }
218 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700219 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000220}
221
deadbeef0a6c4ca2015-10-06 11:38:28 -0700222// Adds a StunConfiguration or TurnConfiguration to the appropriate list,
223// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200224bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
225 const std::string& url,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700226 StunConfigurations* stun_config,
227 TurnConfigurations* turn_config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000228 // draft-nandakumar-rtcweb-stun-uri-01
229 // stunURI = scheme ":" stun-host [ ":" stun-port ]
230 // scheme = "stun" / "stuns"
231 // stun-host = IP-literal / IPv4address / reg-name
232 // stun-port = *DIGIT
233
234 // draft-petithuguenin-behave-turn-uris-01
235 // turnURI = scheme ":" turn-host [ ":" turn-port ]
236 // [ "?transport=" transport ]
237 // scheme = "turn" / "turns"
238 // transport = "udp" / "tcp" / transport-ext
239 // transport-ext = 1*unreserved
240 // turn-host = IP-literal / IPv4address / reg-name
241 // turn-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700242 RTC_DCHECK(stun_config != nullptr);
243 RTC_DCHECK(turn_config != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200244 std::vector<std::string> tokens;
245 std::string turn_transport_type = kUdpTransportType;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700246 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200247 rtc::tokenize(url, '?', &tokens);
248 std::string uri_without_transport = tokens[0];
249 // Let's look into transport= param, if it exists.
250 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
251 std::string uri_transport_param = tokens[1];
252 rtc::tokenize(uri_transport_param, '=', &tokens);
253 if (tokens[0] == kTransport) {
254 // As per above grammar transport param will be consist of lower case
255 // letters.
256 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
257 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700258 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 turn_transport_type = tokens[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200262 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200264 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200266 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
267 &service_type,
268 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
270 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200271 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000272
deadbeef0a6c4ca2015-10-06 11:38:28 -0700273 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
274 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200275
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200276 // Let's break hostname.
277 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700278 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
279
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200280 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700281 if (tokens.size() > kTurnHostTokensNum) {
282 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
283 return false;
284 }
285 if (tokens.size() == kTurnHostTokensNum) {
286 if (tokens[0].empty() || tokens[1].empty()) {
287 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
288 return false;
289 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200290 username.assign(rtc::s_url_decode(tokens[0]));
291 hoststring = tokens[1];
292 } else {
293 hoststring = tokens[0];
294 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000295
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200296 int port = kDefaultStunPort;
297 if (service_type == TURNS) {
298 port = kDefaultStunTlsPort;
299 turn_transport_type = kTcpTransportType;
300 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000301
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200302 std::string address;
303 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700304 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
305 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200306 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000307
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200308 if (port <= 0 || port > 0xffff) {
309 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700310 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000312
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200313 switch (service_type) {
314 case STUN:
315 case STUNS:
316 stun_config->push_back(StunConfiguration(address, port));
317 break;
318 case TURN:
319 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200320 bool secure = (service_type == TURNS);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200321 turn_config->push_back(TurnConfiguration(address, port,
322 username,
323 server.password,
324 turn_transport_type,
325 secure));
326 break;
327 }
328 case INVALID:
329 default:
330 LOG(WARNING) << "Configuration not supported: " << url;
331 return false;
332 }
333 return true;
334}
335
deadbeef653b8e02015-11-11 12:55:10 -0800336void ConvertToCricketIceServers(
337 const std::vector<StunConfiguration>& stuns,
338 const std::vector<TurnConfiguration>& turns,
339 cricket::ServerAddresses* cricket_stuns,
340 std::vector<cricket::RelayServerConfig>* cricket_turns) {
341 RTC_DCHECK(cricket_stuns && cricket_turns);
342 for (const StunConfiguration& stun : stuns) {
343 cricket_stuns->insert(stun.server);
344 }
345
346 int priority = static_cast<int>(turns.size() - 1);
347 for (const TurnConfiguration& turn : turns) {
348 cricket::RelayCredentials credentials(turn.username, turn.password);
349 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
350 cricket::ProtocolType protocol;
351 // Using VERIFY because ParseIceServers should have already caught an
352 // invalid transport type.
353 if (!VERIFY(
354 cricket::StringToProto(turn.transport_type.c_str(), &protocol))) {
355 LOG(LS_WARNING) << "Ignoring TURN server " << turn.server << ". "
356 << "Reason= Incorrect " << turn.transport_type
357 << " transport parameter.";
358 } else {
359 relay_server.ports.push_back(
360 cricket::ProtocolAddress(turn.server, protocol, turn.secure));
361 relay_server.credentials = credentials;
362 relay_server.priority = priority;
363 cricket_turns->push_back(relay_server);
364 }
365 // First in the list gets highest priority.
366 --priority;
367 }
368}
369
deadbeefab9b2d12015-10-14 11:33:11 -0700370// Check if we can send |new_stream| on a PeerConnection.
371bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
372 webrtc::MediaStreamInterface* new_stream) {
373 if (!new_stream || !current_streams) {
374 return false;
375 }
376 if (current_streams->find(new_stream->label()) != nullptr) {
377 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
378 << " is already added.";
379 return false;
380 }
381 return true;
382}
383
384bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
385 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
386}
387
deadbeef5e97fb52015-10-15 12:49:08 -0700388// If the direction is "recvonly" or "inactive", treat the description
389// as containing no streams.
390// See: https://code.google.com/p/webrtc/issues/detail?id=5054
391std::vector<cricket::StreamParams> GetActiveStreams(
392 const cricket::MediaContentDescription* desc) {
393 return MediaContentDirectionHasSend(desc->direction())
394 ? desc->streams()
395 : std::vector<cricket::StreamParams>();
396}
397
deadbeefab9b2d12015-10-14 11:33:11 -0700398bool IsValidOfferToReceiveMedia(int value) {
399 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
400 return (value >= Options::kUndefined) &&
401 (value <= Options::kMaxOfferToReceiveMedia);
402}
403
404// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800405void AddSendStreams(
406 cricket::MediaSessionOptions* session_options,
407 const std::vector<rtc::scoped_refptr<RtpSenderInterface>>& senders,
408 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
409 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700410 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800411 for (const auto& sender : senders) {
412 session_options->AddSendStream(sender->media_type(), sender->id(),
413 sender->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700414 }
415
416 // Check for data channels.
417 for (const auto& kv : rtp_data_channels) {
418 const DataChannel* channel = kv.second;
419 if (channel->state() == DataChannel::kConnecting ||
420 channel->state() == DataChannel::kOpen) {
421 // |streamid| and |sync_label| are both set to the DataChannel label
422 // here so they can be signaled the same way as MediaStreams and Tracks.
423 // For MediaStreams, the sync_label is the MediaStream label and the
424 // track label is the same as |streamid|.
425 const std::string& streamid = channel->label();
426 const std::string& sync_label = channel->label();
427 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
428 sync_label);
429 }
430 }
431}
432
deadbeef0a6c4ca2015-10-06 11:38:28 -0700433} // namespace
434
435namespace webrtc {
436
deadbeefab9b2d12015-10-14 11:33:11 -0700437// Factory class for creating remote MediaStreams and MediaStreamTracks.
438class RemoteMediaStreamFactory {
439 public:
440 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
441 cricket::ChannelManager* channel_manager)
442 : signaling_thread_(signaling_thread),
443 channel_manager_(channel_manager) {}
444
445 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
446 const std::string& stream_label) {
447 return MediaStreamProxy::Create(signaling_thread_,
448 MediaStream::Create(stream_label));
449 }
450
451 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
452 const std::string& track_id) {
453 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
454 stream, track_id, RemoteAudioSource::Create().get());
455 }
456
457 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
458 const std::string& track_id) {
459 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
460 stream, track_id,
461 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
462 nullptr)
463 .get());
464 }
465
466 private:
467 template <typename TI, typename T, typename TP, typename S>
468 TI* AddTrack(MediaStreamInterface* stream,
469 const std::string& track_id,
470 S* source) {
471 rtc::scoped_refptr<TI> track(
472 TP::Create(signaling_thread_, T::Create(track_id, source)));
473 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
474 if (stream->AddTrack(track)) {
475 return track;
476 }
477 return nullptr;
478 }
479
480 rtc::Thread* signaling_thread_;
481 cricket::ChannelManager* channel_manager_;
482};
483
484bool ConvertRtcOptionsForOffer(
485 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
486 cricket::MediaSessionOptions* session_options) {
487 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
488 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
489 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
490 return false;
491 }
492
deadbeefc80741f2015-10-22 13:14:45 -0700493 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700494 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
495 }
deadbeefc80741f2015-10-22 13:14:45 -0700496 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700497 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
498 }
499
500 session_options->vad_enabled = rtc_options.voice_activity_detection;
501 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700502 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700503
504 return true;
505}
506
507bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
508 cricket::MediaSessionOptions* session_options) {
509 bool value = false;
510 size_t mandatory_constraints_satisfied = 0;
511
512 // kOfferToReceiveAudio defaults to true according to spec.
513 if (!FindConstraint(constraints,
514 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
515 &mandatory_constraints_satisfied) ||
516 value) {
517 session_options->recv_audio = true;
518 }
519
520 // kOfferToReceiveVideo defaults to false according to spec. But
521 // if it is an answer and video is offered, we should still accept video
522 // per default.
523 value = false;
524 if (!FindConstraint(constraints,
525 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
526 &mandatory_constraints_satisfied) ||
527 value) {
528 session_options->recv_video = true;
529 }
530
531 if (FindConstraint(constraints,
532 MediaConstraintsInterface::kVoiceActivityDetection, &value,
533 &mandatory_constraints_satisfied)) {
534 session_options->vad_enabled = value;
535 }
536
537 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
538 &mandatory_constraints_satisfied)) {
539 session_options->bundle_enabled = value;
540 } else {
541 // kUseRtpMux defaults to true according to spec.
542 session_options->bundle_enabled = true;
543 }
deadbeefab9b2d12015-10-14 11:33:11 -0700544
545 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
546 &value, &mandatory_constraints_satisfied)) {
547 session_options->transport_options.ice_restart = value;
548 } else {
549 // kIceRestart defaults to false according to spec.
550 session_options->transport_options.ice_restart = false;
551 }
552
553 if (!constraints) {
554 return true;
555 }
556 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
557}
558
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200559bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700560 StunConfigurations* stun_config,
561 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200562 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
563 if (!server.urls.empty()) {
564 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200565 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700566 LOG(LS_ERROR) << "Empty uri.";
567 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200568 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200569 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
570 return false;
571 }
572 }
573 } else if (!server.uri.empty()) {
574 // Fallback to old .uri if new .urls isn't present.
575 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200577 }
578 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700579 LOG(LS_ERROR) << "Empty uri.";
580 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000581 }
582 }
583 return true;
584}
585
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586PeerConnection::PeerConnection(PeerConnectionFactory* factory)
587 : factory_(factory),
588 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000589 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590 signaling_state_(kStable),
591 ice_state_(kIceNew),
592 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700593 ice_gathering_state_(kIceGatheringNew),
594 local_streams_(StreamCollection::Create()),
595 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000596
597PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100598 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700599 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700600 // Need to detach RTP senders/receivers from WebRtcSession,
601 // since it's about to be destroyed.
602 for (const auto& sender : senders_) {
603 sender->Stop();
604 }
605 for (const auto& receiver : receivers_) {
606 receiver->Stop();
607 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608}
609
610bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000611 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000613 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200614 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000615 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700616 RTC_DCHECK(observer != nullptr);
617 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000618 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700619 }
deadbeef653b8e02015-11-11 12:55:10 -0800620
621 // This Initialize function parses ICE servers an extra time, but it will
622 // be removed once all PortAllocaotrs support SetIceServers.
623 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
624 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
625 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
626 return false;
627 }
628 rtc::scoped_ptr<cricket::PortAllocator> allocator(
629 allocator_factory->CreatePortAllocator(stun_config, turn_config));
630 return Initialize(configuration, constraints, allocator.Pass(),
631 dtls_identity_store.Pass(), observer);
632}
633
634bool PeerConnection::Initialize(
635 const PeerConnectionInterface::RTCConfiguration& configuration,
636 const MediaConstraintsInterface* constraints,
637 rtc::scoped_ptr<cricket::PortAllocator> allocator,
638 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
639 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100640 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800641 RTC_DCHECK(observer != nullptr);
642 if (!observer) {
643 return false;
644 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000645 observer_ = observer;
646
deadbeef653b8e02015-11-11 12:55:10 -0800647 port_allocator_ = allocator.Pass();
648
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000649 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
650 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000651 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000652 return false;
653 }
deadbeef653b8e02015-11-11 12:55:10 -0800654
655 cricket::ServerAddresses cricket_stuns;
656 std::vector<cricket::RelayServerConfig> cricket_turns;
657 ConvertToCricketIceServers(stun_config, turn_config, &cricket_stuns,
658 &cricket_turns);
659 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000660
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000661 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000662 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000663 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700664 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000665 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000666 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000667 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700668 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
669 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000670 if (!value) {
671 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000672 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000673 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000674 "Disabled") {
675 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000676 }
677
Jiayang Liucac1b382015-04-30 12:35:24 -0700678 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
679 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
680 LOG(LS_INFO) << "TCP candidates are disabled.";
681 }
682
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000683 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 // No step delay is used while allocating ports.
685 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
686
stefanc1aeaf02015-10-15 07:26:07 -0700687 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688
stefanc1aeaf02015-10-15 07:26:07 -0700689 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
690 factory_->signaling_thread(), media_controller_->channel_manager()));
691
692 session_.reset(
693 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
694 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700695 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696
697 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000698 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700699 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700701 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 // Register PeerConnection as receiver of local ice candidates.
704 // All the callbacks will be posted to the application from PeerConnection.
705 session_->RegisterIceObserver(this);
706 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700707 session_->SignalVoiceChannelDestroyed.connect(
708 this, &PeerConnection::OnVoiceChannelDestroyed);
709 session_->SignalVideoChannelDestroyed.connect(
710 this, &PeerConnection::OnVideoChannelDestroyed);
711 session_->SignalDataChannelCreated.connect(
712 this, &PeerConnection::OnDataChannelCreated);
713 session_->SignalDataChannelDestroyed.connect(
714 this, &PeerConnection::OnDataChannelDestroyed);
715 session_->SignalDataChannelOpenMessage.connect(
716 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717 return true;
718}
719
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000720rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700722 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723}
724
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000725rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700727 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728}
729
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000730bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100731 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732 if (IsClosed()) {
733 return false;
734 }
deadbeefab9b2d12015-10-14 11:33:11 -0700735 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 return false;
737 }
deadbeefab9b2d12015-10-14 11:33:11 -0700738
739 local_streams_->AddStream(local_stream);
740
deadbeefab9b2d12015-10-14 11:33:11 -0700741 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800742 auto sender = FindSenderForTrack(track.get());
743 if (sender == senders_.end()) {
744 // Normal case; we've never seen this track before.
745 AudioRtpSender* new_sender = new AudioRtpSender(
746 track.get(), local_stream->label(), session_.get(), stats_.get());
747 senders_.push_back(new_sender);
748 // If the sender has already been configured in SDP, we call SetSsrc,
749 // which will connect the sender to the underlying transport. This can
750 // occur if a local session description that contains the ID of the sender
751 // is set before AddStream is called. It can also occur if the local
752 // session description is not changed and RemoveStream is called, and
753 // later AddStream is called again with the same stream.
754 const TrackInfo* track_info = FindTrackInfo(
755 local_audio_tracks_, local_stream->label(), track->id());
756 if (track_info) {
757 new_sender->SetSsrc(track_info->ssrc);
758 }
759 } else {
760 // We already have a sender for this track, so just change the stream_id
761 // so that it's correct in the next call to CreateOffer.
762 (*sender)->set_stream_id(local_stream->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700763 }
764 }
765 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800766 auto sender = FindSenderForTrack(track.get());
767 if (sender == senders_.end()) {
768 // Normal case; we've never seen this track before.
769 VideoRtpSender* new_sender = new VideoRtpSender(
770 track.get(), local_stream->label(), session_.get());
771 senders_.push_back(new_sender);
772 const TrackInfo* track_info = FindTrackInfo(
773 local_video_tracks_, local_stream->label(), track->id());
774 if (track_info) {
775 new_sender->SetSsrc(track_info->ssrc);
776 }
777 } else {
778 // We already have a sender for this track, so just change the stream_id
779 // so that it's correct in the next call to CreateOffer.
780 (*sender)->set_stream_id(local_stream->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700781 }
782 }
783
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000784 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785 observer_->OnRenegotiationNeeded();
786 return true;
787}
788
deadbeefab9b2d12015-10-14 11:33:11 -0700789// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
deadbeeffac06552015-11-25 11:26:01 -0800790// indefinitely, when we have unified plan SDP.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000791void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100792 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700793 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800794 auto sender = FindSenderForTrack(track.get());
795 if (sender == senders_.end()) {
796 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
797 << " doesn't exist.";
798 continue;
deadbeefab9b2d12015-10-14 11:33:11 -0700799 }
deadbeeffac06552015-11-25 11:26:01 -0800800 (*sender)->Stop();
801 senders_.erase(sender);
deadbeefab9b2d12015-10-14 11:33:11 -0700802 }
803 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800804 auto sender = FindSenderForTrack(track.get());
805 if (sender == senders_.end()) {
806 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
807 << " doesn't exist.";
808 continue;
deadbeefab9b2d12015-10-14 11:33:11 -0700809 }
deadbeeffac06552015-11-25 11:26:01 -0800810 (*sender)->Stop();
811 senders_.erase(sender);
deadbeefab9b2d12015-10-14 11:33:11 -0700812 }
813
814 local_streams_->RemoveStream(local_stream);
815
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000816 if (IsClosed()) {
817 return;
818 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 observer_->OnRenegotiationNeeded();
820}
821
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000822rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100824 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 if (!track) {
826 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
827 return NULL;
828 }
deadbeefab9b2d12015-10-14 11:33:11 -0700829 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000830 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
831 return NULL;
832 }
833
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000834 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 DtmfSender::Create(track, signaling_thread(), session_.get()));
836 if (!sender.get()) {
837 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
838 return NULL;
839 }
840 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
841}
842
deadbeeffac06552015-11-25 11:26:01 -0800843rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
844 const std::string& kind) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100845 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeeffac06552015-11-25 11:26:01 -0800846 RtpSenderInterface* new_sender;
847 if (kind == MediaStreamTrackInterface::kAudioKind) {
848 new_sender = new AudioRtpSender(session_.get(), stats_.get());
849 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
850 new_sender = new VideoRtpSender(session_.get());
851 } else {
852 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
853 return rtc::scoped_refptr<RtpSenderInterface>();
854 }
855 senders_.push_back(new_sender);
856 return RtpSenderProxy::Create(signaling_thread(), new_sender);
857}
858
deadbeef70ab1a12015-09-28 16:53:55 -0700859std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
860 const {
861 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
862 for (const auto& sender : senders_) {
863 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
864 }
865 return senders;
866}
867
868std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
869PeerConnection::GetReceivers() const {
870 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
871 for (const auto& receiver : receivers_) {
872 receivers.push_back(
873 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
874 }
875 return receivers;
876}
877
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000879 MediaStreamTrackInterface* track,
880 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100881 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700882 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 if (!VERIFY(observer != NULL)) {
884 LOG(LS_ERROR) << "GetStats - observer is NULL.";
885 return false;
886 }
887
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000888 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000889 signaling_thread()->Post(this, MSG_GETSTATS,
890 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891 return true;
892}
893
894PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
895 return signaling_state_;
896}
897
898PeerConnectionInterface::IceState PeerConnection::ice_state() {
899 return ice_state_;
900}
901
902PeerConnectionInterface::IceConnectionState
903PeerConnection::ice_connection_state() {
904 return ice_connection_state_;
905}
906
907PeerConnectionInterface::IceGatheringState
908PeerConnection::ice_gathering_state() {
909 return ice_gathering_state_;
910}
911
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000912rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913PeerConnection::CreateDataChannel(
914 const std::string& label,
915 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100916 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700917 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000918
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000919 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000920 if (config) {
921 internal_config.reset(new InternalDataChannelInit(*config));
922 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000923 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700924 InternalCreateDataChannel(label, internal_config.get()));
925 if (!channel.get()) {
926 return nullptr;
927 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000929 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
930 // the first SCTP DataChannel.
931 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
932 observer_->OnRenegotiationNeeded();
933 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000934
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 return DataChannelProxy::Create(signaling_thread(), channel.get());
936}
937
938void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
939 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100940 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700941 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
943 return;
944 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000945 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000946
947 bool value;
948 size_t mandatory_constraints = 0;
949
950 if (FindConstraint(constraints,
951 MediaConstraintsInterface::kOfferToReceiveAudio,
952 &value,
953 &mandatory_constraints)) {
954 options.offer_to_receive_audio =
955 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
956 }
957
958 if (FindConstraint(constraints,
959 MediaConstraintsInterface::kOfferToReceiveVideo,
960 &value,
961 &mandatory_constraints)) {
962 options.offer_to_receive_video =
963 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
964 }
965
966 if (FindConstraint(constraints,
967 MediaConstraintsInterface::kVoiceActivityDetection,
968 &value,
969 &mandatory_constraints)) {
970 options.voice_activity_detection = value;
971 }
972
973 if (FindConstraint(constraints,
974 MediaConstraintsInterface::kIceRestart,
975 &value,
976 &mandatory_constraints)) {
977 options.ice_restart = value;
978 }
979
980 if (FindConstraint(constraints,
981 MediaConstraintsInterface::kUseRtpMux,
982 &value,
983 &mandatory_constraints)) {
984 options.use_rtp_mux = value;
985 }
986
987 CreateOffer(observer, options);
988}
989
990void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
991 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100992 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700993 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000994 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
995 return;
996 }
deadbeefab9b2d12015-10-14 11:33:11 -0700997
998 cricket::MediaSessionOptions session_options;
999 if (!GetOptionsForOffer(options, &session_options)) {
1000 std::string error = "CreateOffer called with invalid options.";
1001 LOG(LS_ERROR) << error;
1002 PostCreateSessionDescriptionFailure(observer, error);
1003 return;
1004 }
1005
1006 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007}
1008
1009void PeerConnection::CreateAnswer(
1010 CreateSessionDescriptionObserver* observer,
1011 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001012 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001013 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1015 return;
1016 }
deadbeefab9b2d12015-10-14 11:33:11 -07001017
1018 cricket::MediaSessionOptions session_options;
1019 if (!GetOptionsForAnswer(constraints, &session_options)) {
1020 std::string error = "CreateAnswer called with invalid constraints.";
1021 LOG(LS_ERROR) << error;
1022 PostCreateSessionDescriptionFailure(observer, error);
1023 return;
1024 }
1025
1026 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027}
1028
1029void PeerConnection::SetLocalDescription(
1030 SetSessionDescriptionObserver* observer,
1031 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001032 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001033 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1035 return;
1036 }
1037 if (!desc) {
1038 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1039 return;
1040 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 // Update stats here so that we have the most recent stats for tracks and
1042 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001043 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044 std::string error;
1045 if (!session_->SetLocalDescription(desc, &error)) {
1046 PostSetSessionDescriptionFailure(observer, error);
1047 return;
1048 }
deadbeefab9b2d12015-10-14 11:33:11 -07001049
1050 // If setting the description decided our SSL role, allocate any necessary
1051 // SCTP sids.
1052 rtc::SSLRole role;
1053 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1054 session_->GetSslRole(&role)) {
1055 AllocateSctpSids(role);
1056 }
1057
1058 // Update state and SSRC of local MediaStreams and DataChannels based on the
1059 // local session description.
1060 const cricket::ContentInfo* audio_content =
1061 GetFirstAudioContent(desc->description());
1062 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001063 if (audio_content->rejected) {
1064 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1065 } else {
1066 const cricket::AudioContentDescription* audio_desc =
1067 static_cast<const cricket::AudioContentDescription*>(
1068 audio_content->description);
1069 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1070 }
deadbeefab9b2d12015-10-14 11:33:11 -07001071 }
1072
1073 const cricket::ContentInfo* video_content =
1074 GetFirstVideoContent(desc->description());
1075 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001076 if (video_content->rejected) {
1077 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1078 } else {
1079 const cricket::VideoContentDescription* video_desc =
1080 static_cast<const cricket::VideoContentDescription*>(
1081 video_content->description);
1082 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1083 }
deadbeefab9b2d12015-10-14 11:33:11 -07001084 }
1085
1086 const cricket::ContentInfo* data_content =
1087 GetFirstDataContent(desc->description());
1088 if (data_content) {
1089 const cricket::DataContentDescription* data_desc =
1090 static_cast<const cricket::DataContentDescription*>(
1091 data_content->description);
1092 if (rtc::starts_with(data_desc->protocol().data(),
1093 cricket::kMediaProtocolRtpPrefix)) {
1094 UpdateLocalRtpDataChannels(data_desc->streams());
1095 }
1096 }
1097
1098 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001099 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001100
deadbeefcbecd352015-09-23 11:50:27 -07001101 // MaybeStartGathering needs to be called after posting
1102 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1103 // before signaling that SetLocalDescription completed.
1104 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105}
1106
1107void PeerConnection::SetRemoteDescription(
1108 SetSessionDescriptionObserver* observer,
1109 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001110 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001111 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1113 return;
1114 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115 if (!desc) {
1116 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1117 return;
1118 }
1119 // Update stats here so that we have the most recent stats for tracks and
1120 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001121 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122 std::string error;
1123 if (!session_->SetRemoteDescription(desc, &error)) {
1124 PostSetSessionDescriptionFailure(observer, error);
1125 return;
1126 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127
deadbeefab9b2d12015-10-14 11:33:11 -07001128 // If setting the description decided our SSL role, allocate any necessary
1129 // SCTP sids.
1130 rtc::SSLRole role;
1131 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1132 session_->GetSslRole(&role)) {
1133 AllocateSctpSids(role);
1134 }
1135
1136 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001137 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1138 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1139 const cricket::AudioContentDescription* audio_desc =
1140 GetFirstAudioContentDescription(remote_desc);
1141 const cricket::VideoContentDescription* video_desc =
1142 GetFirstVideoContentDescription(remote_desc);
1143 const cricket::DataContentDescription* data_desc =
1144 GetFirstDataContentDescription(remote_desc);
1145
1146 // Check if the descriptions include streams, just in case the peer supports
1147 // MSID, but doesn't indicate so with "a=msid-semantic".
1148 if (remote_desc->msid_supported() ||
1149 (audio_desc && !audio_desc->streams().empty()) ||
1150 (video_desc && !video_desc->streams().empty())) {
1151 remote_peer_supports_msid_ = true;
1152 }
deadbeefab9b2d12015-10-14 11:33:11 -07001153
1154 // We wait to signal new streams until we finish processing the description,
1155 // since only at that point will new streams have all their tracks.
1156 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1157
1158 // Find all audio rtp streams and create corresponding remote AudioTracks
1159 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001160 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001161 if (audio_content->rejected) {
1162 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1163 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001164 bool default_audio_track_needed =
1165 !remote_peer_supports_msid_ &&
1166 MediaContentDirectionHasSend(audio_desc->direction());
1167 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1168 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001169 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001170 }
deadbeefab9b2d12015-10-14 11:33:11 -07001171 }
1172
1173 // Find all video rtp streams and create corresponding remote VideoTracks
1174 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001175 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001176 if (video_content->rejected) {
1177 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1178 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001179 bool default_video_track_needed =
1180 !remote_peer_supports_msid_ &&
1181 MediaContentDirectionHasSend(video_desc->direction());
1182 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1183 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001184 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001185 }
deadbeefab9b2d12015-10-14 11:33:11 -07001186 }
1187
1188 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001189 if (data_desc) {
1190 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001191 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001192 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001193 }
1194 }
1195
1196 // Iterate new_streams and notify the observer about new MediaStreams.
1197 for (size_t i = 0; i < new_streams->count(); ++i) {
1198 MediaStreamInterface* new_stream = new_streams->at(i);
1199 stats_->AddStream(new_stream);
1200 observer_->OnAddStream(new_stream);
1201 }
1202
deadbeefbda7e0b2015-12-08 17:13:40 -08001203 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001204
1205 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1206 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001207}
1208
deadbeefa67696b2015-09-29 11:56:26 -07001209bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001210 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001211 if (port_allocator_) {
1212 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1213 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1214 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1215 return false;
1216 }
1217
deadbeef653b8e02015-11-11 12:55:10 -08001218 cricket::ServerAddresses cricket_stuns;
1219 std::vector<cricket::RelayServerConfig> cricket_turns;
1220 ConvertToCricketIceServers(stuns, turns, &cricket_stuns, &cricket_turns);
1221 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001222 }
honghaiz1f429e32015-09-28 07:57:34 -07001223 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001224 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001225}
1226
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227bool PeerConnection::AddIceCandidate(
1228 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001229 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230 return session_->ProcessIceMessage(ice_candidate);
1231}
1232
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001233void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001234 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001235 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001236
1237 if (session_) {
1238 session_->set_metrics_observer(uma_observer_);
1239 }
1240
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001241 // Send information about IPv4/IPv6 status.
1242 if (uma_observer_ && port_allocator_) {
1243 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001244 uma_observer_->IncrementEnumCounter(
1245 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1246 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001247 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001248 uma_observer_->IncrementEnumCounter(
1249 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1250 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001251 }
1252 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001253}
1254
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001255const SessionDescriptionInterface* PeerConnection::local_description() const {
1256 return session_->local_description();
1257}
1258
1259const SessionDescriptionInterface* PeerConnection::remote_description() const {
1260 return session_->remote_description();
1261}
1262
1263void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001264 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265 // Update stats here so that we have the most recent stats for tracks and
1266 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001267 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268
deadbeefd59daf82015-10-14 15:02:44 -07001269 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001270}
1271
deadbeefd59daf82015-10-14 15:02:44 -07001272void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1273 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001275 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001277 break;
deadbeefd59daf82015-10-14 15:02:44 -07001278 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1280 break;
deadbeefd59daf82015-10-14 15:02:44 -07001281 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1283 break;
deadbeefd59daf82015-10-14 15:02:44 -07001284 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1286 break;
deadbeefd59daf82015-10-14 15:02:44 -07001287 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1289 break;
deadbeefd59daf82015-10-14 15:02:44 -07001290 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 ChangeSignalingState(PeerConnectionInterface::kStable);
1292 break;
deadbeefd59daf82015-10-14 15:02:44 -07001293 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001294 ChangeSignalingState(PeerConnectionInterface::kClosed);
1295 break;
1296 default:
1297 break;
1298 }
1299}
1300
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001301void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1304 SetSessionDescriptionMsg* param =
1305 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1306 param->observer->OnSuccess();
1307 delete param;
1308 break;
1309 }
1310 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1311 SetSessionDescriptionMsg* param =
1312 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1313 param->observer->OnFailure(param->error);
1314 delete param;
1315 break;
1316 }
deadbeefab9b2d12015-10-14 11:33:11 -07001317 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1318 CreateSessionDescriptionMsg* param =
1319 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1320 param->observer->OnFailure(param->error);
1321 delete param;
1322 break;
1323 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 case MSG_GETSTATS: {
1325 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001326 StatsReports reports;
1327 stats_->GetStats(param->track, &reports);
1328 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 delete param;
1330 break;
1331 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001333 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 break;
1335 }
1336}
1337
deadbeefab9b2d12015-10-14 11:33:11 -07001338void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1339 AudioTrackInterface* audio_track,
1340 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001341 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342}
1343
deadbeefab9b2d12015-10-14 11:33:11 -07001344void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1345 VideoTrackInterface* video_track,
1346 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001347 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348}
1349
deadbeef70ab1a12015-09-28 16:53:55 -07001350// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1351// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001352void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1353 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001354 auto it = FindReceiverForTrack(audio_track);
1355 if (it == receivers_.end()) {
1356 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1357 << " doesn't exist.";
1358 } else {
1359 (*it)->Stop();
1360 receivers_.erase(it);
1361 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001362}
1363
deadbeefab9b2d12015-10-14 11:33:11 -07001364void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1365 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001366 auto it = FindReceiverForTrack(video_track);
1367 if (it == receivers_.end()) {
1368 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1369 << " doesn't exist.";
1370 } else {
1371 (*it)->Stop();
1372 receivers_.erase(it);
1373 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374}
deadbeef70ab1a12015-09-28 16:53:55 -07001375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376void PeerConnection::OnIceConnectionChange(
1377 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001378 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001379 // After transitioning to "closed", ignore any additional states from
1380 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001381 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001382 return;
1383 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001385 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386}
1387
1388void PeerConnection::OnIceGatheringChange(
1389 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001390 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 if (IsClosed()) {
1392 return;
1393 }
1394 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001395 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396}
1397
1398void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001399 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001400 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401}
1402
1403void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001404 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001405 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406}
1407
Peter Thatcher54360512015-07-08 11:08:35 -07001408void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001409 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001410 observer_->OnIceConnectionReceivingChange(receiving);
1411}
1412
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413void PeerConnection::ChangeSignalingState(
1414 PeerConnectionInterface::SignalingState signaling_state) {
1415 signaling_state_ = signaling_state;
1416 if (signaling_state == kClosed) {
1417 ice_connection_state_ = kIceConnectionClosed;
1418 observer_->OnIceConnectionChange(ice_connection_state_);
1419 if (ice_gathering_state_ != kIceGatheringComplete) {
1420 ice_gathering_state_ = kIceGatheringComplete;
1421 observer_->OnIceGatheringChange(ice_gathering_state_);
1422 }
1423 }
1424 observer_->OnSignalingChange(signaling_state_);
1425 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1426}
1427
deadbeefab9b2d12015-10-14 11:33:11 -07001428void PeerConnection::PostSetSessionDescriptionFailure(
1429 SetSessionDescriptionObserver* observer,
1430 const std::string& error) {
1431 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1432 msg->error = error;
1433 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1434}
1435
1436void PeerConnection::PostCreateSessionDescriptionFailure(
1437 CreateSessionDescriptionObserver* observer,
1438 const std::string& error) {
1439 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1440 msg->error = error;
1441 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1442}
1443
1444bool PeerConnection::GetOptionsForOffer(
1445 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1446 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001447 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1448 return false;
1449 }
1450
deadbeeffac06552015-11-25 11:26:01 -08001451 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001452 // Offer to receive audio/video if the constraint is not set and there are
1453 // send streams, or we're currently receiving.
1454 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1455 session_options->recv_audio =
1456 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1457 !remote_audio_tracks_.empty();
1458 }
1459 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1460 session_options->recv_video =
1461 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1462 !remote_video_tracks_.empty();
1463 }
1464 session_options->bundle_enabled =
1465 session_options->bundle_enabled &&
1466 (session_options->has_audio() || session_options->has_video() ||
1467 session_options->has_data());
1468
deadbeefab9b2d12015-10-14 11:33:11 -07001469 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1470 session_options->data_channel_type = cricket::DCT_SCTP;
1471 }
1472 return true;
1473}
1474
1475bool PeerConnection::GetOptionsForAnswer(
1476 const MediaConstraintsInterface* constraints,
1477 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001478 session_options->recv_audio = false;
1479 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001480 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1481 return false;
1482 }
1483
deadbeeffac06552015-11-25 11:26:01 -08001484 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001485 session_options->bundle_enabled =
1486 session_options->bundle_enabled &&
1487 (session_options->has_audio() || session_options->has_video() ||
1488 session_options->has_data());
1489
deadbeefab9b2d12015-10-14 11:33:11 -07001490 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1491 // are not signaled in the SDP so does not go through that path and must be
1492 // handled here.
1493 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1494 session_options->data_channel_type = cricket::DCT_SCTP;
1495 }
1496 return true;
1497}
1498
deadbeeffaac4972015-11-12 15:33:07 -08001499void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1500 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001501 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1502 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001503}
1504
deadbeefab9b2d12015-10-14 11:33:11 -07001505void PeerConnection::UpdateRemoteStreamsList(
1506 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001507 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001508 cricket::MediaType media_type,
1509 StreamCollection* new_streams) {
1510 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1511
1512 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001513 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001514 auto track_it = current_tracks->begin();
1515 while (track_it != current_tracks->end()) {
1516 const TrackInfo& info = *track_it;
1517 const cricket::StreamParams* params =
1518 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001519 bool track_exists = params && params->id == info.track_id;
1520 // If this is a default track, and we still need it, don't remove it.
1521 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1522 track_exists) {
1523 ++track_it;
1524 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001525 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1526 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001527 }
1528 }
1529
1530 // Find new and active tracks.
1531 for (const cricket::StreamParams& params : streams) {
1532 // The sync_label is the MediaStream label and the |stream.id| is the
1533 // track id.
1534 const std::string& stream_label = params.sync_label;
1535 const std::string& track_id = params.id;
1536 uint32_t ssrc = params.first_ssrc();
1537
1538 rtc::scoped_refptr<MediaStreamInterface> stream =
1539 remote_streams_->find(stream_label);
1540 if (!stream) {
1541 // This is a new MediaStream. Create a new remote MediaStream.
1542 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1543 remote_streams_->AddStream(stream);
1544 new_streams->AddStream(stream);
1545 }
1546
1547 const TrackInfo* track_info =
1548 FindTrackInfo(*current_tracks, stream_label, track_id);
1549 if (!track_info) {
1550 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1551 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1552 }
1553 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001554
1555 // Add default track if necessary.
1556 if (default_track_needed) {
1557 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1558 remote_streams_->find(kDefaultStreamLabel);
1559 if (!default_stream) {
1560 // Create the new default MediaStream.
1561 default_stream =
1562 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1563 remote_streams_->AddStream(default_stream);
1564 new_streams->AddStream(default_stream);
1565 }
1566 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1567 ? kDefaultAudioTrackLabel
1568 : kDefaultVideoTrackLabel;
1569 const TrackInfo* default_track_info =
1570 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1571 if (!default_track_info) {
1572 current_tracks->push_back(
1573 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1574 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1575 }
1576 }
deadbeefab9b2d12015-10-14 11:33:11 -07001577}
1578
1579void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1580 const std::string& track_id,
1581 uint32_t ssrc,
1582 cricket::MediaType media_type) {
1583 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1584
1585 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1586 AudioTrackInterface* audio_track =
1587 remote_stream_factory_->AddAudioTrack(stream, track_id);
1588 CreateAudioReceiver(stream, audio_track, ssrc);
1589 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1590 VideoTrackInterface* video_track =
1591 remote_stream_factory_->AddVideoTrack(stream, track_id);
1592 CreateVideoReceiver(stream, video_track, ssrc);
1593 } else {
1594 RTC_DCHECK(false && "Invalid media type");
1595 }
1596}
1597
1598void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1599 const std::string& track_id,
1600 cricket::MediaType media_type) {
1601 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1602
1603 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1604 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1605 stream->FindAudioTrack(track_id);
1606 if (audio_track) {
1607 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1608 stream->RemoveTrack(audio_track);
1609 DestroyAudioReceiver(stream, audio_track);
1610 }
1611 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1612 rtc::scoped_refptr<VideoTrackInterface> video_track =
1613 stream->FindVideoTrack(track_id);
1614 if (video_track) {
1615 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1616 stream->RemoveTrack(video_track);
1617 DestroyVideoReceiver(stream, video_track);
1618 }
1619 } else {
1620 ASSERT(false && "Invalid media type");
1621 }
1622}
1623
1624void PeerConnection::UpdateEndedRemoteMediaStreams() {
1625 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1626 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1627 MediaStreamInterface* stream = remote_streams_->at(i);
1628 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1629 streams_to_remove.push_back(stream);
1630 }
1631 }
1632
1633 for (const auto& stream : streams_to_remove) {
1634 remote_streams_->RemoveStream(stream);
1635 observer_->OnRemoveStream(stream);
1636 }
1637}
1638
deadbeefab9b2d12015-10-14 11:33:11 -07001639void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1640 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1641 for (TrackInfos::iterator track_it = current_tracks->begin();
1642 track_it != current_tracks->end(); ++track_it) {
1643 const TrackInfo& info = *track_it;
1644 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1645 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1646 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1647 // There's no guarantee the track is still available, e.g. the track may
1648 // have been removed from the stream by javascript.
1649 if (track) {
1650 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1651 }
1652 }
1653 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1654 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1655 // There's no guarantee the track is still available, e.g. the track may
1656 // have been removed from the stream by javascript.
1657 if (track) {
1658 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1659 }
1660 }
1661 }
1662}
1663
1664void PeerConnection::UpdateLocalTracks(
1665 const std::vector<cricket::StreamParams>& streams,
1666 cricket::MediaType media_type) {
1667 TrackInfos* current_tracks = GetLocalTracks(media_type);
1668
1669 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1670 // don't match the new StreamParam.
1671 TrackInfos::iterator track_it = current_tracks->begin();
1672 while (track_it != current_tracks->end()) {
1673 const TrackInfo& info = *track_it;
1674 const cricket::StreamParams* params =
1675 cricket::GetStreamBySsrc(streams, info.ssrc);
1676 if (!params || params->id != info.track_id ||
1677 params->sync_label != info.stream_label) {
1678 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1679 media_type);
1680 track_it = current_tracks->erase(track_it);
1681 } else {
1682 ++track_it;
1683 }
1684 }
1685
1686 // Find new and active tracks.
1687 for (const cricket::StreamParams& params : streams) {
1688 // The sync_label is the MediaStream label and the |stream.id| is the
1689 // track id.
1690 const std::string& stream_label = params.sync_label;
1691 const std::string& track_id = params.id;
1692 uint32_t ssrc = params.first_ssrc();
1693 const TrackInfo* track_info =
1694 FindTrackInfo(*current_tracks, stream_label, track_id);
1695 if (!track_info) {
1696 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1697 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1698 }
1699 }
1700}
1701
1702void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1703 const std::string& track_id,
1704 uint32_t ssrc,
1705 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001706 RtpSenderInterface* sender = FindSenderById(track_id);
1707 if (!sender) {
1708 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1709 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001710 return;
1711 }
1712
deadbeeffac06552015-11-25 11:26:01 -08001713 if (sender->media_type() != media_type) {
1714 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1715 << " description with an unexpected media type.";
1716 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001717 }
deadbeeffac06552015-11-25 11:26:01 -08001718
1719 sender->set_stream_id(stream_label);
1720 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001721}
1722
1723void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1724 const std::string& track_id,
1725 uint32_t ssrc,
1726 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001727 RtpSenderInterface* sender = FindSenderById(track_id);
1728 if (!sender) {
1729 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001730 // SessionDescriptions has been renegotiated.
1731 return;
1732 }
deadbeeffac06552015-11-25 11:26:01 -08001733
1734 // A sender has been removed from the SessionDescription but it's still
1735 // associated with the PeerConnection. This only occurs if the SDP doesn't
1736 // match with the calls to CreateSender, AddStream and RemoveStream.
1737 if (sender->media_type() != media_type) {
1738 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1739 << " description with an unexpected media type.";
1740 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001741 }
deadbeeffac06552015-11-25 11:26:01 -08001742
1743 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001744}
1745
1746void PeerConnection::UpdateLocalRtpDataChannels(
1747 const cricket::StreamParamsVec& streams) {
1748 std::vector<std::string> existing_channels;
1749
1750 // Find new and active data channels.
1751 for (const cricket::StreamParams& params : streams) {
1752 // |it->sync_label| is actually the data channel label. The reason is that
1753 // we use the same naming of data channels as we do for
1754 // MediaStreams and Tracks.
1755 // For MediaStreams, the sync_label is the MediaStream label and the
1756 // track label is the same as |streamid|.
1757 const std::string& channel_label = params.sync_label;
1758 auto data_channel_it = rtp_data_channels_.find(channel_label);
1759 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1760 continue;
1761 }
1762 // Set the SSRC the data channel should use for sending.
1763 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1764 existing_channels.push_back(data_channel_it->first);
1765 }
1766
1767 UpdateClosingRtpDataChannels(existing_channels, true);
1768}
1769
1770void PeerConnection::UpdateRemoteRtpDataChannels(
1771 const cricket::StreamParamsVec& streams) {
1772 std::vector<std::string> existing_channels;
1773
1774 // Find new and active data channels.
1775 for (const cricket::StreamParams& params : streams) {
1776 // The data channel label is either the mslabel or the SSRC if the mslabel
1777 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1778 std::string label = params.sync_label.empty()
1779 ? rtc::ToString(params.first_ssrc())
1780 : params.sync_label;
1781 auto data_channel_it = rtp_data_channels_.find(label);
1782 if (data_channel_it == rtp_data_channels_.end()) {
1783 // This is a new data channel.
1784 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1785 } else {
1786 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1787 }
1788 existing_channels.push_back(label);
1789 }
1790
1791 UpdateClosingRtpDataChannels(existing_channels, false);
1792}
1793
1794void PeerConnection::UpdateClosingRtpDataChannels(
1795 const std::vector<std::string>& active_channels,
1796 bool is_local_update) {
1797 auto it = rtp_data_channels_.begin();
1798 while (it != rtp_data_channels_.end()) {
1799 DataChannel* data_channel = it->second;
1800 if (std::find(active_channels.begin(), active_channels.end(),
1801 data_channel->label()) != active_channels.end()) {
1802 ++it;
1803 continue;
1804 }
1805
1806 if (is_local_update) {
1807 data_channel->SetSendSsrc(0);
1808 } else {
1809 data_channel->RemotePeerRequestClose();
1810 }
1811
1812 if (data_channel->state() == DataChannel::kClosed) {
1813 rtp_data_channels_.erase(it);
1814 it = rtp_data_channels_.begin();
1815 } else {
1816 ++it;
1817 }
1818 }
1819}
1820
1821void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1822 uint32_t remote_ssrc) {
1823 rtc::scoped_refptr<DataChannel> channel(
1824 InternalCreateDataChannel(label, nullptr));
1825 if (!channel.get()) {
1826 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1827 << "CreateDataChannel failed.";
1828 return;
1829 }
1830 channel->SetReceiveSsrc(remote_ssrc);
1831 observer_->OnDataChannel(
1832 DataChannelProxy::Create(signaling_thread(), channel));
1833}
1834
1835rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1836 const std::string& label,
1837 const InternalDataChannelInit* config) {
1838 if (IsClosed()) {
1839 return nullptr;
1840 }
1841 if (session_->data_channel_type() == cricket::DCT_NONE) {
1842 LOG(LS_ERROR)
1843 << "InternalCreateDataChannel: Data is not supported in this call.";
1844 return nullptr;
1845 }
1846 InternalDataChannelInit new_config =
1847 config ? (*config) : InternalDataChannelInit();
1848 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1849 if (new_config.id < 0) {
1850 rtc::SSLRole role;
1851 if (session_->GetSslRole(&role) &&
1852 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1853 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1854 return nullptr;
1855 }
1856 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1857 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1858 << "because the id is already in use or out of range.";
1859 return nullptr;
1860 }
1861 }
1862
1863 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1864 session_.get(), session_->data_channel_type(), label, new_config));
1865 if (!channel) {
1866 sid_allocator_.ReleaseSid(new_config.id);
1867 return nullptr;
1868 }
1869
1870 if (channel->data_channel_type() == cricket::DCT_RTP) {
1871 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1872 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1873 << " already exists.";
1874 return nullptr;
1875 }
1876 rtp_data_channels_[channel->label()] = channel;
1877 } else {
1878 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1879 sctp_data_channels_.push_back(channel);
1880 channel->SignalClosed.connect(this,
1881 &PeerConnection::OnSctpDataChannelClosed);
1882 }
1883
1884 return channel;
1885}
1886
1887bool PeerConnection::HasDataChannels() const {
1888 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1889}
1890
1891void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1892 for (const auto& channel : sctp_data_channels_) {
1893 if (channel->id() < 0) {
1894 int sid;
1895 if (!sid_allocator_.AllocateSid(role, &sid)) {
1896 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1897 continue;
1898 }
1899 channel->SetSctpSid(sid);
1900 }
1901 }
1902}
1903
1904void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1905 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1906 ++it) {
1907 if (it->get() == channel) {
1908 if (channel->id() >= 0) {
1909 sid_allocator_.ReleaseSid(channel->id());
1910 }
1911 sctp_data_channels_.erase(it);
1912 return;
1913 }
1914 }
1915}
1916
1917void PeerConnection::OnVoiceChannelDestroyed() {
1918 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1919}
1920
1921void PeerConnection::OnVideoChannelDestroyed() {
1922 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1923}
1924
1925void PeerConnection::OnDataChannelCreated() {
1926 for (const auto& channel : sctp_data_channels_) {
1927 channel->OnTransportChannelCreated();
1928 }
1929}
1930
1931void PeerConnection::OnDataChannelDestroyed() {
1932 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1933 // DataChannel may callback to us and try to modify the list.
1934 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1935 temp_rtp_dcs.swap(rtp_data_channels_);
1936 for (const auto& kv : temp_rtp_dcs) {
1937 kv.second->OnTransportChannelDestroyed();
1938 }
1939
1940 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1941 temp_sctp_dcs.swap(sctp_data_channels_);
1942 for (const auto& channel : temp_sctp_dcs) {
1943 channel->OnTransportChannelDestroyed();
1944 }
1945}
1946
1947void PeerConnection::OnDataChannelOpenMessage(
1948 const std::string& label,
1949 const InternalDataChannelInit& config) {
1950 rtc::scoped_refptr<DataChannel> channel(
1951 InternalCreateDataChannel(label, &config));
1952 if (!channel.get()) {
1953 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1954 return;
1955 }
1956
1957 observer_->OnDataChannel(
1958 DataChannelProxy::Create(signaling_thread(), channel));
1959}
1960
deadbeeffac06552015-11-25 11:26:01 -08001961RtpSenderInterface* PeerConnection::FindSenderById(const std::string& id) {
1962 auto it =
1963 std::find_if(senders_.begin(), senders_.end(),
1964 [id](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1965 return sender->id() == id;
1966 });
1967 return it != senders_.end() ? it->get() : nullptr;
1968}
1969
deadbeef70ab1a12015-09-28 16:53:55 -07001970std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1971PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1972 return std::find_if(
1973 senders_.begin(), senders_.end(),
1974 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1975 return sender->track() == track;
1976 });
1977}
1978
1979std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1980PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1981 return std::find_if(
1982 receivers_.begin(), receivers_.end(),
1983 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1984 return receiver->track() == track;
1985 });
1986}
1987
deadbeefab9b2d12015-10-14 11:33:11 -07001988PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1989 cricket::MediaType media_type) {
1990 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1991 media_type == cricket::MEDIA_TYPE_VIDEO);
1992 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1993 : &remote_video_tracks_;
1994}
1995
1996PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
1997 cricket::MediaType media_type) {
1998 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1999 media_type == cricket::MEDIA_TYPE_VIDEO);
2000 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2001 : &local_video_tracks_;
2002}
2003
2004const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2005 const PeerConnection::TrackInfos& infos,
2006 const std::string& stream_label,
2007 const std::string track_id) const {
2008 for (const TrackInfo& track_info : infos) {
2009 if (track_info.stream_label == stream_label &&
2010 track_info.track_id == track_id) {
2011 return &track_info;
2012 }
2013 }
2014 return nullptr;
2015}
2016
2017DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2018 for (const auto& channel : sctp_data_channels_) {
2019 if (channel->id() == sid) {
2020 return channel;
2021 }
2022 }
2023 return nullptr;
2024}
2025
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026} // namespace webrtc