blob: f0db1397aa7941612612ea3be8cb010b0b09c854 [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"
tfarina5237aaf2015-11-10 23:44:30 -080054#include "webrtc/p2p/client/basicportallocator.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010055#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57namespace {
58
deadbeefab9b2d12015-10-14 11:33:11 -070059using webrtc::DataChannel;
60using webrtc::MediaConstraintsInterface;
61using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062using webrtc::PeerConnectionInterface;
deadbeeffac06552015-11-25 11:26:01 -080063using webrtc::RtpSenderInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070064using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070065using webrtc::StunConfigurations;
66using webrtc::TurnConfigurations;
67typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
68 StunConfiguration;
69typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
70 TurnConfiguration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071
deadbeefab9b2d12015-10-14 11:33:11 -070072static const char kDefaultStreamLabel[] = "default";
73static const char kDefaultAudioTrackLabel[] = "defaulta0";
74static const char kDefaultVideoTrackLabel[] = "defaultv0";
75
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076// The min number of tokens must present in Turn host uri.
77// e.g. user@turn.example.org
78static const size_t kTurnHostTokensNum = 2;
79// Number of tokens must be preset when TURN uri has transport param.
80static const size_t kTurnTransportTokensNum = 2;
81// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000082static const int kDefaultStunPort = 3478;
83static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000084static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000085static const char kUdpTransportType[] = "udp";
86static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087
88// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070089static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
deadbeef0a6c4ca2015-10-06 11:38:28 -070091// NOTE: A loop below assumes that the first value of this enum is 0 and all
92// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070094 STUN = 0, // Indicates a STUN server.
95 STUNS, // Indicates a STUN server used with a TLS session.
96 TURN, // Indicates a TURN server
97 TURNS, // Indicates a TURN server used with a TLS session.
98 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099};
tfarina5237aaf2015-11-10 23:44:30 -0800100static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -0700101 "kValidIceServiceTypes must have as many strings as ServiceType "
102 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103
104enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 MSG_GETSTATS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 std::string error;
119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
127 std::string error;
128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000139// |in_str| should be of format
140// stunURI = scheme ":" stun-host [ ":" stun-port ]
141// scheme = "stun" / "stuns"
142// stun-host = IP-literal / IPv4address / reg-name
143// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700144//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000145// draft-petithuguenin-behave-turn-uris-01
146// turnURI = scheme ":" turn-host [ ":" turn-port ]
147// turn-host = username@IP-literal / IPv4address / reg-name
148bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
149 ServiceType* service_type,
150 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200151 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700152 if (colonpos == std::string::npos) {
153 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000154 return false;
155 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700156 if ((colonpos + 1) == in_str.length()) {
157 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
158 return false;
159 }
160 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800161 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700162 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000163 *service_type = static_cast<ServiceType>(i);
164 break;
165 }
166 }
167 if (*service_type == INVALID) {
168 return false;
169 }
170 *hostname = in_str.substr(colonpos + 1, std::string::npos);
171 return true;
172}
173
deadbeef0a6c4ca2015-10-06 11:38:28 -0700174bool ParsePort(const std::string& in_str, int* port) {
175 // Make sure port only contains digits. FromString doesn't check this.
176 for (const char& c : in_str) {
177 if (!std::isdigit(c)) {
178 return false;
179 }
180 }
181 return rtc::FromString(in_str, port);
182}
183
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184// This method parses IPv6 and IPv4 literal strings, along with hostnames in
185// standard hostname:port format.
186// Consider following formats as correct.
187// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700188// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000189bool ParseHostnameAndPortFromString(const std::string& in_str,
190 std::string* host,
191 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700192 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000193 if (in_str.at(0) == '[') {
194 std::string::size_type closebracket = in_str.rfind(']');
195 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000196 std::string::size_type colonpos = in_str.find(':', closebracket);
197 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700198 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
199 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000200 return false;
201 }
202 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700203 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000204 } else {
205 return false;
206 }
207 } else {
208 std::string::size_type colonpos = in_str.find(':');
209 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700210 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000211 return false;
212 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700213 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000214 } else {
215 *host = in_str;
216 }
217 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700218 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000219}
220
deadbeef0a6c4ca2015-10-06 11:38:28 -0700221// Adds a StunConfiguration or TurnConfiguration to the appropriate list,
222// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200223bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
224 const std::string& url,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700225 StunConfigurations* stun_config,
226 TurnConfigurations* turn_config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000227 // draft-nandakumar-rtcweb-stun-uri-01
228 // stunURI = scheme ":" stun-host [ ":" stun-port ]
229 // scheme = "stun" / "stuns"
230 // stun-host = IP-literal / IPv4address / reg-name
231 // stun-port = *DIGIT
232
233 // draft-petithuguenin-behave-turn-uris-01
234 // turnURI = scheme ":" turn-host [ ":" turn-port ]
235 // [ "?transport=" transport ]
236 // scheme = "turn" / "turns"
237 // transport = "udp" / "tcp" / transport-ext
238 // transport-ext = 1*unreserved
239 // turn-host = IP-literal / IPv4address / reg-name
240 // turn-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700241 RTC_DCHECK(stun_config != nullptr);
242 RTC_DCHECK(turn_config != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200243 std::vector<std::string> tokens;
244 std::string turn_transport_type = kUdpTransportType;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700245 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200246 rtc::tokenize(url, '?', &tokens);
247 std::string uri_without_transport = tokens[0];
248 // Let's look into transport= param, if it exists.
249 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
250 std::string uri_transport_param = tokens[1];
251 rtc::tokenize(uri_transport_param, '=', &tokens);
252 if (tokens[0] == kTransport) {
253 // As per above grammar transport param will be consist of lower case
254 // letters.
255 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
256 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700257 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200259 turn_transport_type = tokens[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200261 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200263 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700264 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200265 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
266 &service_type,
267 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700268 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
269 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200270 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000271
deadbeef0a6c4ca2015-10-06 11:38:28 -0700272 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
273 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200274
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200275 // Let's break hostname.
276 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700277 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
278
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200279 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700280 if (tokens.size() > kTurnHostTokensNum) {
281 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
282 return false;
283 }
284 if (tokens.size() == kTurnHostTokensNum) {
285 if (tokens[0].empty() || tokens[1].empty()) {
286 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
287 return false;
288 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200289 username.assign(rtc::s_url_decode(tokens[0]));
290 hoststring = tokens[1];
291 } else {
292 hoststring = tokens[0];
293 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000294
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200295 int port = kDefaultStunPort;
296 if (service_type == TURNS) {
297 port = kDefaultStunTlsPort;
298 turn_transport_type = kTcpTransportType;
299 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000300
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200301 std::string address;
302 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700303 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
304 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200305 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000306
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200307 if (port <= 0 || port > 0xffff) {
308 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700309 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200310 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000311
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200312 switch (service_type) {
313 case STUN:
314 case STUNS:
315 stun_config->push_back(StunConfiguration(address, port));
316 break;
317 case TURN:
318 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200319 bool secure = (service_type == TURNS);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200320 turn_config->push_back(TurnConfiguration(address, port,
321 username,
322 server.password,
323 turn_transport_type,
324 secure));
325 break;
326 }
327 case INVALID:
328 default:
329 LOG(WARNING) << "Configuration not supported: " << url;
330 return false;
331 }
332 return true;
333}
334
deadbeef653b8e02015-11-11 12:55:10 -0800335void ConvertToCricketIceServers(
336 const std::vector<StunConfiguration>& stuns,
337 const std::vector<TurnConfiguration>& turns,
338 cricket::ServerAddresses* cricket_stuns,
339 std::vector<cricket::RelayServerConfig>* cricket_turns) {
340 RTC_DCHECK(cricket_stuns && cricket_turns);
341 for (const StunConfiguration& stun : stuns) {
342 cricket_stuns->insert(stun.server);
343 }
344
345 int priority = static_cast<int>(turns.size() - 1);
346 for (const TurnConfiguration& turn : turns) {
347 cricket::RelayCredentials credentials(turn.username, turn.password);
348 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
349 cricket::ProtocolType protocol;
350 // Using VERIFY because ParseIceServers should have already caught an
351 // invalid transport type.
352 if (!VERIFY(
353 cricket::StringToProto(turn.transport_type.c_str(), &protocol))) {
354 LOG(LS_WARNING) << "Ignoring TURN server " << turn.server << ". "
355 << "Reason= Incorrect " << turn.transport_type
356 << " transport parameter.";
357 } else {
358 relay_server.ports.push_back(
359 cricket::ProtocolAddress(turn.server, protocol, turn.secure));
360 relay_server.credentials = credentials;
361 relay_server.priority = priority;
362 cricket_turns->push_back(relay_server);
363 }
364 // First in the list gets highest priority.
365 --priority;
366 }
367}
368
deadbeefab9b2d12015-10-14 11:33:11 -0700369// Check if we can send |new_stream| on a PeerConnection.
370bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
371 webrtc::MediaStreamInterface* new_stream) {
372 if (!new_stream || !current_streams) {
373 return false;
374 }
375 if (current_streams->find(new_stream->label()) != nullptr) {
376 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
377 << " is already added.";
378 return false;
379 }
380 return true;
381}
382
383bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
384 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
385}
386
deadbeef5e97fb52015-10-15 12:49:08 -0700387// If the direction is "recvonly" or "inactive", treat the description
388// as containing no streams.
389// See: https://code.google.com/p/webrtc/issues/detail?id=5054
390std::vector<cricket::StreamParams> GetActiveStreams(
391 const cricket::MediaContentDescription* desc) {
392 return MediaContentDirectionHasSend(desc->direction())
393 ? desc->streams()
394 : std::vector<cricket::StreamParams>();
395}
396
deadbeefab9b2d12015-10-14 11:33:11 -0700397bool IsValidOfferToReceiveMedia(int value) {
398 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
399 return (value >= Options::kUndefined) &&
400 (value <= Options::kMaxOfferToReceiveMedia);
401}
402
403// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800404void AddSendStreams(
405 cricket::MediaSessionOptions* session_options,
406 const std::vector<rtc::scoped_refptr<RtpSenderInterface>>& senders,
407 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
408 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700409 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800410 for (const auto& sender : senders) {
411 session_options->AddSendStream(sender->media_type(), sender->id(),
412 sender->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700413 }
414
415 // Check for data channels.
416 for (const auto& kv : rtp_data_channels) {
417 const DataChannel* channel = kv.second;
418 if (channel->state() == DataChannel::kConnecting ||
419 channel->state() == DataChannel::kOpen) {
420 // |streamid| and |sync_label| are both set to the DataChannel label
421 // here so they can be signaled the same way as MediaStreams and Tracks.
422 // For MediaStreams, the sync_label is the MediaStream label and the
423 // track label is the same as |streamid|.
424 const std::string& streamid = channel->label();
425 const std::string& sync_label = channel->label();
426 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
427 sync_label);
428 }
429 }
430}
431
deadbeef0a6c4ca2015-10-06 11:38:28 -0700432} // namespace
433
434namespace webrtc {
435
deadbeefab9b2d12015-10-14 11:33:11 -0700436// Factory class for creating remote MediaStreams and MediaStreamTracks.
437class RemoteMediaStreamFactory {
438 public:
439 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
440 cricket::ChannelManager* channel_manager)
441 : signaling_thread_(signaling_thread),
442 channel_manager_(channel_manager) {}
443
444 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
445 const std::string& stream_label) {
446 return MediaStreamProxy::Create(signaling_thread_,
447 MediaStream::Create(stream_label));
448 }
449
450 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
451 const std::string& track_id) {
452 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
453 stream, track_id, RemoteAudioSource::Create().get());
454 }
455
456 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
457 const std::string& track_id) {
458 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
459 stream, track_id,
460 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
461 nullptr)
462 .get());
463 }
464
465 private:
466 template <typename TI, typename T, typename TP, typename S>
467 TI* AddTrack(MediaStreamInterface* stream,
468 const std::string& track_id,
469 S* source) {
470 rtc::scoped_refptr<TI> track(
471 TP::Create(signaling_thread_, T::Create(track_id, source)));
472 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
473 if (stream->AddTrack(track)) {
474 return track;
475 }
476 return nullptr;
477 }
478
479 rtc::Thread* signaling_thread_;
480 cricket::ChannelManager* channel_manager_;
481};
482
483bool ConvertRtcOptionsForOffer(
484 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
485 cricket::MediaSessionOptions* session_options) {
486 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
487 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
488 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
489 return false;
490 }
491
deadbeefc80741f2015-10-22 13:14:45 -0700492 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700493 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
494 }
deadbeefc80741f2015-10-22 13:14:45 -0700495 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700496 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
497 }
498
499 session_options->vad_enabled = rtc_options.voice_activity_detection;
500 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700501 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700502
503 return true;
504}
505
506bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
507 cricket::MediaSessionOptions* session_options) {
508 bool value = false;
509 size_t mandatory_constraints_satisfied = 0;
510
511 // kOfferToReceiveAudio defaults to true according to spec.
512 if (!FindConstraint(constraints,
513 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
514 &mandatory_constraints_satisfied) ||
515 value) {
516 session_options->recv_audio = true;
517 }
518
519 // kOfferToReceiveVideo defaults to false according to spec. But
520 // if it is an answer and video is offered, we should still accept video
521 // per default.
522 value = false;
523 if (!FindConstraint(constraints,
524 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
525 &mandatory_constraints_satisfied) ||
526 value) {
527 session_options->recv_video = true;
528 }
529
530 if (FindConstraint(constraints,
531 MediaConstraintsInterface::kVoiceActivityDetection, &value,
532 &mandatory_constraints_satisfied)) {
533 session_options->vad_enabled = value;
534 }
535
536 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
537 &mandatory_constraints_satisfied)) {
538 session_options->bundle_enabled = value;
539 } else {
540 // kUseRtpMux defaults to true according to spec.
541 session_options->bundle_enabled = true;
542 }
deadbeefab9b2d12015-10-14 11:33:11 -0700543
544 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
545 &value, &mandatory_constraints_satisfied)) {
546 session_options->transport_options.ice_restart = value;
547 } else {
548 // kIceRestart defaults to false according to spec.
549 session_options->transport_options.ice_restart = false;
550 }
551
552 if (!constraints) {
553 return true;
554 }
555 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
556}
557
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200558bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700559 StunConfigurations* stun_config,
560 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200561 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
562 if (!server.urls.empty()) {
563 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200564 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700565 LOG(LS_ERROR) << "Empty uri.";
566 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200567 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200568 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
569 return false;
570 }
571 }
572 } else if (!server.uri.empty()) {
573 // Fallback to old .uri if new .urls isn't present.
574 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200576 }
577 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700578 LOG(LS_ERROR) << "Empty uri.";
579 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000580 }
581 }
582 return true;
583}
584
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585PeerConnection::PeerConnection(PeerConnectionFactory* factory)
586 : factory_(factory),
587 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000588 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 signaling_state_(kStable),
590 ice_state_(kIceNew),
591 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700592 ice_gathering_state_(kIceGatheringNew),
593 local_streams_(StreamCollection::Create()),
594 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595
596PeerConnection::~PeerConnection() {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700597 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700598 // Need to detach RTP senders/receivers from WebRtcSession,
599 // since it's about to be destroyed.
600 for (const auto& sender : senders_) {
601 sender->Stop();
602 }
603 for (const auto& receiver : receivers_) {
604 receiver->Stop();
605 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000606}
607
608bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000609 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000611 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200612 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700614 RTC_DCHECK(observer != nullptr);
615 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000616 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700617 }
deadbeef653b8e02015-11-11 12:55:10 -0800618
619 // This Initialize function parses ICE servers an extra time, but it will
620 // be removed once all PortAllocaotrs support SetIceServers.
621 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
622 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
623 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
624 return false;
625 }
626 rtc::scoped_ptr<cricket::PortAllocator> allocator(
627 allocator_factory->CreatePortAllocator(stun_config, turn_config));
628 return Initialize(configuration, constraints, allocator.Pass(),
629 dtls_identity_store.Pass(), observer);
630}
631
632bool PeerConnection::Initialize(
633 const PeerConnectionInterface::RTCConfiguration& configuration,
634 const MediaConstraintsInterface* constraints,
635 rtc::scoped_ptr<cricket::PortAllocator> allocator,
636 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
637 PeerConnectionObserver* observer) {
638 RTC_DCHECK(observer != nullptr);
639 if (!observer) {
640 return false;
641 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000642 observer_ = observer;
643
deadbeef653b8e02015-11-11 12:55:10 -0800644 port_allocator_ = allocator.Pass();
645
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000646 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
647 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000648 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000649 return false;
650 }
deadbeef653b8e02015-11-11 12:55:10 -0800651
652 cricket::ServerAddresses cricket_stuns;
653 std::vector<cricket::RelayServerConfig> cricket_turns;
654 ConvertToCricketIceServers(stun_config, turn_config, &cricket_stuns,
655 &cricket_turns);
656 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000657
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000659 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000660 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700661 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000662 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000663 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000664 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700665 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
666 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000667 if (!value) {
668 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000669 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000670 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000671 "Disabled") {
672 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000673 }
674
Jiayang Liucac1b382015-04-30 12:35:24 -0700675 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
676 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
677 LOG(LS_INFO) << "TCP candidates are disabled.";
678 }
679
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000680 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 // No step delay is used while allocating ports.
682 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
683
stefanc1aeaf02015-10-15 07:26:07 -0700684 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685
stefanc1aeaf02015-10-15 07:26:07 -0700686 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
687 factory_->signaling_thread(), media_controller_->channel_manager()));
688
689 session_.reset(
690 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
691 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700692 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693
694 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000695 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700696 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000697 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700698 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 // Register PeerConnection as receiver of local ice candidates.
701 // All the callbacks will be posted to the application from PeerConnection.
702 session_->RegisterIceObserver(this);
703 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700704 session_->SignalVoiceChannelDestroyed.connect(
705 this, &PeerConnection::OnVoiceChannelDestroyed);
706 session_->SignalVideoChannelDestroyed.connect(
707 this, &PeerConnection::OnVideoChannelDestroyed);
708 session_->SignalDataChannelCreated.connect(
709 this, &PeerConnection::OnDataChannelCreated);
710 session_->SignalDataChannelDestroyed.connect(
711 this, &PeerConnection::OnDataChannelDestroyed);
712 session_->SignalDataChannelOpenMessage.connect(
713 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714 return true;
715}
716
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000717rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700719 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720}
721
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000722rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700724 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725}
726
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000727bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 if (IsClosed()) {
729 return false;
730 }
deadbeefab9b2d12015-10-14 11:33:11 -0700731 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732 return false;
733 }
deadbeefab9b2d12015-10-14 11:33:11 -0700734
735 local_streams_->AddStream(local_stream);
736
deadbeefab9b2d12015-10-14 11:33:11 -0700737 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800738 auto sender = FindSenderForTrack(track.get());
739 if (sender == senders_.end()) {
740 // Normal case; we've never seen this track before.
741 AudioRtpSender* new_sender = new AudioRtpSender(
742 track.get(), local_stream->label(), session_.get(), stats_.get());
743 senders_.push_back(new_sender);
744 // If the sender has already been configured in SDP, we call SetSsrc,
745 // which will connect the sender to the underlying transport. This can
746 // occur if a local session description that contains the ID of the sender
747 // is set before AddStream is called. It can also occur if the local
748 // session description is not changed and RemoveStream is called, and
749 // later AddStream is called again with the same stream.
750 const TrackInfo* track_info = FindTrackInfo(
751 local_audio_tracks_, local_stream->label(), track->id());
752 if (track_info) {
753 new_sender->SetSsrc(track_info->ssrc);
754 }
755 } else {
756 // We already have a sender for this track, so just change the stream_id
757 // so that it's correct in the next call to CreateOffer.
758 (*sender)->set_stream_id(local_stream->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700759 }
760 }
761 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800762 auto sender = FindSenderForTrack(track.get());
763 if (sender == senders_.end()) {
764 // Normal case; we've never seen this track before.
765 VideoRtpSender* new_sender = new VideoRtpSender(
766 track.get(), local_stream->label(), session_.get());
767 senders_.push_back(new_sender);
768 const TrackInfo* track_info = FindTrackInfo(
769 local_video_tracks_, local_stream->label(), track->id());
770 if (track_info) {
771 new_sender->SetSsrc(track_info->ssrc);
772 }
773 } else {
774 // We already have a sender for this track, so just change the stream_id
775 // so that it's correct in the next call to CreateOffer.
776 (*sender)->set_stream_id(local_stream->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700777 }
778 }
779
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000780 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000781 observer_->OnRenegotiationNeeded();
782 return true;
783}
784
deadbeefab9b2d12015-10-14 11:33:11 -0700785// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
deadbeeffac06552015-11-25 11:26:01 -0800786// indefinitely, when we have unified plan SDP.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000787void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
deadbeefab9b2d12015-10-14 11:33:11 -0700788 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800789 auto sender = FindSenderForTrack(track.get());
790 if (sender == senders_.end()) {
791 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
792 << " doesn't exist.";
793 continue;
deadbeefab9b2d12015-10-14 11:33:11 -0700794 }
deadbeeffac06552015-11-25 11:26:01 -0800795 (*sender)->Stop();
796 senders_.erase(sender);
deadbeefab9b2d12015-10-14 11:33:11 -0700797 }
798 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800799 auto sender = FindSenderForTrack(track.get());
800 if (sender == senders_.end()) {
801 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
802 << " doesn't exist.";
803 continue;
deadbeefab9b2d12015-10-14 11:33:11 -0700804 }
deadbeeffac06552015-11-25 11:26:01 -0800805 (*sender)->Stop();
806 senders_.erase(sender);
deadbeefab9b2d12015-10-14 11:33:11 -0700807 }
808
809 local_streams_->RemoveStream(local_stream);
810
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 if (IsClosed()) {
812 return;
813 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 observer_->OnRenegotiationNeeded();
815}
816
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000817rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 AudioTrackInterface* track) {
819 if (!track) {
820 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
821 return NULL;
822 }
deadbeefab9b2d12015-10-14 11:33:11 -0700823 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
825 return NULL;
826 }
827
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000828 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829 DtmfSender::Create(track, signaling_thread(), session_.get()));
830 if (!sender.get()) {
831 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
832 return NULL;
833 }
834 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
835}
836
deadbeeffac06552015-11-25 11:26:01 -0800837rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
838 const std::string& kind) {
839 RtpSenderInterface* new_sender;
840 if (kind == MediaStreamTrackInterface::kAudioKind) {
841 new_sender = new AudioRtpSender(session_.get(), stats_.get());
842 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
843 new_sender = new VideoRtpSender(session_.get());
844 } else {
845 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
846 return rtc::scoped_refptr<RtpSenderInterface>();
847 }
848 senders_.push_back(new_sender);
849 return RtpSenderProxy::Create(signaling_thread(), new_sender);
850}
851
deadbeef70ab1a12015-09-28 16:53:55 -0700852std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
853 const {
854 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
855 for (const auto& sender : senders_) {
856 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
857 }
858 return senders;
859}
860
861std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
862PeerConnection::GetReceivers() const {
863 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
864 for (const auto& receiver : receivers_) {
865 receivers.push_back(
866 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
867 }
868 return receivers;
869}
870
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000872 MediaStreamTrackInterface* track,
873 StatsOutputLevel level) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700874 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875 if (!VERIFY(observer != NULL)) {
876 LOG(LS_ERROR) << "GetStats - observer is NULL.";
877 return false;
878 }
879
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000880 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000881 signaling_thread()->Post(this, MSG_GETSTATS,
882 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 return true;
884}
885
886PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
887 return signaling_state_;
888}
889
890PeerConnectionInterface::IceState PeerConnection::ice_state() {
891 return ice_state_;
892}
893
894PeerConnectionInterface::IceConnectionState
895PeerConnection::ice_connection_state() {
896 return ice_connection_state_;
897}
898
899PeerConnectionInterface::IceGatheringState
900PeerConnection::ice_gathering_state() {
901 return ice_gathering_state_;
902}
903
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000904rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905PeerConnection::CreateDataChannel(
906 const std::string& label,
907 const DataChannelInit* config) {
deadbeefab9b2d12015-10-14 11:33:11 -0700908 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000909
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000910 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000911 if (config) {
912 internal_config.reset(new InternalDataChannelInit(*config));
913 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000914 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700915 InternalCreateDataChannel(label, internal_config.get()));
916 if (!channel.get()) {
917 return nullptr;
918 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000920 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
921 // the first SCTP DataChannel.
922 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
923 observer_->OnRenegotiationNeeded();
924 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000925
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926 return DataChannelProxy::Create(signaling_thread(), channel.get());
927}
928
929void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
930 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700931 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
933 return;
934 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000935 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000936
937 bool value;
938 size_t mandatory_constraints = 0;
939
940 if (FindConstraint(constraints,
941 MediaConstraintsInterface::kOfferToReceiveAudio,
942 &value,
943 &mandatory_constraints)) {
944 options.offer_to_receive_audio =
945 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
946 }
947
948 if (FindConstraint(constraints,
949 MediaConstraintsInterface::kOfferToReceiveVideo,
950 &value,
951 &mandatory_constraints)) {
952 options.offer_to_receive_video =
953 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
954 }
955
956 if (FindConstraint(constraints,
957 MediaConstraintsInterface::kVoiceActivityDetection,
958 &value,
959 &mandatory_constraints)) {
960 options.voice_activity_detection = value;
961 }
962
963 if (FindConstraint(constraints,
964 MediaConstraintsInterface::kIceRestart,
965 &value,
966 &mandatory_constraints)) {
967 options.ice_restart = value;
968 }
969
970 if (FindConstraint(constraints,
971 MediaConstraintsInterface::kUseRtpMux,
972 &value,
973 &mandatory_constraints)) {
974 options.use_rtp_mux = value;
975 }
976
977 CreateOffer(observer, options);
978}
979
980void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
981 const RTCOfferAnswerOptions& options) {
deadbeefab9b2d12015-10-14 11:33:11 -0700982 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000983 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
984 return;
985 }
deadbeefab9b2d12015-10-14 11:33:11 -0700986
987 cricket::MediaSessionOptions session_options;
988 if (!GetOptionsForOffer(options, &session_options)) {
989 std::string error = "CreateOffer called with invalid options.";
990 LOG(LS_ERROR) << error;
991 PostCreateSessionDescriptionFailure(observer, error);
992 return;
993 }
994
995 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996}
997
998void PeerConnection::CreateAnswer(
999 CreateSessionDescriptionObserver* observer,
1000 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -07001001 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1003 return;
1004 }
deadbeefab9b2d12015-10-14 11:33:11 -07001005
1006 cricket::MediaSessionOptions session_options;
1007 if (!GetOptionsForAnswer(constraints, &session_options)) {
1008 std::string error = "CreateAnswer called with invalid constraints.";
1009 LOG(LS_ERROR) << error;
1010 PostCreateSessionDescriptionFailure(observer, error);
1011 return;
1012 }
1013
1014 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015}
1016
1017void PeerConnection::SetLocalDescription(
1018 SetSessionDescriptionObserver* observer,
1019 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -07001020 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1022 return;
1023 }
1024 if (!desc) {
1025 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1026 return;
1027 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028 // Update stats here so that we have the most recent stats for tracks and
1029 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001030 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031 std::string error;
1032 if (!session_->SetLocalDescription(desc, &error)) {
1033 PostSetSessionDescriptionFailure(observer, error);
1034 return;
1035 }
deadbeefab9b2d12015-10-14 11:33:11 -07001036
1037 // If setting the description decided our SSL role, allocate any necessary
1038 // SCTP sids.
1039 rtc::SSLRole role;
1040 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1041 session_->GetSslRole(&role)) {
1042 AllocateSctpSids(role);
1043 }
1044
1045 // Update state and SSRC of local MediaStreams and DataChannels based on the
1046 // local session description.
1047 const cricket::ContentInfo* audio_content =
1048 GetFirstAudioContent(desc->description());
1049 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001050 if (audio_content->rejected) {
1051 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1052 } else {
1053 const cricket::AudioContentDescription* audio_desc =
1054 static_cast<const cricket::AudioContentDescription*>(
1055 audio_content->description);
1056 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1057 }
deadbeefab9b2d12015-10-14 11:33:11 -07001058 }
1059
1060 const cricket::ContentInfo* video_content =
1061 GetFirstVideoContent(desc->description());
1062 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001063 if (video_content->rejected) {
1064 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1065 } else {
1066 const cricket::VideoContentDescription* video_desc =
1067 static_cast<const cricket::VideoContentDescription*>(
1068 video_content->description);
1069 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1070 }
deadbeefab9b2d12015-10-14 11:33:11 -07001071 }
1072
1073 const cricket::ContentInfo* data_content =
1074 GetFirstDataContent(desc->description());
1075 if (data_content) {
1076 const cricket::DataContentDescription* data_desc =
1077 static_cast<const cricket::DataContentDescription*>(
1078 data_content->description);
1079 if (rtc::starts_with(data_desc->protocol().data(),
1080 cricket::kMediaProtocolRtpPrefix)) {
1081 UpdateLocalRtpDataChannels(data_desc->streams());
1082 }
1083 }
1084
1085 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001087
deadbeefcbecd352015-09-23 11:50:27 -07001088 // MaybeStartGathering needs to be called after posting
1089 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1090 // before signaling that SetLocalDescription completed.
1091 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092}
1093
1094void PeerConnection::SetRemoteDescription(
1095 SetSessionDescriptionObserver* observer,
1096 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -07001097 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1099 return;
1100 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 if (!desc) {
1102 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1103 return;
1104 }
1105 // Update stats here so that we have the most recent stats for tracks and
1106 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001107 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108 std::string error;
1109 if (!session_->SetRemoteDescription(desc, &error)) {
1110 PostSetSessionDescriptionFailure(observer, error);
1111 return;
1112 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001113
deadbeefab9b2d12015-10-14 11:33:11 -07001114 // If setting the description decided our SSL role, allocate any necessary
1115 // SCTP sids.
1116 rtc::SSLRole role;
1117 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1118 session_->GetSslRole(&role)) {
1119 AllocateSctpSids(role);
1120 }
1121
1122 const cricket::SessionDescription* remote_desc = desc->description();
1123
1124 // We wait to signal new streams until we finish processing the description,
1125 // since only at that point will new streams have all their tracks.
1126 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1127
1128 // Find all audio rtp streams and create corresponding remote AudioTracks
1129 // and MediaStreams.
1130 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1131 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001132 if (audio_content->rejected) {
1133 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1134 } else {
1135 const cricket::AudioContentDescription* desc =
1136 static_cast<const cricket::AudioContentDescription*>(
1137 audio_content->description);
1138 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(),
1139 new_streams);
1140 remote_info_.default_audio_track_needed =
1141 !remote_desc->msid_supported() && desc->streams().empty() &&
1142 MediaContentDirectionHasSend(desc->direction());
1143 }
deadbeefab9b2d12015-10-14 11:33:11 -07001144 }
1145
1146 // Find all video rtp streams and create corresponding remote VideoTracks
1147 // and MediaStreams.
1148 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1149 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001150 if (video_content->rejected) {
1151 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1152 } else {
1153 const cricket::VideoContentDescription* desc =
1154 static_cast<const cricket::VideoContentDescription*>(
1155 video_content->description);
1156 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(),
1157 new_streams);
1158 remote_info_.default_video_track_needed =
1159 !remote_desc->msid_supported() && desc->streams().empty() &&
1160 MediaContentDirectionHasSend(desc->direction());
1161 }
deadbeefab9b2d12015-10-14 11:33:11 -07001162 }
1163
1164 // Update the DataChannels with the information from the remote peer.
1165 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
1166 if (data_content) {
deadbeef5e97fb52015-10-15 12:49:08 -07001167 const cricket::DataContentDescription* desc =
deadbeefab9b2d12015-10-14 11:33:11 -07001168 static_cast<const cricket::DataContentDescription*>(
1169 data_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001170 if (rtc::starts_with(desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001171 cricket::kMediaProtocolRtpPrefix)) {
deadbeef5e97fb52015-10-15 12:49:08 -07001172 UpdateRemoteRtpDataChannels(GetActiveStreams(desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001173 }
1174 }
1175
1176 // Iterate new_streams and notify the observer about new MediaStreams.
1177 for (size_t i = 0; i < new_streams->count(); ++i) {
1178 MediaStreamInterface* new_stream = new_streams->at(i);
1179 stats_->AddStream(new_stream);
1180 observer_->OnAddStream(new_stream);
1181 }
1182
1183 // Find removed MediaStreams.
1184 if (remote_info_.IsDefaultMediaStreamNeeded() &&
1185 remote_streams_->find(kDefaultStreamLabel) != nullptr) {
1186 // The default media stream already exists. No need to do anything.
1187 } else {
1188 UpdateEndedRemoteMediaStreams();
1189 remote_info_.msid_supported |= remote_streams_->count() > 0;
1190 }
1191 MaybeCreateDefaultStream();
1192
1193 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1194 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001195}
1196
deadbeefa67696b2015-09-29 11:56:26 -07001197bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001198 if (port_allocator_) {
1199 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1200 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1201 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1202 return false;
1203 }
1204
deadbeef653b8e02015-11-11 12:55:10 -08001205 cricket::ServerAddresses cricket_stuns;
1206 std::vector<cricket::RelayServerConfig> cricket_turns;
1207 ConvertToCricketIceServers(stuns, turns, &cricket_stuns, &cricket_turns);
1208 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001209 }
honghaiz1f429e32015-09-28 07:57:34 -07001210 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001211 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001212}
1213
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214bool PeerConnection::AddIceCandidate(
1215 const IceCandidateInterface* ice_candidate) {
1216 return session_->ProcessIceMessage(ice_candidate);
1217}
1218
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001219void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
1220 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001221
1222 if (session_) {
1223 session_->set_metrics_observer(uma_observer_);
1224 }
1225
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001226 // Send information about IPv4/IPv6 status.
1227 if (uma_observer_ && port_allocator_) {
1228 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001229 uma_observer_->IncrementEnumCounter(
1230 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1231 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001232 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001233 uma_observer_->IncrementEnumCounter(
1234 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1235 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001236 }
1237 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001238}
1239
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001240const SessionDescriptionInterface* PeerConnection::local_description() const {
1241 return session_->local_description();
1242}
1243
1244const SessionDescriptionInterface* PeerConnection::remote_description() const {
1245 return session_->remote_description();
1246}
1247
1248void PeerConnection::Close() {
1249 // Update stats here so that we have the most recent stats for tracks and
1250 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001251 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001252
deadbeefd59daf82015-10-14 15:02:44 -07001253 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001254}
1255
deadbeefd59daf82015-10-14 15:02:44 -07001256void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1257 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001259 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001261 break;
deadbeefd59daf82015-10-14 15:02:44 -07001262 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1264 break;
deadbeefd59daf82015-10-14 15:02:44 -07001265 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1267 break;
deadbeefd59daf82015-10-14 15:02:44 -07001268 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001269 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1270 break;
deadbeefd59daf82015-10-14 15:02:44 -07001271 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1273 break;
deadbeefd59daf82015-10-14 15:02:44 -07001274 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001275 ChangeSignalingState(PeerConnectionInterface::kStable);
1276 break;
deadbeefd59daf82015-10-14 15:02:44 -07001277 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 ChangeSignalingState(PeerConnectionInterface::kClosed);
1279 break;
1280 default:
1281 break;
1282 }
1283}
1284
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001285void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1288 SetSessionDescriptionMsg* param =
1289 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1290 param->observer->OnSuccess();
1291 delete param;
1292 break;
1293 }
1294 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1295 SetSessionDescriptionMsg* param =
1296 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1297 param->observer->OnFailure(param->error);
1298 delete param;
1299 break;
1300 }
deadbeefab9b2d12015-10-14 11:33:11 -07001301 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1302 CreateSessionDescriptionMsg* param =
1303 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1304 param->observer->OnFailure(param->error);
1305 delete param;
1306 break;
1307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 case MSG_GETSTATS: {
1309 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001310 StatsReports reports;
1311 stats_->GetStats(param->track, &reports);
1312 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313 delete param;
1314 break;
1315 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001317 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318 break;
1319 }
1320}
1321
deadbeefab9b2d12015-10-14 11:33:11 -07001322void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1323 AudioTrackInterface* audio_track,
1324 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001325 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326}
1327
deadbeefab9b2d12015-10-14 11:33:11 -07001328void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1329 VideoTrackInterface* video_track,
1330 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001331 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332}
1333
deadbeef70ab1a12015-09-28 16:53:55 -07001334// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1335// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001336void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1337 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001338 auto it = FindReceiverForTrack(audio_track);
1339 if (it == receivers_.end()) {
1340 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1341 << " doesn't exist.";
1342 } else {
1343 (*it)->Stop();
1344 receivers_.erase(it);
1345 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346}
1347
deadbeefab9b2d12015-10-14 11:33:11 -07001348void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1349 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001350 auto it = FindReceiverForTrack(video_track);
1351 if (it == receivers_.end()) {
1352 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1353 << " doesn't exist.";
1354 } else {
1355 (*it)->Stop();
1356 receivers_.erase(it);
1357 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358}
deadbeef70ab1a12015-09-28 16:53:55 -07001359
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360void PeerConnection::OnIceConnectionChange(
1361 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001362 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001363 // After transitioning to "closed", ignore any additional states from
1364 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001365 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001366 return;
1367 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001369 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
1372void PeerConnection::OnIceGatheringChange(
1373 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001374 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 if (IsClosed()) {
1376 return;
1377 }
1378 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001379 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380}
1381
1382void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001383 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001384 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385}
1386
1387void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001388 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001389 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390}
1391
Peter Thatcher54360512015-07-08 11:08:35 -07001392void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001393 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001394 observer_->OnIceConnectionReceivingChange(receiving);
1395}
1396
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001397void PeerConnection::ChangeSignalingState(
1398 PeerConnectionInterface::SignalingState signaling_state) {
1399 signaling_state_ = signaling_state;
1400 if (signaling_state == kClosed) {
1401 ice_connection_state_ = kIceConnectionClosed;
1402 observer_->OnIceConnectionChange(ice_connection_state_);
1403 if (ice_gathering_state_ != kIceGatheringComplete) {
1404 ice_gathering_state_ = kIceGatheringComplete;
1405 observer_->OnIceGatheringChange(ice_gathering_state_);
1406 }
1407 }
1408 observer_->OnSignalingChange(signaling_state_);
1409 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1410}
1411
deadbeefab9b2d12015-10-14 11:33:11 -07001412void PeerConnection::PostSetSessionDescriptionFailure(
1413 SetSessionDescriptionObserver* observer,
1414 const std::string& error) {
1415 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1416 msg->error = error;
1417 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1418}
1419
1420void PeerConnection::PostCreateSessionDescriptionFailure(
1421 CreateSessionDescriptionObserver* observer,
1422 const std::string& error) {
1423 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1424 msg->error = error;
1425 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1426}
1427
1428bool PeerConnection::GetOptionsForOffer(
1429 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1430 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001431 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1432 return false;
1433 }
1434
deadbeeffac06552015-11-25 11:26:01 -08001435 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001436 // Offer to receive audio/video if the constraint is not set and there are
1437 // send streams, or we're currently receiving.
1438 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1439 session_options->recv_audio =
1440 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1441 !remote_audio_tracks_.empty();
1442 }
1443 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1444 session_options->recv_video =
1445 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1446 !remote_video_tracks_.empty();
1447 }
1448 session_options->bundle_enabled =
1449 session_options->bundle_enabled &&
1450 (session_options->has_audio() || session_options->has_video() ||
1451 session_options->has_data());
1452
deadbeefab9b2d12015-10-14 11:33:11 -07001453 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1454 session_options->data_channel_type = cricket::DCT_SCTP;
1455 }
1456 return true;
1457}
1458
1459bool PeerConnection::GetOptionsForAnswer(
1460 const MediaConstraintsInterface* constraints,
1461 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001462 session_options->recv_audio = false;
1463 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001464 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1465 return false;
1466 }
1467
deadbeeffac06552015-11-25 11:26:01 -08001468 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001469 session_options->bundle_enabled =
1470 session_options->bundle_enabled &&
1471 (session_options->has_audio() || session_options->has_video() ||
1472 session_options->has_data());
1473
deadbeefab9b2d12015-10-14 11:33:11 -07001474 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1475 // are not signaled in the SDP so does not go through that path and must be
1476 // handled here.
1477 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1478 session_options->data_channel_type = cricket::DCT_SCTP;
1479 }
1480 return true;
1481}
1482
deadbeeffaac4972015-11-12 15:33:07 -08001483void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1484 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
1485 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), media_type,
1486 nullptr);
1487}
1488
deadbeefab9b2d12015-10-14 11:33:11 -07001489void PeerConnection::UpdateRemoteStreamsList(
1490 const cricket::StreamParamsVec& streams,
1491 cricket::MediaType media_type,
1492 StreamCollection* new_streams) {
1493 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1494
1495 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001496 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001497 auto track_it = current_tracks->begin();
1498 while (track_it != current_tracks->end()) {
1499 const TrackInfo& info = *track_it;
1500 const cricket::StreamParams* params =
1501 cricket::GetStreamBySsrc(streams, info.ssrc);
1502 if (!params || params->id != info.track_id) {
1503 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1504 track_it = current_tracks->erase(track_it);
1505 } else {
1506 ++track_it;
1507 }
1508 }
1509
1510 // Find new and active tracks.
1511 for (const cricket::StreamParams& params : streams) {
1512 // The sync_label is the MediaStream label and the |stream.id| is the
1513 // track id.
1514 const std::string& stream_label = params.sync_label;
1515 const std::string& track_id = params.id;
1516 uint32_t ssrc = params.first_ssrc();
1517
1518 rtc::scoped_refptr<MediaStreamInterface> stream =
1519 remote_streams_->find(stream_label);
1520 if (!stream) {
1521 // This is a new MediaStream. Create a new remote MediaStream.
1522 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1523 remote_streams_->AddStream(stream);
1524 new_streams->AddStream(stream);
1525 }
1526
1527 const TrackInfo* track_info =
1528 FindTrackInfo(*current_tracks, stream_label, track_id);
1529 if (!track_info) {
1530 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1531 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1532 }
1533 }
1534}
1535
1536void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1537 const std::string& track_id,
1538 uint32_t ssrc,
1539 cricket::MediaType media_type) {
1540 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1541
1542 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1543 AudioTrackInterface* audio_track =
1544 remote_stream_factory_->AddAudioTrack(stream, track_id);
1545 CreateAudioReceiver(stream, audio_track, ssrc);
1546 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1547 VideoTrackInterface* video_track =
1548 remote_stream_factory_->AddVideoTrack(stream, track_id);
1549 CreateVideoReceiver(stream, video_track, ssrc);
1550 } else {
1551 RTC_DCHECK(false && "Invalid media type");
1552 }
1553}
1554
1555void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1556 const std::string& track_id,
1557 cricket::MediaType media_type) {
1558 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1559
1560 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1561 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1562 stream->FindAudioTrack(track_id);
1563 if (audio_track) {
1564 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1565 stream->RemoveTrack(audio_track);
1566 DestroyAudioReceiver(stream, audio_track);
1567 }
1568 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1569 rtc::scoped_refptr<VideoTrackInterface> video_track =
1570 stream->FindVideoTrack(track_id);
1571 if (video_track) {
1572 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1573 stream->RemoveTrack(video_track);
1574 DestroyVideoReceiver(stream, video_track);
1575 }
1576 } else {
1577 ASSERT(false && "Invalid media type");
1578 }
1579}
1580
1581void PeerConnection::UpdateEndedRemoteMediaStreams() {
1582 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1583 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1584 MediaStreamInterface* stream = remote_streams_->at(i);
1585 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1586 streams_to_remove.push_back(stream);
1587 }
1588 }
1589
1590 for (const auto& stream : streams_to_remove) {
1591 remote_streams_->RemoveStream(stream);
1592 observer_->OnRemoveStream(stream);
1593 }
1594}
1595
1596void PeerConnection::MaybeCreateDefaultStream() {
1597 if (!remote_info_.IsDefaultMediaStreamNeeded()) {
1598 return;
1599 }
1600
1601 bool default_created = false;
1602
1603 rtc::scoped_refptr<MediaStreamInterface> default_remote_stream =
1604 remote_streams_->find(kDefaultStreamLabel);
1605 if (default_remote_stream == nullptr) {
1606 default_created = true;
1607 default_remote_stream =
1608 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1609 remote_streams_->AddStream(default_remote_stream);
1610 }
1611 if (remote_info_.default_audio_track_needed &&
1612 default_remote_stream->GetAudioTracks().size() == 0) {
1613 remote_audio_tracks_.push_back(
1614 TrackInfo(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0));
1615 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
1616 cricket::MEDIA_TYPE_AUDIO);
1617 }
1618 if (remote_info_.default_video_track_needed &&
1619 default_remote_stream->GetVideoTracks().size() == 0) {
1620 remote_video_tracks_.push_back(
1621 TrackInfo(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0));
1622 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
1623 cricket::MEDIA_TYPE_VIDEO);
1624 }
1625 if (default_created) {
1626 stats_->AddStream(default_remote_stream);
1627 observer_->OnAddStream(default_remote_stream);
1628 }
1629}
1630
1631void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1632 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1633 for (TrackInfos::iterator track_it = current_tracks->begin();
1634 track_it != current_tracks->end(); ++track_it) {
1635 const TrackInfo& info = *track_it;
1636 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1637 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1638 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1639 // There's no guarantee the track is still available, e.g. the track may
1640 // have been removed from the stream by javascript.
1641 if (track) {
1642 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1643 }
1644 }
1645 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1646 VideoTrackInterface* track = stream->FindVideoTrack(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 }
1654}
1655
1656void PeerConnection::UpdateLocalTracks(
1657 const std::vector<cricket::StreamParams>& streams,
1658 cricket::MediaType media_type) {
1659 TrackInfos* current_tracks = GetLocalTracks(media_type);
1660
1661 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1662 // don't match the new StreamParam.
1663 TrackInfos::iterator track_it = current_tracks->begin();
1664 while (track_it != current_tracks->end()) {
1665 const TrackInfo& info = *track_it;
1666 const cricket::StreamParams* params =
1667 cricket::GetStreamBySsrc(streams, info.ssrc);
1668 if (!params || params->id != info.track_id ||
1669 params->sync_label != info.stream_label) {
1670 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1671 media_type);
1672 track_it = current_tracks->erase(track_it);
1673 } else {
1674 ++track_it;
1675 }
1676 }
1677
1678 // Find new and active tracks.
1679 for (const cricket::StreamParams& params : streams) {
1680 // The sync_label is the MediaStream label and the |stream.id| is the
1681 // track id.
1682 const std::string& stream_label = params.sync_label;
1683 const std::string& track_id = params.id;
1684 uint32_t ssrc = params.first_ssrc();
1685 const TrackInfo* track_info =
1686 FindTrackInfo(*current_tracks, stream_label, track_id);
1687 if (!track_info) {
1688 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1689 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1690 }
1691 }
1692}
1693
1694void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1695 const std::string& track_id,
1696 uint32_t ssrc,
1697 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001698 RtpSenderInterface* sender = FindSenderById(track_id);
1699 if (!sender) {
1700 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1701 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001702 return;
1703 }
1704
deadbeeffac06552015-11-25 11:26:01 -08001705 if (sender->media_type() != media_type) {
1706 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1707 << " description with an unexpected media type.";
1708 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001709 }
deadbeeffac06552015-11-25 11:26:01 -08001710
1711 sender->set_stream_id(stream_label);
1712 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001713}
1714
1715void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1716 const std::string& track_id,
1717 uint32_t ssrc,
1718 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001719 RtpSenderInterface* sender = FindSenderById(track_id);
1720 if (!sender) {
1721 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001722 // SessionDescriptions has been renegotiated.
1723 return;
1724 }
deadbeeffac06552015-11-25 11:26:01 -08001725
1726 // A sender has been removed from the SessionDescription but it's still
1727 // associated with the PeerConnection. This only occurs if the SDP doesn't
1728 // match with the calls to CreateSender, AddStream and RemoveStream.
1729 if (sender->media_type() != media_type) {
1730 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1731 << " description with an unexpected media type.";
1732 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001733 }
deadbeeffac06552015-11-25 11:26:01 -08001734
1735 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001736}
1737
1738void PeerConnection::UpdateLocalRtpDataChannels(
1739 const cricket::StreamParamsVec& streams) {
1740 std::vector<std::string> existing_channels;
1741
1742 // Find new and active data channels.
1743 for (const cricket::StreamParams& params : streams) {
1744 // |it->sync_label| is actually the data channel label. The reason is that
1745 // we use the same naming of data channels as we do for
1746 // MediaStreams and Tracks.
1747 // For MediaStreams, the sync_label is the MediaStream label and the
1748 // track label is the same as |streamid|.
1749 const std::string& channel_label = params.sync_label;
1750 auto data_channel_it = rtp_data_channels_.find(channel_label);
1751 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1752 continue;
1753 }
1754 // Set the SSRC the data channel should use for sending.
1755 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1756 existing_channels.push_back(data_channel_it->first);
1757 }
1758
1759 UpdateClosingRtpDataChannels(existing_channels, true);
1760}
1761
1762void PeerConnection::UpdateRemoteRtpDataChannels(
1763 const cricket::StreamParamsVec& streams) {
1764 std::vector<std::string> existing_channels;
1765
1766 // Find new and active data channels.
1767 for (const cricket::StreamParams& params : streams) {
1768 // The data channel label is either the mslabel or the SSRC if the mslabel
1769 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1770 std::string label = params.sync_label.empty()
1771 ? rtc::ToString(params.first_ssrc())
1772 : params.sync_label;
1773 auto data_channel_it = rtp_data_channels_.find(label);
1774 if (data_channel_it == rtp_data_channels_.end()) {
1775 // This is a new data channel.
1776 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1777 } else {
1778 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1779 }
1780 existing_channels.push_back(label);
1781 }
1782
1783 UpdateClosingRtpDataChannels(existing_channels, false);
1784}
1785
1786void PeerConnection::UpdateClosingRtpDataChannels(
1787 const std::vector<std::string>& active_channels,
1788 bool is_local_update) {
1789 auto it = rtp_data_channels_.begin();
1790 while (it != rtp_data_channels_.end()) {
1791 DataChannel* data_channel = it->second;
1792 if (std::find(active_channels.begin(), active_channels.end(),
1793 data_channel->label()) != active_channels.end()) {
1794 ++it;
1795 continue;
1796 }
1797
1798 if (is_local_update) {
1799 data_channel->SetSendSsrc(0);
1800 } else {
1801 data_channel->RemotePeerRequestClose();
1802 }
1803
1804 if (data_channel->state() == DataChannel::kClosed) {
1805 rtp_data_channels_.erase(it);
1806 it = rtp_data_channels_.begin();
1807 } else {
1808 ++it;
1809 }
1810 }
1811}
1812
1813void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1814 uint32_t remote_ssrc) {
1815 rtc::scoped_refptr<DataChannel> channel(
1816 InternalCreateDataChannel(label, nullptr));
1817 if (!channel.get()) {
1818 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1819 << "CreateDataChannel failed.";
1820 return;
1821 }
1822 channel->SetReceiveSsrc(remote_ssrc);
1823 observer_->OnDataChannel(
1824 DataChannelProxy::Create(signaling_thread(), channel));
1825}
1826
1827rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1828 const std::string& label,
1829 const InternalDataChannelInit* config) {
1830 if (IsClosed()) {
1831 return nullptr;
1832 }
1833 if (session_->data_channel_type() == cricket::DCT_NONE) {
1834 LOG(LS_ERROR)
1835 << "InternalCreateDataChannel: Data is not supported in this call.";
1836 return nullptr;
1837 }
1838 InternalDataChannelInit new_config =
1839 config ? (*config) : InternalDataChannelInit();
1840 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1841 if (new_config.id < 0) {
1842 rtc::SSLRole role;
1843 if (session_->GetSslRole(&role) &&
1844 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1845 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1846 return nullptr;
1847 }
1848 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1849 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1850 << "because the id is already in use or out of range.";
1851 return nullptr;
1852 }
1853 }
1854
1855 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1856 session_.get(), session_->data_channel_type(), label, new_config));
1857 if (!channel) {
1858 sid_allocator_.ReleaseSid(new_config.id);
1859 return nullptr;
1860 }
1861
1862 if (channel->data_channel_type() == cricket::DCT_RTP) {
1863 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1864 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1865 << " already exists.";
1866 return nullptr;
1867 }
1868 rtp_data_channels_[channel->label()] = channel;
1869 } else {
1870 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1871 sctp_data_channels_.push_back(channel);
1872 channel->SignalClosed.connect(this,
1873 &PeerConnection::OnSctpDataChannelClosed);
1874 }
1875
1876 return channel;
1877}
1878
1879bool PeerConnection::HasDataChannels() const {
1880 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1881}
1882
1883void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1884 for (const auto& channel : sctp_data_channels_) {
1885 if (channel->id() < 0) {
1886 int sid;
1887 if (!sid_allocator_.AllocateSid(role, &sid)) {
1888 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1889 continue;
1890 }
1891 channel->SetSctpSid(sid);
1892 }
1893 }
1894}
1895
1896void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1897 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1898 ++it) {
1899 if (it->get() == channel) {
1900 if (channel->id() >= 0) {
1901 sid_allocator_.ReleaseSid(channel->id());
1902 }
1903 sctp_data_channels_.erase(it);
1904 return;
1905 }
1906 }
1907}
1908
1909void PeerConnection::OnVoiceChannelDestroyed() {
1910 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1911}
1912
1913void PeerConnection::OnVideoChannelDestroyed() {
1914 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1915}
1916
1917void PeerConnection::OnDataChannelCreated() {
1918 for (const auto& channel : sctp_data_channels_) {
1919 channel->OnTransportChannelCreated();
1920 }
1921}
1922
1923void PeerConnection::OnDataChannelDestroyed() {
1924 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1925 // DataChannel may callback to us and try to modify the list.
1926 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1927 temp_rtp_dcs.swap(rtp_data_channels_);
1928 for (const auto& kv : temp_rtp_dcs) {
1929 kv.second->OnTransportChannelDestroyed();
1930 }
1931
1932 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1933 temp_sctp_dcs.swap(sctp_data_channels_);
1934 for (const auto& channel : temp_sctp_dcs) {
1935 channel->OnTransportChannelDestroyed();
1936 }
1937}
1938
1939void PeerConnection::OnDataChannelOpenMessage(
1940 const std::string& label,
1941 const InternalDataChannelInit& config) {
1942 rtc::scoped_refptr<DataChannel> channel(
1943 InternalCreateDataChannel(label, &config));
1944 if (!channel.get()) {
1945 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1946 return;
1947 }
1948
1949 observer_->OnDataChannel(
1950 DataChannelProxy::Create(signaling_thread(), channel));
1951}
1952
deadbeeffac06552015-11-25 11:26:01 -08001953RtpSenderInterface* PeerConnection::FindSenderById(const std::string& id) {
1954 auto it =
1955 std::find_if(senders_.begin(), senders_.end(),
1956 [id](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1957 return sender->id() == id;
1958 });
1959 return it != senders_.end() ? it->get() : nullptr;
1960}
1961
deadbeef70ab1a12015-09-28 16:53:55 -07001962std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1963PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1964 return std::find_if(
1965 senders_.begin(), senders_.end(),
1966 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1967 return sender->track() == track;
1968 });
1969}
1970
1971std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1972PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1973 return std::find_if(
1974 receivers_.begin(), receivers_.end(),
1975 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1976 return receiver->track() == track;
1977 });
1978}
1979
deadbeefab9b2d12015-10-14 11:33:11 -07001980PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1981 cricket::MediaType media_type) {
1982 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1983 media_type == cricket::MEDIA_TYPE_VIDEO);
1984 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1985 : &remote_video_tracks_;
1986}
1987
1988PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
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) ? &local_audio_tracks_
1993 : &local_video_tracks_;
1994}
1995
1996const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
1997 const PeerConnection::TrackInfos& infos,
1998 const std::string& stream_label,
1999 const std::string track_id) const {
2000 for (const TrackInfo& track_info : infos) {
2001 if (track_info.stream_label == stream_label &&
2002 track_info.track_id == track_id) {
2003 return &track_info;
2004 }
2005 }
2006 return nullptr;
2007}
2008
2009DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2010 for (const auto& channel : sctp_data_channels_) {
2011 if (channel->id() == sid) {
2012 return channel;
2013 }
2014 }
2015 return nullptr;
2016}
2017
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002018} // namespace webrtc