blob: 83e29191c8a2ac1b5003e5f684d7755250f11dec [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"
Tommif888bb52015-12-12 01:37:01 +010042#include "talk/app/webrtc/remoteaudiotrack.h"
deadbeefab9b2d12015-10-14 11:33:11 -070043#include "talk/app/webrtc/remotevideocapturer.h"
deadbeef70ab1a12015-09-28 16:53:55 -070044#include "talk/app/webrtc/rtpreceiver.h"
45#include "talk/app/webrtc/rtpsender.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000046#include "talk/app/webrtc/streamcollection.h"
deadbeefab9b2d12015-10-14 11:33:11 -070047#include "talk/app/webrtc/videosource.h"
48#include "talk/app/webrtc/videotrack.h"
49#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050#include "talk/session/media/channelmanager.h"
tfarina5237aaf2015-11-10 23:44:30 -080051#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000052#include "webrtc/base/logging.h"
53#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070054#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010055#include "webrtc/base/trace_event.h"
tfarina5237aaf2015-11-10 23:44:30 -080056#include "webrtc/p2p/client/basicportallocator.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010057#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
59namespace {
60
deadbeefab9b2d12015-10-14 11:33:11 -070061using webrtc::DataChannel;
62using webrtc::MediaConstraintsInterface;
63using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064using webrtc::PeerConnectionInterface;
deadbeeffac06552015-11-25 11:26:01 -080065using webrtc::RtpSenderInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070066using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070067using webrtc::StunConfigurations;
68using webrtc::TurnConfigurations;
69typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
70 StunConfiguration;
71typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
72 TurnConfiguration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073
deadbeefab9b2d12015-10-14 11:33:11 -070074static const char kDefaultStreamLabel[] = "default";
75static const char kDefaultAudioTrackLabel[] = "defaulta0";
76static const char kDefaultVideoTrackLabel[] = "defaultv0";
77
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078// The min number of tokens must present in Turn host uri.
79// e.g. user@turn.example.org
80static const size_t kTurnHostTokensNum = 2;
81// Number of tokens must be preset when TURN uri has transport param.
82static const size_t kTurnTransportTokensNum = 2;
83// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000084static const int kDefaultStunPort = 3478;
85static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000087static const char kUdpTransportType[] = "udp";
88static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089
90// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070091static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
deadbeef0a6c4ca2015-10-06 11:38:28 -070093// NOTE: A loop below assumes that the first value of this enum is 0 and all
94// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070096 STUN = 0, // Indicates a STUN server.
97 STUNS, // Indicates a STUN server used with a TLS session.
98 TURN, // Indicates a TURN server
99 TURNS, // Indicates a TURN server used with a TLS session.
100 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101};
tfarina5237aaf2015-11-10 23:44:30 -0800102static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -0700103 "kValidIceServiceTypes must have as many strings as ServiceType "
104 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105
106enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000107 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700109 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 MSG_GETSTATS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111};
112
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000113struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114 explicit SetSessionDescriptionMsg(
115 webrtc::SetSessionDescriptionObserver* observer)
116 : observer(observer) {
117 }
118
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000119 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000120 std::string error;
121};
122
deadbeefab9b2d12015-10-14 11:33:11 -0700123struct CreateSessionDescriptionMsg : public rtc::MessageData {
124 explicit CreateSessionDescriptionMsg(
125 webrtc::CreateSessionDescriptionObserver* observer)
126 : observer(observer) {}
127
128 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
129 std::string error;
130};
131
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000133 GetStatsMsg(webrtc::StatsObserver* observer,
134 webrtc::MediaStreamTrackInterface* track)
135 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139};
140
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000141// |in_str| should be of format
142// stunURI = scheme ":" stun-host [ ":" stun-port ]
143// scheme = "stun" / "stuns"
144// stun-host = IP-literal / IPv4address / reg-name
145// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700146//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000147// draft-petithuguenin-behave-turn-uris-01
148// turnURI = scheme ":" turn-host [ ":" turn-port ]
149// turn-host = username@IP-literal / IPv4address / reg-name
150bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
151 ServiceType* service_type,
152 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200153 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700154 if (colonpos == std::string::npos) {
155 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000156 return false;
157 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700158 if ((colonpos + 1) == in_str.length()) {
159 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
160 return false;
161 }
162 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800163 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700164 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000165 *service_type = static_cast<ServiceType>(i);
166 break;
167 }
168 }
169 if (*service_type == INVALID) {
170 return false;
171 }
172 *hostname = in_str.substr(colonpos + 1, std::string::npos);
173 return true;
174}
175
deadbeef0a6c4ca2015-10-06 11:38:28 -0700176bool ParsePort(const std::string& in_str, int* port) {
177 // Make sure port only contains digits. FromString doesn't check this.
178 for (const char& c : in_str) {
179 if (!std::isdigit(c)) {
180 return false;
181 }
182 }
183 return rtc::FromString(in_str, port);
184}
185
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000186// This method parses IPv6 and IPv4 literal strings, along with hostnames in
187// standard hostname:port format.
188// Consider following formats as correct.
189// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700190// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000191bool ParseHostnameAndPortFromString(const std::string& in_str,
192 std::string* host,
193 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700194 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000195 if (in_str.at(0) == '[') {
196 std::string::size_type closebracket = in_str.rfind(']');
197 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000198 std::string::size_type colonpos = in_str.find(':', closebracket);
199 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700200 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
201 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 return false;
203 }
204 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700205 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000206 } else {
207 return false;
208 }
209 } else {
210 std::string::size_type colonpos = in_str.find(':');
211 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700212 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000213 return false;
214 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700215 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000216 } else {
217 *host = in_str;
218 }
219 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700220 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000221}
222
deadbeef0a6c4ca2015-10-06 11:38:28 -0700223// Adds a StunConfiguration or TurnConfiguration to the appropriate list,
224// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200225bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
226 const std::string& url,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700227 StunConfigurations* stun_config,
228 TurnConfigurations* turn_config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229 // draft-nandakumar-rtcweb-stun-uri-01
230 // stunURI = scheme ":" stun-host [ ":" stun-port ]
231 // scheme = "stun" / "stuns"
232 // stun-host = IP-literal / IPv4address / reg-name
233 // stun-port = *DIGIT
234
235 // draft-petithuguenin-behave-turn-uris-01
236 // turnURI = scheme ":" turn-host [ ":" turn-port ]
237 // [ "?transport=" transport ]
238 // scheme = "turn" / "turns"
239 // transport = "udp" / "tcp" / transport-ext
240 // transport-ext = 1*unreserved
241 // turn-host = IP-literal / IPv4address / reg-name
242 // turn-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700243 RTC_DCHECK(stun_config != nullptr);
244 RTC_DCHECK(turn_config != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200245 std::vector<std::string> tokens;
246 std::string turn_transport_type = kUdpTransportType;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700247 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200248 rtc::tokenize(url, '?', &tokens);
249 std::string uri_without_transport = tokens[0];
250 // Let's look into transport= param, if it exists.
251 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
252 std::string uri_transport_param = tokens[1];
253 rtc::tokenize(uri_transport_param, '=', &tokens);
254 if (tokens[0] == kTransport) {
255 // As per above grammar transport param will be consist of lower case
256 // letters.
257 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
258 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700259 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200261 turn_transport_type = tokens[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200263 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200265 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700266 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200267 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
268 &service_type,
269 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
271 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200272 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000273
deadbeef0a6c4ca2015-10-06 11:38:28 -0700274 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
275 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200276
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200277 // Let's break hostname.
278 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700279 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
280
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200281 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700282 if (tokens.size() > kTurnHostTokensNum) {
283 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
284 return false;
285 }
286 if (tokens.size() == kTurnHostTokensNum) {
287 if (tokens[0].empty() || tokens[1].empty()) {
288 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
289 return false;
290 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200291 username.assign(rtc::s_url_decode(tokens[0]));
292 hoststring = tokens[1];
293 } else {
294 hoststring = tokens[0];
295 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000296
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 int port = kDefaultStunPort;
298 if (service_type == TURNS) {
299 port = kDefaultStunTlsPort;
300 turn_transport_type = kTcpTransportType;
301 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000302
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200303 std::string address;
304 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700305 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
306 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200307 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000308
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200309 if (port <= 0 || port > 0xffff) {
310 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700311 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200312 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000313
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200314 switch (service_type) {
315 case STUN:
316 case STUNS:
317 stun_config->push_back(StunConfiguration(address, port));
318 break;
319 case TURN:
320 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200321 bool secure = (service_type == TURNS);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200322 turn_config->push_back(TurnConfiguration(address, port,
323 username,
324 server.password,
325 turn_transport_type,
326 secure));
327 break;
328 }
329 case INVALID:
330 default:
331 LOG(WARNING) << "Configuration not supported: " << url;
332 return false;
333 }
334 return true;
335}
336
deadbeef653b8e02015-11-11 12:55:10 -0800337void ConvertToCricketIceServers(
338 const std::vector<StunConfiguration>& stuns,
339 const std::vector<TurnConfiguration>& turns,
340 cricket::ServerAddresses* cricket_stuns,
341 std::vector<cricket::RelayServerConfig>* cricket_turns) {
342 RTC_DCHECK(cricket_stuns && cricket_turns);
343 for (const StunConfiguration& stun : stuns) {
344 cricket_stuns->insert(stun.server);
345 }
346
347 int priority = static_cast<int>(turns.size() - 1);
348 for (const TurnConfiguration& turn : turns) {
349 cricket::RelayCredentials credentials(turn.username, turn.password);
350 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
351 cricket::ProtocolType protocol;
352 // Using VERIFY because ParseIceServers should have already caught an
353 // invalid transport type.
354 if (!VERIFY(
355 cricket::StringToProto(turn.transport_type.c_str(), &protocol))) {
356 LOG(LS_WARNING) << "Ignoring TURN server " << turn.server << ". "
357 << "Reason= Incorrect " << turn.transport_type
358 << " transport parameter.";
359 } else {
360 relay_server.ports.push_back(
361 cricket::ProtocolAddress(turn.server, protocol, turn.secure));
362 relay_server.credentials = credentials;
363 relay_server.priority = priority;
364 cricket_turns->push_back(relay_server);
365 }
366 // First in the list gets highest priority.
367 --priority;
368 }
369}
370
deadbeefab9b2d12015-10-14 11:33:11 -0700371// Check if we can send |new_stream| on a PeerConnection.
372bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
373 webrtc::MediaStreamInterface* new_stream) {
374 if (!new_stream || !current_streams) {
375 return false;
376 }
377 if (current_streams->find(new_stream->label()) != nullptr) {
378 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
379 << " is already added.";
380 return false;
381 }
382 return true;
383}
384
385bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
386 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
387}
388
deadbeef5e97fb52015-10-15 12:49:08 -0700389// If the direction is "recvonly" or "inactive", treat the description
390// as containing no streams.
391// See: https://code.google.com/p/webrtc/issues/detail?id=5054
392std::vector<cricket::StreamParams> GetActiveStreams(
393 const cricket::MediaContentDescription* desc) {
394 return MediaContentDirectionHasSend(desc->direction())
395 ? desc->streams()
396 : std::vector<cricket::StreamParams>();
397}
398
deadbeefab9b2d12015-10-14 11:33:11 -0700399bool IsValidOfferToReceiveMedia(int value) {
400 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
401 return (value >= Options::kUndefined) &&
402 (value <= Options::kMaxOfferToReceiveMedia);
403}
404
405// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800406void AddSendStreams(
407 cricket::MediaSessionOptions* session_options,
408 const std::vector<rtc::scoped_refptr<RtpSenderInterface>>& senders,
409 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
410 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700411 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800412 for (const auto& sender : senders) {
413 session_options->AddSendStream(sender->media_type(), sender->id(),
414 sender->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700415 }
416
417 // Check for data channels.
418 for (const auto& kv : rtp_data_channels) {
419 const DataChannel* channel = kv.second;
420 if (channel->state() == DataChannel::kConnecting ||
421 channel->state() == DataChannel::kOpen) {
422 // |streamid| and |sync_label| are both set to the DataChannel label
423 // here so they can be signaled the same way as MediaStreams and Tracks.
424 // For MediaStreams, the sync_label is the MediaStream label and the
425 // track label is the same as |streamid|.
426 const std::string& streamid = channel->label();
427 const std::string& sync_label = channel->label();
428 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
429 sync_label);
430 }
431 }
432}
433
deadbeef0a6c4ca2015-10-06 11:38:28 -0700434} // namespace
435
436namespace webrtc {
437
deadbeefab9b2d12015-10-14 11:33:11 -0700438// Factory class for creating remote MediaStreams and MediaStreamTracks.
439class RemoteMediaStreamFactory {
440 public:
441 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
442 cricket::ChannelManager* channel_manager)
443 : signaling_thread_(signaling_thread),
444 channel_manager_(channel_manager) {}
445
446 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
447 const std::string& stream_label) {
448 return MediaStreamProxy::Create(signaling_thread_,
449 MediaStream::Create(stream_label));
450 }
451
Tommif888bb52015-12-12 01:37:01 +0100452 AudioTrackInterface* AddAudioTrack(uint32_t ssrc,
453 AudioProviderInterface* provider,
454 webrtc::MediaStreamInterface* stream,
deadbeefab9b2d12015-10-14 11:33:11 -0700455 const std::string& track_id) {
Tommif888bb52015-12-12 01:37:01 +0100456 return AddTrack<AudioTrackInterface, RemoteAudioTrack, AudioTrackProxy>(
457 stream, track_id, RemoteAudioSource::Create(ssrc, provider));
deadbeefab9b2d12015-10-14 11:33:11 -0700458 }
459
460 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
461 const std::string& track_id) {
462 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
463 stream, track_id,
464 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
465 nullptr)
466 .get());
467 }
468
469 private:
470 template <typename TI, typename T, typename TP, typename S>
471 TI* AddTrack(MediaStreamInterface* stream,
472 const std::string& track_id,
Tommif888bb52015-12-12 01:37:01 +0100473 const S& source) {
deadbeefab9b2d12015-10-14 11:33:11 -0700474 rtc::scoped_refptr<TI> track(
475 TP::Create(signaling_thread_, T::Create(track_id, source)));
476 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
477 if (stream->AddTrack(track)) {
478 return track;
479 }
480 return nullptr;
481 }
482
483 rtc::Thread* signaling_thread_;
484 cricket::ChannelManager* channel_manager_;
485};
486
487bool ConvertRtcOptionsForOffer(
488 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
489 cricket::MediaSessionOptions* session_options) {
490 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
491 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
492 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
493 return false;
494 }
495
deadbeefc80741f2015-10-22 13:14:45 -0700496 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700497 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
498 }
deadbeefc80741f2015-10-22 13:14:45 -0700499 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700500 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
501 }
502
503 session_options->vad_enabled = rtc_options.voice_activity_detection;
504 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700505 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700506
507 return true;
508}
509
510bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
511 cricket::MediaSessionOptions* session_options) {
512 bool value = false;
513 size_t mandatory_constraints_satisfied = 0;
514
515 // kOfferToReceiveAudio defaults to true according to spec.
516 if (!FindConstraint(constraints,
517 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
518 &mandatory_constraints_satisfied) ||
519 value) {
520 session_options->recv_audio = true;
521 }
522
523 // kOfferToReceiveVideo defaults to false according to spec. But
524 // if it is an answer and video is offered, we should still accept video
525 // per default.
526 value = false;
527 if (!FindConstraint(constraints,
528 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
529 &mandatory_constraints_satisfied) ||
530 value) {
531 session_options->recv_video = true;
532 }
533
534 if (FindConstraint(constraints,
535 MediaConstraintsInterface::kVoiceActivityDetection, &value,
536 &mandatory_constraints_satisfied)) {
537 session_options->vad_enabled = value;
538 }
539
540 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
541 &mandatory_constraints_satisfied)) {
542 session_options->bundle_enabled = value;
543 } else {
544 // kUseRtpMux defaults to true according to spec.
545 session_options->bundle_enabled = true;
546 }
deadbeefab9b2d12015-10-14 11:33:11 -0700547
548 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
549 &value, &mandatory_constraints_satisfied)) {
550 session_options->transport_options.ice_restart = value;
551 } else {
552 // kIceRestart defaults to false according to spec.
553 session_options->transport_options.ice_restart = false;
554 }
555
556 if (!constraints) {
557 return true;
558 }
559 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
560}
561
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200562bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700563 StunConfigurations* stun_config,
564 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200565 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
566 if (!server.urls.empty()) {
567 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200568 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700569 LOG(LS_ERROR) << "Empty uri.";
570 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200571 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200572 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
573 return false;
574 }
575 }
576 } else if (!server.uri.empty()) {
577 // Fallback to old .uri if new .urls isn't present.
578 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200580 }
581 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700582 LOG(LS_ERROR) << "Empty uri.";
583 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000584 }
585 }
586 return true;
587}
588
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589PeerConnection::PeerConnection(PeerConnectionFactory* factory)
590 : factory_(factory),
591 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000592 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 signaling_state_(kStable),
594 ice_state_(kIceNew),
595 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700596 ice_gathering_state_(kIceGatheringNew),
597 local_streams_(StreamCollection::Create()),
598 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599
600PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100601 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700602 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700603 // Need to detach RTP senders/receivers from WebRtcSession,
604 // since it's about to be destroyed.
605 for (const auto& sender : senders_) {
606 sender->Stop();
607 }
608 for (const auto& receiver : receivers_) {
609 receiver->Stop();
610 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000611}
612
613bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000614 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000615 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000616 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200617 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000618 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700619 RTC_DCHECK(observer != nullptr);
620 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000621 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700622 }
deadbeef653b8e02015-11-11 12:55:10 -0800623
624 // This Initialize function parses ICE servers an extra time, but it will
625 // be removed once all PortAllocaotrs support SetIceServers.
626 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
627 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
628 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
629 return false;
630 }
631 rtc::scoped_ptr<cricket::PortAllocator> allocator(
632 allocator_factory->CreatePortAllocator(stun_config, turn_config));
633 return Initialize(configuration, constraints, allocator.Pass(),
634 dtls_identity_store.Pass(), observer);
635}
636
637bool PeerConnection::Initialize(
638 const PeerConnectionInterface::RTCConfiguration& configuration,
639 const MediaConstraintsInterface* constraints,
640 rtc::scoped_ptr<cricket::PortAllocator> allocator,
641 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
642 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100643 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800644 RTC_DCHECK(observer != nullptr);
645 if (!observer) {
646 return false;
647 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000648 observer_ = observer;
649
deadbeef653b8e02015-11-11 12:55:10 -0800650 port_allocator_ = allocator.Pass();
651
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000652 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
653 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000654 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000655 return false;
656 }
deadbeef653b8e02015-11-11 12:55:10 -0800657
658 cricket::ServerAddresses cricket_stuns;
659 std::vector<cricket::RelayServerConfig> cricket_turns;
660 ConvertToCricketIceServers(stun_config, turn_config, &cricket_stuns,
661 &cricket_turns);
662 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000663
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000665 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000666 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700667 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000668 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000669 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000670 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700671 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
672 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000673 if (!value) {
674 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000675 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000676 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000677 "Disabled") {
678 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000679 }
680
Jiayang Liucac1b382015-04-30 12:35:24 -0700681 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
682 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
683 LOG(LS_INFO) << "TCP candidates are disabled.";
684 }
685
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000686 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000687 // No step delay is used while allocating ports.
688 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
689
stefanc1aeaf02015-10-15 07:26:07 -0700690 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691
stefanc1aeaf02015-10-15 07:26:07 -0700692 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
693 factory_->signaling_thread(), media_controller_->channel_manager()));
694
695 session_.reset(
696 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
697 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700698 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699
700 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000701 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700702 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700704 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000706 // Register PeerConnection as receiver of local ice candidates.
707 // All the callbacks will be posted to the application from PeerConnection.
708 session_->RegisterIceObserver(this);
709 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700710 session_->SignalVoiceChannelDestroyed.connect(
711 this, &PeerConnection::OnVoiceChannelDestroyed);
712 session_->SignalVideoChannelDestroyed.connect(
713 this, &PeerConnection::OnVideoChannelDestroyed);
714 session_->SignalDataChannelCreated.connect(
715 this, &PeerConnection::OnDataChannelCreated);
716 session_->SignalDataChannelDestroyed.connect(
717 this, &PeerConnection::OnDataChannelDestroyed);
718 session_->SignalDataChannelOpenMessage.connect(
719 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000720 return true;
721}
722
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000723rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700725 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726}
727
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000728rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700730 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731}
732
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000733bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100734 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 if (IsClosed()) {
736 return false;
737 }
deadbeefab9b2d12015-10-14 11:33:11 -0700738 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000739 return false;
740 }
deadbeefab9b2d12015-10-14 11:33:11 -0700741
742 local_streams_->AddStream(local_stream);
743
deadbeefab9b2d12015-10-14 11:33:11 -0700744 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800745 auto sender = FindSenderForTrack(track.get());
746 if (sender == senders_.end()) {
747 // Normal case; we've never seen this track before.
748 AudioRtpSender* new_sender = new AudioRtpSender(
749 track.get(), local_stream->label(), session_.get(), stats_.get());
750 senders_.push_back(new_sender);
751 // If the sender has already been configured in SDP, we call SetSsrc,
752 // which will connect the sender to the underlying transport. This can
753 // occur if a local session description that contains the ID of the sender
754 // is set before AddStream is called. It can also occur if the local
755 // session description is not changed and RemoveStream is called, and
756 // later AddStream is called again with the same stream.
757 const TrackInfo* track_info = FindTrackInfo(
758 local_audio_tracks_, local_stream->label(), track->id());
759 if (track_info) {
760 new_sender->SetSsrc(track_info->ssrc);
761 }
762 } else {
763 // We already have a sender for this track, so just change the stream_id
764 // so that it's correct in the next call to CreateOffer.
765 (*sender)->set_stream_id(local_stream->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700766 }
767 }
768 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800769 auto sender = FindSenderForTrack(track.get());
770 if (sender == senders_.end()) {
771 // Normal case; we've never seen this track before.
772 VideoRtpSender* new_sender = new VideoRtpSender(
773 track.get(), local_stream->label(), session_.get());
774 senders_.push_back(new_sender);
775 const TrackInfo* track_info = FindTrackInfo(
776 local_video_tracks_, local_stream->label(), track->id());
777 if (track_info) {
778 new_sender->SetSsrc(track_info->ssrc);
779 }
780 } else {
781 // We already have a sender for this track, so just change the stream_id
782 // so that it's correct in the next call to CreateOffer.
783 (*sender)->set_stream_id(local_stream->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700784 }
785 }
786
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000787 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000788 observer_->OnRenegotiationNeeded();
789 return true;
790}
791
deadbeefab9b2d12015-10-14 11:33:11 -0700792// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
deadbeeffac06552015-11-25 11:26:01 -0800793// indefinitely, when we have unified plan SDP.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100795 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700796 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800797 auto sender = FindSenderForTrack(track.get());
798 if (sender == senders_.end()) {
799 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
800 << " doesn't exist.";
801 continue;
deadbeefab9b2d12015-10-14 11:33:11 -0700802 }
deadbeeffac06552015-11-25 11:26:01 -0800803 (*sender)->Stop();
804 senders_.erase(sender);
deadbeefab9b2d12015-10-14 11:33:11 -0700805 }
806 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeeffac06552015-11-25 11:26:01 -0800807 auto sender = FindSenderForTrack(track.get());
808 if (sender == senders_.end()) {
809 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
810 << " doesn't exist.";
811 continue;
deadbeefab9b2d12015-10-14 11:33:11 -0700812 }
deadbeeffac06552015-11-25 11:26:01 -0800813 (*sender)->Stop();
814 senders_.erase(sender);
deadbeefab9b2d12015-10-14 11:33:11 -0700815 }
816
817 local_streams_->RemoveStream(local_stream);
818
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 if (IsClosed()) {
820 return;
821 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 observer_->OnRenegotiationNeeded();
823}
824
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000825rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100827 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828 if (!track) {
829 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
830 return NULL;
831 }
deadbeefab9b2d12015-10-14 11:33:11 -0700832 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
834 return NULL;
835 }
836
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000837 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 DtmfSender::Create(track, signaling_thread(), session_.get()));
839 if (!sender.get()) {
840 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
841 return NULL;
842 }
843 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
844}
845
deadbeeffac06552015-11-25 11:26:01 -0800846rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
847 const std::string& kind) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100848 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeeffac06552015-11-25 11:26:01 -0800849 RtpSenderInterface* new_sender;
850 if (kind == MediaStreamTrackInterface::kAudioKind) {
851 new_sender = new AudioRtpSender(session_.get(), stats_.get());
852 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
853 new_sender = new VideoRtpSender(session_.get());
854 } else {
855 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
856 return rtc::scoped_refptr<RtpSenderInterface>();
857 }
858 senders_.push_back(new_sender);
859 return RtpSenderProxy::Create(signaling_thread(), new_sender);
860}
861
deadbeef70ab1a12015-09-28 16:53:55 -0700862std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
863 const {
864 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
865 for (const auto& sender : senders_) {
866 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
867 }
868 return senders;
869}
870
871std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
872PeerConnection::GetReceivers() const {
873 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
874 for (const auto& receiver : receivers_) {
875 receivers.push_back(
876 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
877 }
878 return receivers;
879}
880
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000881bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000882 MediaStreamTrackInterface* track,
883 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100884 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700885 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886 if (!VERIFY(observer != NULL)) {
887 LOG(LS_ERROR) << "GetStats - observer is NULL.";
888 return false;
889 }
890
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000891 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000892 signaling_thread()->Post(this, MSG_GETSTATS,
893 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000894 return true;
895}
896
897PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
898 return signaling_state_;
899}
900
901PeerConnectionInterface::IceState PeerConnection::ice_state() {
902 return ice_state_;
903}
904
905PeerConnectionInterface::IceConnectionState
906PeerConnection::ice_connection_state() {
907 return ice_connection_state_;
908}
909
910PeerConnectionInterface::IceGatheringState
911PeerConnection::ice_gathering_state() {
912 return ice_gathering_state_;
913}
914
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000915rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916PeerConnection::CreateDataChannel(
917 const std::string& label,
918 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100919 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700920 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000921
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000922 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000923 if (config) {
924 internal_config.reset(new InternalDataChannelInit(*config));
925 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000926 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700927 InternalCreateDataChannel(label, internal_config.get()));
928 if (!channel.get()) {
929 return nullptr;
930 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000932 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
933 // the first SCTP DataChannel.
934 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
935 observer_->OnRenegotiationNeeded();
936 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000937
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 return DataChannelProxy::Create(signaling_thread(), channel.get());
939}
940
941void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
942 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100943 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700944 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
946 return;
947 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000948 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000949
950 bool value;
951 size_t mandatory_constraints = 0;
952
953 if (FindConstraint(constraints,
954 MediaConstraintsInterface::kOfferToReceiveAudio,
955 &value,
956 &mandatory_constraints)) {
957 options.offer_to_receive_audio =
958 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
959 }
960
961 if (FindConstraint(constraints,
962 MediaConstraintsInterface::kOfferToReceiveVideo,
963 &value,
964 &mandatory_constraints)) {
965 options.offer_to_receive_video =
966 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
967 }
968
969 if (FindConstraint(constraints,
970 MediaConstraintsInterface::kVoiceActivityDetection,
971 &value,
972 &mandatory_constraints)) {
973 options.voice_activity_detection = value;
974 }
975
976 if (FindConstraint(constraints,
977 MediaConstraintsInterface::kIceRestart,
978 &value,
979 &mandatory_constraints)) {
980 options.ice_restart = value;
981 }
982
983 if (FindConstraint(constraints,
984 MediaConstraintsInterface::kUseRtpMux,
985 &value,
986 &mandatory_constraints)) {
987 options.use_rtp_mux = value;
988 }
989
990 CreateOffer(observer, options);
991}
992
993void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
994 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100995 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700996 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000997 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
998 return;
999 }
deadbeefab9b2d12015-10-14 11:33:11 -07001000
1001 cricket::MediaSessionOptions session_options;
1002 if (!GetOptionsForOffer(options, &session_options)) {
1003 std::string error = "CreateOffer called with invalid options.";
1004 LOG(LS_ERROR) << error;
1005 PostCreateSessionDescriptionFailure(observer, error);
1006 return;
1007 }
1008
1009 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010}
1011
1012void PeerConnection::CreateAnswer(
1013 CreateSessionDescriptionObserver* observer,
1014 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001015 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001016 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1018 return;
1019 }
deadbeefab9b2d12015-10-14 11:33:11 -07001020
1021 cricket::MediaSessionOptions session_options;
1022 if (!GetOptionsForAnswer(constraints, &session_options)) {
1023 std::string error = "CreateAnswer called with invalid constraints.";
1024 LOG(LS_ERROR) << error;
1025 PostCreateSessionDescriptionFailure(observer, error);
1026 return;
1027 }
1028
1029 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030}
1031
1032void PeerConnection::SetLocalDescription(
1033 SetSessionDescriptionObserver* observer,
1034 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001035 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001036 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1038 return;
1039 }
1040 if (!desc) {
1041 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1042 return;
1043 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044 // Update stats here so that we have the most recent stats for tracks and
1045 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001046 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047 std::string error;
1048 if (!session_->SetLocalDescription(desc, &error)) {
1049 PostSetSessionDescriptionFailure(observer, error);
1050 return;
1051 }
deadbeefab9b2d12015-10-14 11:33:11 -07001052
1053 // If setting the description decided our SSL role, allocate any necessary
1054 // SCTP sids.
1055 rtc::SSLRole role;
1056 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1057 session_->GetSslRole(&role)) {
1058 AllocateSctpSids(role);
1059 }
1060
1061 // Update state and SSRC of local MediaStreams and DataChannels based on the
1062 // local session description.
1063 const cricket::ContentInfo* audio_content =
1064 GetFirstAudioContent(desc->description());
1065 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001066 if (audio_content->rejected) {
1067 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1068 } else {
1069 const cricket::AudioContentDescription* audio_desc =
1070 static_cast<const cricket::AudioContentDescription*>(
1071 audio_content->description);
1072 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1073 }
deadbeefab9b2d12015-10-14 11:33:11 -07001074 }
1075
1076 const cricket::ContentInfo* video_content =
1077 GetFirstVideoContent(desc->description());
1078 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001079 if (video_content->rejected) {
1080 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1081 } else {
1082 const cricket::VideoContentDescription* video_desc =
1083 static_cast<const cricket::VideoContentDescription*>(
1084 video_content->description);
1085 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1086 }
deadbeefab9b2d12015-10-14 11:33:11 -07001087 }
1088
1089 const cricket::ContentInfo* data_content =
1090 GetFirstDataContent(desc->description());
1091 if (data_content) {
1092 const cricket::DataContentDescription* data_desc =
1093 static_cast<const cricket::DataContentDescription*>(
1094 data_content->description);
1095 if (rtc::starts_with(data_desc->protocol().data(),
1096 cricket::kMediaProtocolRtpPrefix)) {
1097 UpdateLocalRtpDataChannels(data_desc->streams());
1098 }
1099 }
1100
1101 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001103
deadbeefcbecd352015-09-23 11:50:27 -07001104 // MaybeStartGathering needs to be called after posting
1105 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1106 // before signaling that SetLocalDescription completed.
1107 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108}
1109
1110void PeerConnection::SetRemoteDescription(
1111 SetSessionDescriptionObserver* observer,
1112 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001113 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001114 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1116 return;
1117 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001118 if (!desc) {
1119 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1120 return;
1121 }
1122 // Update stats here so that we have the most recent stats for tracks and
1123 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001124 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001125 std::string error;
1126 if (!session_->SetRemoteDescription(desc, &error)) {
1127 PostSetSessionDescriptionFailure(observer, error);
1128 return;
1129 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130
deadbeefab9b2d12015-10-14 11:33:11 -07001131 // If setting the description decided our SSL role, allocate any necessary
1132 // SCTP sids.
1133 rtc::SSLRole role;
1134 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1135 session_->GetSslRole(&role)) {
1136 AllocateSctpSids(role);
1137 }
1138
1139 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001140 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1141 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1142 const cricket::AudioContentDescription* audio_desc =
1143 GetFirstAudioContentDescription(remote_desc);
1144 const cricket::VideoContentDescription* video_desc =
1145 GetFirstVideoContentDescription(remote_desc);
1146 const cricket::DataContentDescription* data_desc =
1147 GetFirstDataContentDescription(remote_desc);
1148
1149 // Check if the descriptions include streams, just in case the peer supports
1150 // MSID, but doesn't indicate so with "a=msid-semantic".
1151 if (remote_desc->msid_supported() ||
1152 (audio_desc && !audio_desc->streams().empty()) ||
1153 (video_desc && !video_desc->streams().empty())) {
1154 remote_peer_supports_msid_ = true;
1155 }
deadbeefab9b2d12015-10-14 11:33:11 -07001156
1157 // We wait to signal new streams until we finish processing the description,
1158 // since only at that point will new streams have all their tracks.
1159 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1160
1161 // Find all audio rtp streams and create corresponding remote AudioTracks
1162 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001163 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001164 if (audio_content->rejected) {
1165 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1166 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001167 bool default_audio_track_needed =
1168 !remote_peer_supports_msid_ &&
1169 MediaContentDirectionHasSend(audio_desc->direction());
1170 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1171 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001172 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001173 }
deadbeefab9b2d12015-10-14 11:33:11 -07001174 }
1175
1176 // Find all video rtp streams and create corresponding remote VideoTracks
1177 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001178 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001179 if (video_content->rejected) {
1180 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1181 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001182 bool default_video_track_needed =
1183 !remote_peer_supports_msid_ &&
1184 MediaContentDirectionHasSend(video_desc->direction());
1185 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1186 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001187 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001188 }
deadbeefab9b2d12015-10-14 11:33:11 -07001189 }
1190
1191 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001192 if (data_desc) {
1193 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001194 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001195 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001196 }
1197 }
1198
1199 // Iterate new_streams and notify the observer about new MediaStreams.
1200 for (size_t i = 0; i < new_streams->count(); ++i) {
1201 MediaStreamInterface* new_stream = new_streams->at(i);
1202 stats_->AddStream(new_stream);
1203 observer_->OnAddStream(new_stream);
1204 }
1205
deadbeefbda7e0b2015-12-08 17:13:40 -08001206 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001207
1208 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1209 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001210}
1211
deadbeefa67696b2015-09-29 11:56:26 -07001212bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001213 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001214 if (port_allocator_) {
1215 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1216 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1217 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1218 return false;
1219 }
1220
deadbeef653b8e02015-11-11 12:55:10 -08001221 cricket::ServerAddresses cricket_stuns;
1222 std::vector<cricket::RelayServerConfig> cricket_turns;
1223 ConvertToCricketIceServers(stuns, turns, &cricket_stuns, &cricket_turns);
1224 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001225 }
honghaiz1f429e32015-09-28 07:57:34 -07001226 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001227 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001228}
1229
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230bool PeerConnection::AddIceCandidate(
1231 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001232 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 return session_->ProcessIceMessage(ice_candidate);
1234}
1235
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001236void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001237 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001238 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001239
1240 if (session_) {
1241 session_->set_metrics_observer(uma_observer_);
1242 }
1243
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001244 // Send information about IPv4/IPv6 status.
1245 if (uma_observer_ && port_allocator_) {
1246 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001247 uma_observer_->IncrementEnumCounter(
1248 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1249 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001250 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001251 uma_observer_->IncrementEnumCounter(
1252 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1253 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001254 }
1255 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001256}
1257
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258const SessionDescriptionInterface* PeerConnection::local_description() const {
1259 return session_->local_description();
1260}
1261
1262const SessionDescriptionInterface* PeerConnection::remote_description() const {
1263 return session_->remote_description();
1264}
1265
1266void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001267 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268 // Update stats here so that we have the most recent stats for tracks and
1269 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001270 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271
deadbeefd59daf82015-10-14 15:02:44 -07001272 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273}
1274
deadbeefd59daf82015-10-14 15:02:44 -07001275void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1276 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001277 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001278 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001280 break;
deadbeefd59daf82015-10-14 15:02:44 -07001281 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1283 break;
deadbeefd59daf82015-10-14 15:02:44 -07001284 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1286 break;
deadbeefd59daf82015-10-14 15:02:44 -07001287 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1289 break;
deadbeefd59daf82015-10-14 15:02:44 -07001290 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1292 break;
deadbeefd59daf82015-10-14 15:02:44 -07001293 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001294 ChangeSignalingState(PeerConnectionInterface::kStable);
1295 break;
deadbeefd59daf82015-10-14 15:02:44 -07001296 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 ChangeSignalingState(PeerConnectionInterface::kClosed);
1298 break;
1299 default:
1300 break;
1301 }
1302}
1303
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001304void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1307 SetSessionDescriptionMsg* param =
1308 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1309 param->observer->OnSuccess();
1310 delete param;
1311 break;
1312 }
1313 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1314 SetSessionDescriptionMsg* param =
1315 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1316 param->observer->OnFailure(param->error);
1317 delete param;
1318 break;
1319 }
deadbeefab9b2d12015-10-14 11:33:11 -07001320 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1321 CreateSessionDescriptionMsg* param =
1322 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1323 param->observer->OnFailure(param->error);
1324 delete param;
1325 break;
1326 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327 case MSG_GETSTATS: {
1328 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001329 StatsReports reports;
1330 stats_->GetStats(param->track, &reports);
1331 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 delete param;
1333 break;
1334 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001336 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 break;
1338 }
1339}
1340
deadbeefab9b2d12015-10-14 11:33:11 -07001341void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1342 AudioTrackInterface* audio_track,
1343 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001344 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345}
1346
deadbeefab9b2d12015-10-14 11:33:11 -07001347void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1348 VideoTrackInterface* video_track,
1349 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001350 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351}
1352
deadbeef70ab1a12015-09-28 16:53:55 -07001353// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1354// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001355void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1356 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001357 auto it = FindReceiverForTrack(audio_track);
1358 if (it == receivers_.end()) {
1359 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1360 << " doesn't exist.";
1361 } else {
1362 (*it)->Stop();
1363 receivers_.erase(it);
1364 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365}
1366
deadbeefab9b2d12015-10-14 11:33:11 -07001367void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1368 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001369 auto it = FindReceiverForTrack(video_track);
1370 if (it == receivers_.end()) {
1371 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1372 << " doesn't exist.";
1373 } else {
1374 (*it)->Stop();
1375 receivers_.erase(it);
1376 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377}
deadbeef70ab1a12015-09-28 16:53:55 -07001378
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379void PeerConnection::OnIceConnectionChange(
1380 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001381 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001382 // After transitioning to "closed", ignore any additional states from
1383 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001384 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001385 return;
1386 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001388 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389}
1390
1391void PeerConnection::OnIceGatheringChange(
1392 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001393 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394 if (IsClosed()) {
1395 return;
1396 }
1397 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001398 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001399}
1400
1401void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001402 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001403 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404}
1405
1406void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001407 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001408 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409}
1410
Peter Thatcher54360512015-07-08 11:08:35 -07001411void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001412 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001413 observer_->OnIceConnectionReceivingChange(receiving);
1414}
1415
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416void PeerConnection::ChangeSignalingState(
1417 PeerConnectionInterface::SignalingState signaling_state) {
1418 signaling_state_ = signaling_state;
1419 if (signaling_state == kClosed) {
1420 ice_connection_state_ = kIceConnectionClosed;
1421 observer_->OnIceConnectionChange(ice_connection_state_);
1422 if (ice_gathering_state_ != kIceGatheringComplete) {
1423 ice_gathering_state_ = kIceGatheringComplete;
1424 observer_->OnIceGatheringChange(ice_gathering_state_);
1425 }
1426 }
1427 observer_->OnSignalingChange(signaling_state_);
1428 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1429}
1430
deadbeefab9b2d12015-10-14 11:33:11 -07001431void PeerConnection::PostSetSessionDescriptionFailure(
1432 SetSessionDescriptionObserver* observer,
1433 const std::string& error) {
1434 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1435 msg->error = error;
1436 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1437}
1438
1439void PeerConnection::PostCreateSessionDescriptionFailure(
1440 CreateSessionDescriptionObserver* observer,
1441 const std::string& error) {
1442 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1443 msg->error = error;
1444 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1445}
1446
1447bool PeerConnection::GetOptionsForOffer(
1448 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1449 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001450 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1451 return false;
1452 }
1453
deadbeeffac06552015-11-25 11:26:01 -08001454 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001455 // Offer to receive audio/video if the constraint is not set and there are
1456 // send streams, or we're currently receiving.
1457 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1458 session_options->recv_audio =
1459 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1460 !remote_audio_tracks_.empty();
1461 }
1462 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1463 session_options->recv_video =
1464 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1465 !remote_video_tracks_.empty();
1466 }
1467 session_options->bundle_enabled =
1468 session_options->bundle_enabled &&
1469 (session_options->has_audio() || session_options->has_video() ||
1470 session_options->has_data());
1471
deadbeefab9b2d12015-10-14 11:33:11 -07001472 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1473 session_options->data_channel_type = cricket::DCT_SCTP;
1474 }
1475 return true;
1476}
1477
1478bool PeerConnection::GetOptionsForAnswer(
1479 const MediaConstraintsInterface* constraints,
1480 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001481 session_options->recv_audio = false;
1482 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001483 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1484 return false;
1485 }
1486
deadbeeffac06552015-11-25 11:26:01 -08001487 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001488 session_options->bundle_enabled =
1489 session_options->bundle_enabled &&
1490 (session_options->has_audio() || session_options->has_video() ||
1491 session_options->has_data());
1492
deadbeefab9b2d12015-10-14 11:33:11 -07001493 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1494 // are not signaled in the SDP so does not go through that path and must be
1495 // handled here.
1496 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1497 session_options->data_channel_type = cricket::DCT_SCTP;
1498 }
1499 return true;
1500}
1501
deadbeeffaac4972015-11-12 15:33:07 -08001502void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1503 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001504 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1505 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001506}
1507
deadbeefab9b2d12015-10-14 11:33:11 -07001508void PeerConnection::UpdateRemoteStreamsList(
1509 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001510 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001511 cricket::MediaType media_type,
1512 StreamCollection* new_streams) {
1513 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1514
1515 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001516 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001517 auto track_it = current_tracks->begin();
1518 while (track_it != current_tracks->end()) {
1519 const TrackInfo& info = *track_it;
1520 const cricket::StreamParams* params =
1521 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001522 bool track_exists = params && params->id == info.track_id;
1523 // If this is a default track, and we still need it, don't remove it.
1524 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1525 track_exists) {
1526 ++track_it;
1527 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001528 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1529 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001530 }
1531 }
1532
1533 // Find new and active tracks.
1534 for (const cricket::StreamParams& params : streams) {
1535 // The sync_label is the MediaStream label and the |stream.id| is the
1536 // track id.
1537 const std::string& stream_label = params.sync_label;
1538 const std::string& track_id = params.id;
1539 uint32_t ssrc = params.first_ssrc();
1540
1541 rtc::scoped_refptr<MediaStreamInterface> stream =
1542 remote_streams_->find(stream_label);
1543 if (!stream) {
1544 // This is a new MediaStream. Create a new remote MediaStream.
1545 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1546 remote_streams_->AddStream(stream);
1547 new_streams->AddStream(stream);
1548 }
1549
1550 const TrackInfo* track_info =
1551 FindTrackInfo(*current_tracks, stream_label, track_id);
1552 if (!track_info) {
1553 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1554 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1555 }
1556 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001557
1558 // Add default track if necessary.
1559 if (default_track_needed) {
1560 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1561 remote_streams_->find(kDefaultStreamLabel);
1562 if (!default_stream) {
1563 // Create the new default MediaStream.
1564 default_stream =
1565 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1566 remote_streams_->AddStream(default_stream);
1567 new_streams->AddStream(default_stream);
1568 }
1569 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1570 ? kDefaultAudioTrackLabel
1571 : kDefaultVideoTrackLabel;
1572 const TrackInfo* default_track_info =
1573 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1574 if (!default_track_info) {
1575 current_tracks->push_back(
1576 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1577 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1578 }
1579 }
deadbeefab9b2d12015-10-14 11:33:11 -07001580}
1581
1582void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1583 const std::string& track_id,
1584 uint32_t ssrc,
1585 cricket::MediaType media_type) {
1586 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1587
1588 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Tommif888bb52015-12-12 01:37:01 +01001589 AudioTrackInterface* audio_track = remote_stream_factory_->AddAudioTrack(
1590 ssrc, session_.get(), stream, track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001591 CreateAudioReceiver(stream, audio_track, ssrc);
1592 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1593 VideoTrackInterface* video_track =
1594 remote_stream_factory_->AddVideoTrack(stream, track_id);
1595 CreateVideoReceiver(stream, video_track, ssrc);
1596 } else {
1597 RTC_DCHECK(false && "Invalid media type");
1598 }
1599}
1600
1601void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1602 const std::string& track_id,
1603 cricket::MediaType media_type) {
1604 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1605
1606 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1607 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1608 stream->FindAudioTrack(track_id);
1609 if (audio_track) {
1610 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1611 stream->RemoveTrack(audio_track);
1612 DestroyAudioReceiver(stream, audio_track);
1613 }
1614 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1615 rtc::scoped_refptr<VideoTrackInterface> video_track =
1616 stream->FindVideoTrack(track_id);
1617 if (video_track) {
1618 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1619 stream->RemoveTrack(video_track);
1620 DestroyVideoReceiver(stream, video_track);
1621 }
1622 } else {
1623 ASSERT(false && "Invalid media type");
1624 }
1625}
1626
1627void PeerConnection::UpdateEndedRemoteMediaStreams() {
1628 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1629 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1630 MediaStreamInterface* stream = remote_streams_->at(i);
1631 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1632 streams_to_remove.push_back(stream);
1633 }
1634 }
1635
1636 for (const auto& stream : streams_to_remove) {
1637 remote_streams_->RemoveStream(stream);
1638 observer_->OnRemoveStream(stream);
1639 }
1640}
1641
deadbeefab9b2d12015-10-14 11:33:11 -07001642void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1643 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1644 for (TrackInfos::iterator track_it = current_tracks->begin();
1645 track_it != current_tracks->end(); ++track_it) {
1646 const TrackInfo& info = *track_it;
1647 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1648 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1649 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1650 // There's no guarantee the track is still available, e.g. the track may
1651 // have been removed from the stream by javascript.
1652 if (track) {
1653 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1654 }
1655 }
1656 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1657 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1658 // There's no guarantee the track is still available, e.g. the track may
1659 // have been removed from the stream by javascript.
1660 if (track) {
1661 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1662 }
1663 }
1664 }
1665}
1666
1667void PeerConnection::UpdateLocalTracks(
1668 const std::vector<cricket::StreamParams>& streams,
1669 cricket::MediaType media_type) {
1670 TrackInfos* current_tracks = GetLocalTracks(media_type);
1671
1672 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1673 // don't match the new StreamParam.
1674 TrackInfos::iterator track_it = current_tracks->begin();
1675 while (track_it != current_tracks->end()) {
1676 const TrackInfo& info = *track_it;
1677 const cricket::StreamParams* params =
1678 cricket::GetStreamBySsrc(streams, info.ssrc);
1679 if (!params || params->id != info.track_id ||
1680 params->sync_label != info.stream_label) {
1681 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1682 media_type);
1683 track_it = current_tracks->erase(track_it);
1684 } else {
1685 ++track_it;
1686 }
1687 }
1688
1689 // Find new and active tracks.
1690 for (const cricket::StreamParams& params : streams) {
1691 // The sync_label is the MediaStream label and the |stream.id| is the
1692 // track id.
1693 const std::string& stream_label = params.sync_label;
1694 const std::string& track_id = params.id;
1695 uint32_t ssrc = params.first_ssrc();
1696 const TrackInfo* track_info =
1697 FindTrackInfo(*current_tracks, stream_label, track_id);
1698 if (!track_info) {
1699 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1700 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1701 }
1702 }
1703}
1704
1705void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1706 const std::string& track_id,
1707 uint32_t ssrc,
1708 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001709 RtpSenderInterface* sender = FindSenderById(track_id);
1710 if (!sender) {
1711 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1712 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001713 return;
1714 }
1715
deadbeeffac06552015-11-25 11:26:01 -08001716 if (sender->media_type() != media_type) {
1717 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1718 << " description with an unexpected media type.";
1719 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001720 }
deadbeeffac06552015-11-25 11:26:01 -08001721
1722 sender->set_stream_id(stream_label);
1723 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001724}
1725
1726void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1727 const std::string& track_id,
1728 uint32_t ssrc,
1729 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001730 RtpSenderInterface* sender = FindSenderById(track_id);
1731 if (!sender) {
1732 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001733 // SessionDescriptions has been renegotiated.
1734 return;
1735 }
deadbeeffac06552015-11-25 11:26:01 -08001736
1737 // A sender has been removed from the SessionDescription but it's still
1738 // associated with the PeerConnection. This only occurs if the SDP doesn't
1739 // match with the calls to CreateSender, AddStream and RemoveStream.
1740 if (sender->media_type() != media_type) {
1741 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1742 << " description with an unexpected media type.";
1743 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001744 }
deadbeeffac06552015-11-25 11:26:01 -08001745
1746 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001747}
1748
1749void PeerConnection::UpdateLocalRtpDataChannels(
1750 const cricket::StreamParamsVec& streams) {
1751 std::vector<std::string> existing_channels;
1752
1753 // Find new and active data channels.
1754 for (const cricket::StreamParams& params : streams) {
1755 // |it->sync_label| is actually the data channel label. The reason is that
1756 // we use the same naming of data channels as we do for
1757 // MediaStreams and Tracks.
1758 // For MediaStreams, the sync_label is the MediaStream label and the
1759 // track label is the same as |streamid|.
1760 const std::string& channel_label = params.sync_label;
1761 auto data_channel_it = rtp_data_channels_.find(channel_label);
1762 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1763 continue;
1764 }
1765 // Set the SSRC the data channel should use for sending.
1766 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1767 existing_channels.push_back(data_channel_it->first);
1768 }
1769
1770 UpdateClosingRtpDataChannels(existing_channels, true);
1771}
1772
1773void PeerConnection::UpdateRemoteRtpDataChannels(
1774 const cricket::StreamParamsVec& streams) {
1775 std::vector<std::string> existing_channels;
1776
1777 // Find new and active data channels.
1778 for (const cricket::StreamParams& params : streams) {
1779 // The data channel label is either the mslabel or the SSRC if the mslabel
1780 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1781 std::string label = params.sync_label.empty()
1782 ? rtc::ToString(params.first_ssrc())
1783 : params.sync_label;
1784 auto data_channel_it = rtp_data_channels_.find(label);
1785 if (data_channel_it == rtp_data_channels_.end()) {
1786 // This is a new data channel.
1787 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1788 } else {
1789 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1790 }
1791 existing_channels.push_back(label);
1792 }
1793
1794 UpdateClosingRtpDataChannels(existing_channels, false);
1795}
1796
1797void PeerConnection::UpdateClosingRtpDataChannels(
1798 const std::vector<std::string>& active_channels,
1799 bool is_local_update) {
1800 auto it = rtp_data_channels_.begin();
1801 while (it != rtp_data_channels_.end()) {
1802 DataChannel* data_channel = it->second;
1803 if (std::find(active_channels.begin(), active_channels.end(),
1804 data_channel->label()) != active_channels.end()) {
1805 ++it;
1806 continue;
1807 }
1808
1809 if (is_local_update) {
1810 data_channel->SetSendSsrc(0);
1811 } else {
1812 data_channel->RemotePeerRequestClose();
1813 }
1814
1815 if (data_channel->state() == DataChannel::kClosed) {
1816 rtp_data_channels_.erase(it);
1817 it = rtp_data_channels_.begin();
1818 } else {
1819 ++it;
1820 }
1821 }
1822}
1823
1824void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1825 uint32_t remote_ssrc) {
1826 rtc::scoped_refptr<DataChannel> channel(
1827 InternalCreateDataChannel(label, nullptr));
1828 if (!channel.get()) {
1829 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1830 << "CreateDataChannel failed.";
1831 return;
1832 }
1833 channel->SetReceiveSsrc(remote_ssrc);
1834 observer_->OnDataChannel(
1835 DataChannelProxy::Create(signaling_thread(), channel));
1836}
1837
1838rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1839 const std::string& label,
1840 const InternalDataChannelInit* config) {
1841 if (IsClosed()) {
1842 return nullptr;
1843 }
1844 if (session_->data_channel_type() == cricket::DCT_NONE) {
1845 LOG(LS_ERROR)
1846 << "InternalCreateDataChannel: Data is not supported in this call.";
1847 return nullptr;
1848 }
1849 InternalDataChannelInit new_config =
1850 config ? (*config) : InternalDataChannelInit();
1851 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1852 if (new_config.id < 0) {
1853 rtc::SSLRole role;
1854 if (session_->GetSslRole(&role) &&
1855 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1856 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1857 return nullptr;
1858 }
1859 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1860 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1861 << "because the id is already in use or out of range.";
1862 return nullptr;
1863 }
1864 }
1865
1866 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1867 session_.get(), session_->data_channel_type(), label, new_config));
1868 if (!channel) {
1869 sid_allocator_.ReleaseSid(new_config.id);
1870 return nullptr;
1871 }
1872
1873 if (channel->data_channel_type() == cricket::DCT_RTP) {
1874 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1875 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1876 << " already exists.";
1877 return nullptr;
1878 }
1879 rtp_data_channels_[channel->label()] = channel;
1880 } else {
1881 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1882 sctp_data_channels_.push_back(channel);
1883 channel->SignalClosed.connect(this,
1884 &PeerConnection::OnSctpDataChannelClosed);
1885 }
1886
1887 return channel;
1888}
1889
1890bool PeerConnection::HasDataChannels() const {
1891 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1892}
1893
1894void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1895 for (const auto& channel : sctp_data_channels_) {
1896 if (channel->id() < 0) {
1897 int sid;
1898 if (!sid_allocator_.AllocateSid(role, &sid)) {
1899 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1900 continue;
1901 }
1902 channel->SetSctpSid(sid);
1903 }
1904 }
1905}
1906
1907void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1908 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1909 ++it) {
1910 if (it->get() == channel) {
1911 if (channel->id() >= 0) {
1912 sid_allocator_.ReleaseSid(channel->id());
1913 }
1914 sctp_data_channels_.erase(it);
1915 return;
1916 }
1917 }
1918}
1919
1920void PeerConnection::OnVoiceChannelDestroyed() {
1921 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1922}
1923
1924void PeerConnection::OnVideoChannelDestroyed() {
1925 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1926}
1927
1928void PeerConnection::OnDataChannelCreated() {
1929 for (const auto& channel : sctp_data_channels_) {
1930 channel->OnTransportChannelCreated();
1931 }
1932}
1933
1934void PeerConnection::OnDataChannelDestroyed() {
1935 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1936 // DataChannel may callback to us and try to modify the list.
1937 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1938 temp_rtp_dcs.swap(rtp_data_channels_);
1939 for (const auto& kv : temp_rtp_dcs) {
1940 kv.second->OnTransportChannelDestroyed();
1941 }
1942
1943 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1944 temp_sctp_dcs.swap(sctp_data_channels_);
1945 for (const auto& channel : temp_sctp_dcs) {
1946 channel->OnTransportChannelDestroyed();
1947 }
1948}
1949
1950void PeerConnection::OnDataChannelOpenMessage(
1951 const std::string& label,
1952 const InternalDataChannelInit& config) {
1953 rtc::scoped_refptr<DataChannel> channel(
1954 InternalCreateDataChannel(label, &config));
1955 if (!channel.get()) {
1956 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1957 return;
1958 }
1959
1960 observer_->OnDataChannel(
1961 DataChannelProxy::Create(signaling_thread(), channel));
1962}
1963
deadbeeffac06552015-11-25 11:26:01 -08001964RtpSenderInterface* PeerConnection::FindSenderById(const std::string& id) {
1965 auto it =
1966 std::find_if(senders_.begin(), senders_.end(),
1967 [id](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1968 return sender->id() == id;
1969 });
1970 return it != senders_.end() ? it->get() : nullptr;
1971}
1972
deadbeef70ab1a12015-09-28 16:53:55 -07001973std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1974PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1975 return std::find_if(
1976 senders_.begin(), senders_.end(),
1977 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1978 return sender->track() == track;
1979 });
1980}
1981
1982std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1983PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1984 return std::find_if(
1985 receivers_.begin(), receivers_.end(),
1986 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1987 return receiver->track() == track;
1988 });
1989}
1990
deadbeefab9b2d12015-10-14 11:33:11 -07001991PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1992 cricket::MediaType media_type) {
1993 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1994 media_type == cricket::MEDIA_TYPE_VIDEO);
1995 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1996 : &remote_video_tracks_;
1997}
1998
1999PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2000 cricket::MediaType media_type) {
2001 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2002 media_type == cricket::MEDIA_TYPE_VIDEO);
2003 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2004 : &local_video_tracks_;
2005}
2006
2007const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2008 const PeerConnection::TrackInfos& infos,
2009 const std::string& stream_label,
2010 const std::string track_id) const {
2011 for (const TrackInfo& track_info : infos) {
2012 if (track_info.stream_label == stream_label &&
2013 track_info.track_id == track_id) {
2014 return &track_info;
2015 }
2016 }
2017 return nullptr;
2018}
2019
2020DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2021 for (const auto& channel : sctp_data_channels_) {
2022 if (channel->id() == sid) {
2023 return channel;
2024 }
2025 }
2026 return nullptr;
2027}
2028
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029} // namespace webrtc