blob: 1b61c7fb2711ab3ae95e1adae7a635280cd05e3c [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00003 * Copyright 2012 Google Inc.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/peerconnection.h"
29
30#include <vector>
deadbeef0a6c4ca2015-10-06 11:38:28 -070031#include <cctype> // for isdigit
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032
deadbeefab9b2d12015-10-14 11:33:11 -070033#include "talk/app/webrtc/audiotrack.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034#include "talk/app/webrtc/dtmfsender.h"
35#include "talk/app/webrtc/jsepicecandidate.h"
36#include "talk/app/webrtc/jsepsessiondescription.h"
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +000037#include "talk/app/webrtc/mediaconstraintsinterface.h"
deadbeefab9b2d12015-10-14 11:33:11 -070038#include "talk/app/webrtc/mediastream.h"
39#include "talk/app/webrtc/mediastreamproxy.h"
40#include "talk/app/webrtc/mediastreamtrackproxy.h"
41#include "talk/app/webrtc/remoteaudiosource.h"
42#include "talk/app/webrtc/remotevideocapturer.h"
deadbeef70ab1a12015-09-28 16:53:55 -070043#include "talk/app/webrtc/rtpreceiver.h"
44#include "talk/app/webrtc/rtpsender.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045#include "talk/app/webrtc/streamcollection.h"
deadbeefab9b2d12015-10-14 11:33:11 -070046#include "talk/app/webrtc/videosource.h"
47#include "talk/app/webrtc/videotrack.h"
48#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049#include "talk/session/media/channelmanager.h"
tfarina5237aaf2015-11-10 23:44:30 -080050#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000051#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070053#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010054#include "webrtc/base/trace_event.h"
tfarina5237aaf2015-11-10 23:44:30 -080055#include "webrtc/p2p/client/basicportallocator.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010056#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
58namespace {
59
deadbeefab9b2d12015-10-14 11:33:11 -070060using webrtc::DataChannel;
61using webrtc::MediaConstraintsInterface;
62using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063using webrtc::PeerConnectionInterface;
deadbeeffac06552015-11-25 11:26:01 -080064using webrtc::RtpSenderInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070065using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070066using webrtc::StunConfigurations;
67using webrtc::TurnConfigurations;
68typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
69 StunConfiguration;
70typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
71 TurnConfiguration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
deadbeefab9b2d12015-10-14 11:33:11 -070073static const char kDefaultStreamLabel[] = "default";
74static const char kDefaultAudioTrackLabel[] = "defaulta0";
75static const char kDefaultVideoTrackLabel[] = "defaultv0";
76
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077// The min number of tokens must present in Turn host uri.
78// e.g. user@turn.example.org
79static const size_t kTurnHostTokensNum = 2;
80// Number of tokens must be preset when TURN uri has transport param.
81static const size_t kTurnTransportTokensNum = 2;
82// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000083static const int kDefaultStunPort = 3478;
84static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000086static const char kUdpTransportType[] = "udp";
87static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
89// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070090static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091
deadbeef0a6c4ca2015-10-06 11:38:28 -070092// NOTE: A loop below assumes that the first value of this enum is 0 and all
93// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070095 STUN = 0, // Indicates a STUN server.
96 STUNS, // Indicates a STUN server used with a TLS session.
97 TURN, // Indicates a TURN server
98 TURNS, // Indicates a TURN server used with a TLS session.
99 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100};
tfarina5237aaf2015-11-10 23:44:30 -0800101static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -0700102 "kValidIceServiceTypes must have as many strings as ServiceType "
103 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104
105enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 MSG_GETSTATS,
deadbeef38686922015-12-07 15:32:23 -0800110 MSG_DELETE,
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
452 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
453 const std::string& track_id) {
454 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
455 stream, track_id, RemoteAudioSource::Create().get());
456 }
457
458 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
459 const std::string& track_id) {
460 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
461 stream, track_id,
462 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
463 nullptr)
464 .get());
465 }
466
467 private:
468 template <typename TI, typename T, typename TP, typename S>
469 TI* AddTrack(MediaStreamInterface* stream,
470 const std::string& track_id,
471 S* source) {
472 rtc::scoped_refptr<TI> track(
473 TP::Create(signaling_thread_, T::Create(track_id, source)));
474 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
475 if (stream->AddTrack(track)) {
476 return track;
477 }
478 return nullptr;
479 }
480
481 rtc::Thread* signaling_thread_;
482 cricket::ChannelManager* channel_manager_;
483};
484
485bool ConvertRtcOptionsForOffer(
486 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
487 cricket::MediaSessionOptions* session_options) {
488 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
489 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
490 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
491 return false;
492 }
493
deadbeefc80741f2015-10-22 13:14:45 -0700494 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700495 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
496 }
deadbeefc80741f2015-10-22 13:14:45 -0700497 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700498 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
499 }
500
501 session_options->vad_enabled = rtc_options.voice_activity_detection;
502 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700503 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700504
505 return true;
506}
507
508bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
509 cricket::MediaSessionOptions* session_options) {
510 bool value = false;
511 size_t mandatory_constraints_satisfied = 0;
512
513 // kOfferToReceiveAudio defaults to true according to spec.
514 if (!FindConstraint(constraints,
515 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
516 &mandatory_constraints_satisfied) ||
517 value) {
518 session_options->recv_audio = true;
519 }
520
521 // kOfferToReceiveVideo defaults to false according to spec. But
522 // if it is an answer and video is offered, we should still accept video
523 // per default.
524 value = false;
525 if (!FindConstraint(constraints,
526 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
527 &mandatory_constraints_satisfied) ||
528 value) {
529 session_options->recv_video = true;
530 }
531
532 if (FindConstraint(constraints,
533 MediaConstraintsInterface::kVoiceActivityDetection, &value,
534 &mandatory_constraints_satisfied)) {
535 session_options->vad_enabled = value;
536 }
537
538 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
539 &mandatory_constraints_satisfied)) {
540 session_options->bundle_enabled = value;
541 } else {
542 // kUseRtpMux defaults to true according to spec.
543 session_options->bundle_enabled = true;
544 }
deadbeefab9b2d12015-10-14 11:33:11 -0700545
546 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
547 &value, &mandatory_constraints_satisfied)) {
548 session_options->transport_options.ice_restart = value;
549 } else {
550 // kIceRestart defaults to false according to spec.
551 session_options->transport_options.ice_restart = false;
552 }
553
554 if (!constraints) {
555 return true;
556 }
557 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
558}
559
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200560bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700561 StunConfigurations* stun_config,
562 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200563 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
564 if (!server.urls.empty()) {
565 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200566 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700567 LOG(LS_ERROR) << "Empty uri.";
568 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200569 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200570 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
571 return false;
572 }
573 }
574 } else if (!server.uri.empty()) {
575 // Fallback to old .uri if new .urls isn't present.
576 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000577 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200578 }
579 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700580 LOG(LS_ERROR) << "Empty uri.";
581 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000582 }
583 }
584 return true;
585}
586
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587PeerConnection::PeerConnection(PeerConnectionFactory* factory)
588 : factory_(factory),
589 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000590 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591 signaling_state_(kStable),
592 ice_state_(kIceNew),
593 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700594 ice_gathering_state_(kIceGatheringNew),
595 local_streams_(StreamCollection::Create()),
596 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597
598PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100599 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700600 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef38686922015-12-07 15:32:23 -0800601 // Finish any pending deletions.
602 signaling_thread()->Clear(this, MSG_DELETE, nullptr);
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();
1140
1141 // We wait to signal new streams until we finish processing the description,
1142 // since only at that point will new streams have all their tracks.
1143 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1144
1145 // Find all audio rtp streams and create corresponding remote AudioTracks
1146 // and MediaStreams.
1147 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1148 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001149 if (audio_content->rejected) {
1150 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1151 } else {
1152 const cricket::AudioContentDescription* desc =
1153 static_cast<const cricket::AudioContentDescription*>(
1154 audio_content->description);
1155 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(),
1156 new_streams);
1157 remote_info_.default_audio_track_needed =
1158 !remote_desc->msid_supported() && desc->streams().empty() &&
1159 MediaContentDirectionHasSend(desc->direction());
1160 }
deadbeefab9b2d12015-10-14 11:33:11 -07001161 }
1162
1163 // Find all video rtp streams and create corresponding remote VideoTracks
1164 // and MediaStreams.
1165 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1166 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001167 if (video_content->rejected) {
1168 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1169 } else {
1170 const cricket::VideoContentDescription* desc =
1171 static_cast<const cricket::VideoContentDescription*>(
1172 video_content->description);
1173 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(),
1174 new_streams);
1175 remote_info_.default_video_track_needed =
1176 !remote_desc->msid_supported() && desc->streams().empty() &&
1177 MediaContentDirectionHasSend(desc->direction());
1178 }
deadbeefab9b2d12015-10-14 11:33:11 -07001179 }
1180
1181 // Update the DataChannels with the information from the remote peer.
1182 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
1183 if (data_content) {
deadbeef5e97fb52015-10-15 12:49:08 -07001184 const cricket::DataContentDescription* desc =
deadbeefab9b2d12015-10-14 11:33:11 -07001185 static_cast<const cricket::DataContentDescription*>(
1186 data_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001187 if (rtc::starts_with(desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001188 cricket::kMediaProtocolRtpPrefix)) {
deadbeef5e97fb52015-10-15 12:49:08 -07001189 UpdateRemoteRtpDataChannels(GetActiveStreams(desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001190 }
1191 }
1192
1193 // Iterate new_streams and notify the observer about new MediaStreams.
1194 for (size_t i = 0; i < new_streams->count(); ++i) {
1195 MediaStreamInterface* new_stream = new_streams->at(i);
1196 stats_->AddStream(new_stream);
1197 observer_->OnAddStream(new_stream);
1198 }
1199
1200 // Find removed MediaStreams.
1201 if (remote_info_.IsDefaultMediaStreamNeeded() &&
1202 remote_streams_->find(kDefaultStreamLabel) != nullptr) {
1203 // The default media stream already exists. No need to do anything.
1204 } else {
1205 UpdateEndedRemoteMediaStreams();
1206 remote_info_.msid_supported |= remote_streams_->count() > 0;
1207 }
1208 MaybeCreateDefaultStream();
1209
1210 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1211 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001212}
1213
deadbeefa67696b2015-09-29 11:56:26 -07001214bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001215 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001216 if (port_allocator_) {
1217 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1218 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1219 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1220 return false;
1221 }
1222
deadbeef653b8e02015-11-11 12:55:10 -08001223 cricket::ServerAddresses cricket_stuns;
1224 std::vector<cricket::RelayServerConfig> cricket_turns;
1225 ConvertToCricketIceServers(stuns, turns, &cricket_stuns, &cricket_turns);
1226 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001227 }
honghaiz1f429e32015-09-28 07:57:34 -07001228 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001229 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001230}
1231
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232bool PeerConnection::AddIceCandidate(
1233 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001234 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 return session_->ProcessIceMessage(ice_candidate);
1236}
1237
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001238void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001239 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001240 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001241
1242 if (session_) {
1243 session_->set_metrics_observer(uma_observer_);
1244 }
1245
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001246 // Send information about IPv4/IPv6 status.
1247 if (uma_observer_ && port_allocator_) {
1248 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001249 uma_observer_->IncrementEnumCounter(
1250 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1251 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001252 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001253 uma_observer_->IncrementEnumCounter(
1254 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1255 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001256 }
1257 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001258}
1259
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260const SessionDescriptionInterface* PeerConnection::local_description() const {
1261 return session_->local_description();
1262}
1263
1264const SessionDescriptionInterface* PeerConnection::remote_description() const {
1265 return session_->remote_description();
1266}
1267
1268void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001269 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001270 // Update stats here so that we have the most recent stats for tracks and
1271 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001272 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273
deadbeefd59daf82015-10-14 15:02:44 -07001274 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001275}
1276
deadbeefd59daf82015-10-14 15:02:44 -07001277void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1278 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001280 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001282 break;
deadbeefd59daf82015-10-14 15:02:44 -07001283 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1285 break;
deadbeefd59daf82015-10-14 15:02:44 -07001286 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1288 break;
deadbeefd59daf82015-10-14 15:02:44 -07001289 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1291 break;
deadbeefd59daf82015-10-14 15:02:44 -07001292 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1294 break;
deadbeefd59daf82015-10-14 15:02:44 -07001295 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296 ChangeSignalingState(PeerConnectionInterface::kStable);
1297 break;
deadbeefd59daf82015-10-14 15:02:44 -07001298 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 ChangeSignalingState(PeerConnectionInterface::kClosed);
1300 break;
1301 default:
1302 break;
1303 }
1304}
1305
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001306void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1309 SetSessionDescriptionMsg* param =
1310 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1311 param->observer->OnSuccess();
1312 delete param;
1313 break;
1314 }
1315 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1316 SetSessionDescriptionMsg* param =
1317 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1318 param->observer->OnFailure(param->error);
1319 delete param;
1320 break;
1321 }
deadbeefab9b2d12015-10-14 11:33:11 -07001322 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1323 CreateSessionDescriptionMsg* param =
1324 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1325 param->observer->OnFailure(param->error);
1326 delete param;
1327 break;
1328 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 case MSG_GETSTATS: {
1330 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001331 StatsReports reports;
1332 stats_->GetStats(param->track, &reports);
1333 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 delete param;
1335 break;
1336 }
deadbeef38686922015-12-07 15:32:23 -08001337 case MSG_DELETE: {
1338 delete msg->pdata;
1339 break;
1340 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001341 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001342 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 break;
1344 }
1345}
1346
deadbeefab9b2d12015-10-14 11:33:11 -07001347void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1348 AudioTrackInterface* audio_track,
1349 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001350 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351}
1352
deadbeefab9b2d12015-10-14 11:33:11 -07001353void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1354 VideoTrackInterface* video_track,
1355 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001356 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357}
1358
deadbeef70ab1a12015-09-28 16:53:55 -07001359// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1360// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001361void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1362 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001363 auto it = FindReceiverForTrack(audio_track);
1364 if (it == receivers_.end()) {
1365 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1366 << " doesn't exist.";
1367 } else {
1368 (*it)->Stop();
1369 receivers_.erase(it);
1370 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371}
1372
deadbeefab9b2d12015-10-14 11:33:11 -07001373void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1374 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001375 auto it = FindReceiverForTrack(video_track);
1376 if (it == receivers_.end()) {
1377 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1378 << " doesn't exist.";
1379 } else {
1380 (*it)->Stop();
1381 receivers_.erase(it);
1382 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383}
deadbeef70ab1a12015-09-28 16:53:55 -07001384
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385void PeerConnection::OnIceConnectionChange(
1386 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001387 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001388 // After transitioning to "closed", ignore any additional states from
1389 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001390 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001391 return;
1392 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001394 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395}
1396
1397void PeerConnection::OnIceGatheringChange(
1398 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001399 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400 if (IsClosed()) {
1401 return;
1402 }
1403 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001404 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405}
1406
1407void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001408 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001409 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410}
1411
1412void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001413 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001414 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415}
1416
Peter Thatcher54360512015-07-08 11:08:35 -07001417void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001418 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001419 observer_->OnIceConnectionReceivingChange(receiving);
1420}
1421
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422void PeerConnection::ChangeSignalingState(
1423 PeerConnectionInterface::SignalingState signaling_state) {
1424 signaling_state_ = signaling_state;
1425 if (signaling_state == kClosed) {
1426 ice_connection_state_ = kIceConnectionClosed;
1427 observer_->OnIceConnectionChange(ice_connection_state_);
1428 if (ice_gathering_state_ != kIceGatheringComplete) {
1429 ice_gathering_state_ = kIceGatheringComplete;
1430 observer_->OnIceGatheringChange(ice_gathering_state_);
1431 }
1432 }
1433 observer_->OnSignalingChange(signaling_state_);
1434 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1435}
1436
deadbeefab9b2d12015-10-14 11:33:11 -07001437void PeerConnection::PostSetSessionDescriptionFailure(
1438 SetSessionDescriptionObserver* observer,
1439 const std::string& error) {
1440 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1441 msg->error = error;
1442 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1443}
1444
1445void PeerConnection::PostCreateSessionDescriptionFailure(
1446 CreateSessionDescriptionObserver* observer,
1447 const std::string& error) {
1448 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1449 msg->error = error;
1450 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1451}
1452
1453bool PeerConnection::GetOptionsForOffer(
1454 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1455 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001456 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1457 return false;
1458 }
1459
deadbeeffac06552015-11-25 11:26:01 -08001460 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001461 // Offer to receive audio/video if the constraint is not set and there are
1462 // send streams, or we're currently receiving.
1463 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1464 session_options->recv_audio =
1465 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1466 !remote_audio_tracks_.empty();
1467 }
1468 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1469 session_options->recv_video =
1470 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1471 !remote_video_tracks_.empty();
1472 }
1473 session_options->bundle_enabled =
1474 session_options->bundle_enabled &&
1475 (session_options->has_audio() || session_options->has_video() ||
1476 session_options->has_data());
1477
deadbeefab9b2d12015-10-14 11:33:11 -07001478 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1479 session_options->data_channel_type = cricket::DCT_SCTP;
1480 }
1481 return true;
1482}
1483
1484bool PeerConnection::GetOptionsForAnswer(
1485 const MediaConstraintsInterface* constraints,
1486 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001487 session_options->recv_audio = false;
1488 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001489 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1490 return false;
1491 }
1492
deadbeeffac06552015-11-25 11:26:01 -08001493 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001494 session_options->bundle_enabled =
1495 session_options->bundle_enabled &&
1496 (session_options->has_audio() || session_options->has_video() ||
1497 session_options->has_data());
1498
deadbeefab9b2d12015-10-14 11:33:11 -07001499 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1500 // are not signaled in the SDP so does not go through that path and must be
1501 // handled here.
1502 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1503 session_options->data_channel_type = cricket::DCT_SCTP;
1504 }
1505 return true;
1506}
1507
deadbeeffaac4972015-11-12 15:33:07 -08001508void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1509 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
1510 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), media_type,
1511 nullptr);
1512}
1513
deadbeefab9b2d12015-10-14 11:33:11 -07001514void PeerConnection::UpdateRemoteStreamsList(
1515 const cricket::StreamParamsVec& streams,
1516 cricket::MediaType media_type,
1517 StreamCollection* new_streams) {
1518 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1519
1520 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001521 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001522 auto track_it = current_tracks->begin();
1523 while (track_it != current_tracks->end()) {
1524 const TrackInfo& info = *track_it;
1525 const cricket::StreamParams* params =
1526 cricket::GetStreamBySsrc(streams, info.ssrc);
1527 if (!params || params->id != info.track_id) {
1528 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1529 track_it = current_tracks->erase(track_it);
1530 } else {
1531 ++track_it;
1532 }
1533 }
1534
1535 // Find new and active tracks.
1536 for (const cricket::StreamParams& params : streams) {
1537 // The sync_label is the MediaStream label and the |stream.id| is the
1538 // track id.
1539 const std::string& stream_label = params.sync_label;
1540 const std::string& track_id = params.id;
1541 uint32_t ssrc = params.first_ssrc();
1542
1543 rtc::scoped_refptr<MediaStreamInterface> stream =
1544 remote_streams_->find(stream_label);
1545 if (!stream) {
1546 // This is a new MediaStream. Create a new remote MediaStream.
1547 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1548 remote_streams_->AddStream(stream);
1549 new_streams->AddStream(stream);
1550 }
1551
1552 const TrackInfo* track_info =
1553 FindTrackInfo(*current_tracks, stream_label, track_id);
1554 if (!track_info) {
1555 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1556 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1557 }
1558 }
1559}
1560
1561void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1562 const std::string& track_id,
1563 uint32_t ssrc,
1564 cricket::MediaType media_type) {
1565 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1566
1567 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1568 AudioTrackInterface* audio_track =
1569 remote_stream_factory_->AddAudioTrack(stream, track_id);
1570 CreateAudioReceiver(stream, audio_track, ssrc);
1571 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1572 VideoTrackInterface* video_track =
1573 remote_stream_factory_->AddVideoTrack(stream, track_id);
1574 CreateVideoReceiver(stream, video_track, ssrc);
1575 } else {
1576 RTC_DCHECK(false && "Invalid media type");
1577 }
1578}
1579
1580void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1581 const std::string& track_id,
1582 cricket::MediaType media_type) {
1583 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1584
1585 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1586 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1587 stream->FindAudioTrack(track_id);
1588 if (audio_track) {
1589 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1590 stream->RemoveTrack(audio_track);
1591 DestroyAudioReceiver(stream, audio_track);
1592 }
1593 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1594 rtc::scoped_refptr<VideoTrackInterface> video_track =
1595 stream->FindVideoTrack(track_id);
1596 if (video_track) {
1597 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1598 stream->RemoveTrack(video_track);
1599 DestroyVideoReceiver(stream, video_track);
1600 }
1601 } else {
1602 ASSERT(false && "Invalid media type");
1603 }
1604}
1605
1606void PeerConnection::UpdateEndedRemoteMediaStreams() {
1607 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1608 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1609 MediaStreamInterface* stream = remote_streams_->at(i);
1610 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1611 streams_to_remove.push_back(stream);
1612 }
1613 }
1614
1615 for (const auto& stream : streams_to_remove) {
1616 remote_streams_->RemoveStream(stream);
1617 observer_->OnRemoveStream(stream);
1618 }
1619}
1620
1621void PeerConnection::MaybeCreateDefaultStream() {
1622 if (!remote_info_.IsDefaultMediaStreamNeeded()) {
1623 return;
1624 }
1625
1626 bool default_created = false;
1627
1628 rtc::scoped_refptr<MediaStreamInterface> default_remote_stream =
1629 remote_streams_->find(kDefaultStreamLabel);
1630 if (default_remote_stream == nullptr) {
1631 default_created = true;
1632 default_remote_stream =
1633 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1634 remote_streams_->AddStream(default_remote_stream);
1635 }
1636 if (remote_info_.default_audio_track_needed &&
1637 default_remote_stream->GetAudioTracks().size() == 0) {
1638 remote_audio_tracks_.push_back(
1639 TrackInfo(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0));
1640 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
1641 cricket::MEDIA_TYPE_AUDIO);
1642 }
1643 if (remote_info_.default_video_track_needed &&
1644 default_remote_stream->GetVideoTracks().size() == 0) {
1645 remote_video_tracks_.push_back(
1646 TrackInfo(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0));
1647 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
1648 cricket::MEDIA_TYPE_VIDEO);
1649 }
1650 if (default_created) {
1651 stats_->AddStream(default_remote_stream);
1652 observer_->OnAddStream(default_remote_stream);
1653 }
1654}
1655
1656void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1657 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1658 for (TrackInfos::iterator track_it = current_tracks->begin();
1659 track_it != current_tracks->end(); ++track_it) {
1660 const TrackInfo& info = *track_it;
1661 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1662 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1663 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1664 // There's no guarantee the track is still available, e.g. the track may
1665 // have been removed from the stream by javascript.
1666 if (track) {
1667 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1668 }
1669 }
1670 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1671 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1672 // There's no guarantee the track is still available, e.g. the track may
1673 // have been removed from the stream by javascript.
1674 if (track) {
1675 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1676 }
1677 }
1678 }
1679}
1680
1681void PeerConnection::UpdateLocalTracks(
1682 const std::vector<cricket::StreamParams>& streams,
1683 cricket::MediaType media_type) {
1684 TrackInfos* current_tracks = GetLocalTracks(media_type);
1685
1686 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1687 // don't match the new StreamParam.
1688 TrackInfos::iterator track_it = current_tracks->begin();
1689 while (track_it != current_tracks->end()) {
1690 const TrackInfo& info = *track_it;
1691 const cricket::StreamParams* params =
1692 cricket::GetStreamBySsrc(streams, info.ssrc);
1693 if (!params || params->id != info.track_id ||
1694 params->sync_label != info.stream_label) {
1695 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1696 media_type);
1697 track_it = current_tracks->erase(track_it);
1698 } else {
1699 ++track_it;
1700 }
1701 }
1702
1703 // Find new and active tracks.
1704 for (const cricket::StreamParams& params : streams) {
1705 // The sync_label is the MediaStream label and the |stream.id| is the
1706 // track id.
1707 const std::string& stream_label = params.sync_label;
1708 const std::string& track_id = params.id;
1709 uint32_t ssrc = params.first_ssrc();
1710 const TrackInfo* track_info =
1711 FindTrackInfo(*current_tracks, stream_label, track_id);
1712 if (!track_info) {
1713 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1714 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1715 }
1716 }
1717}
1718
1719void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1720 const std::string& track_id,
1721 uint32_t ssrc,
1722 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001723 RtpSenderInterface* sender = FindSenderById(track_id);
1724 if (!sender) {
1725 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1726 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001727 return;
1728 }
1729
deadbeeffac06552015-11-25 11:26:01 -08001730 if (sender->media_type() != media_type) {
1731 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1732 << " description with an unexpected media type.";
1733 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001734 }
deadbeeffac06552015-11-25 11:26:01 -08001735
1736 sender->set_stream_id(stream_label);
1737 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001738}
1739
1740void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1741 const std::string& track_id,
1742 uint32_t ssrc,
1743 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001744 RtpSenderInterface* sender = FindSenderById(track_id);
1745 if (!sender) {
1746 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001747 // SessionDescriptions has been renegotiated.
1748 return;
1749 }
deadbeeffac06552015-11-25 11:26:01 -08001750
1751 // A sender has been removed from the SessionDescription but it's still
1752 // associated with the PeerConnection. This only occurs if the SDP doesn't
1753 // match with the calls to CreateSender, AddStream and RemoveStream.
1754 if (sender->media_type() != media_type) {
1755 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1756 << " description with an unexpected media type.";
1757 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001758 }
deadbeeffac06552015-11-25 11:26:01 -08001759
1760 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001761}
1762
1763void PeerConnection::UpdateLocalRtpDataChannels(
1764 const cricket::StreamParamsVec& streams) {
1765 std::vector<std::string> existing_channels;
1766
1767 // Find new and active data channels.
1768 for (const cricket::StreamParams& params : streams) {
1769 // |it->sync_label| is actually the data channel label. The reason is that
1770 // we use the same naming of data channels as we do for
1771 // MediaStreams and Tracks.
1772 // For MediaStreams, the sync_label is the MediaStream label and the
1773 // track label is the same as |streamid|.
1774 const std::string& channel_label = params.sync_label;
1775 auto data_channel_it = rtp_data_channels_.find(channel_label);
1776 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1777 continue;
1778 }
1779 // Set the SSRC the data channel should use for sending.
1780 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1781 existing_channels.push_back(data_channel_it->first);
1782 }
1783
1784 UpdateClosingRtpDataChannels(existing_channels, true);
1785}
1786
1787void PeerConnection::UpdateRemoteRtpDataChannels(
1788 const cricket::StreamParamsVec& streams) {
1789 std::vector<std::string> existing_channels;
1790
1791 // Find new and active data channels.
1792 for (const cricket::StreamParams& params : streams) {
1793 // The data channel label is either the mslabel or the SSRC if the mslabel
1794 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1795 std::string label = params.sync_label.empty()
1796 ? rtc::ToString(params.first_ssrc())
1797 : params.sync_label;
1798 auto data_channel_it = rtp_data_channels_.find(label);
1799 if (data_channel_it == rtp_data_channels_.end()) {
1800 // This is a new data channel.
1801 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1802 } else {
1803 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1804 }
1805 existing_channels.push_back(label);
1806 }
1807
1808 UpdateClosingRtpDataChannels(existing_channels, false);
1809}
1810
1811void PeerConnection::UpdateClosingRtpDataChannels(
1812 const std::vector<std::string>& active_channels,
1813 bool is_local_update) {
1814 auto it = rtp_data_channels_.begin();
1815 while (it != rtp_data_channels_.end()) {
1816 DataChannel* data_channel = it->second;
1817 if (std::find(active_channels.begin(), active_channels.end(),
1818 data_channel->label()) != active_channels.end()) {
1819 ++it;
1820 continue;
1821 }
1822
1823 if (is_local_update) {
1824 data_channel->SetSendSsrc(0);
1825 } else {
1826 data_channel->RemotePeerRequestClose();
1827 }
1828
1829 if (data_channel->state() == DataChannel::kClosed) {
1830 rtp_data_channels_.erase(it);
1831 it = rtp_data_channels_.begin();
1832 } else {
1833 ++it;
1834 }
1835 }
1836}
1837
1838void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1839 uint32_t remote_ssrc) {
1840 rtc::scoped_refptr<DataChannel> channel(
1841 InternalCreateDataChannel(label, nullptr));
1842 if (!channel.get()) {
1843 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1844 << "CreateDataChannel failed.";
1845 return;
1846 }
1847 channel->SetReceiveSsrc(remote_ssrc);
1848 observer_->OnDataChannel(
1849 DataChannelProxy::Create(signaling_thread(), channel));
1850}
1851
1852rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1853 const std::string& label,
1854 const InternalDataChannelInit* config) {
1855 if (IsClosed()) {
1856 return nullptr;
1857 }
1858 if (session_->data_channel_type() == cricket::DCT_NONE) {
1859 LOG(LS_ERROR)
1860 << "InternalCreateDataChannel: Data is not supported in this call.";
1861 return nullptr;
1862 }
1863 InternalDataChannelInit new_config =
1864 config ? (*config) : InternalDataChannelInit();
1865 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1866 if (new_config.id < 0) {
1867 rtc::SSLRole role;
1868 if (session_->GetSslRole(&role) &&
1869 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1870 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1871 return nullptr;
1872 }
1873 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1874 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1875 << "because the id is already in use or out of range.";
1876 return nullptr;
1877 }
1878 }
1879
1880 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1881 session_.get(), session_->data_channel_type(), label, new_config));
1882 if (!channel) {
1883 sid_allocator_.ReleaseSid(new_config.id);
1884 return nullptr;
1885 }
1886
1887 if (channel->data_channel_type() == cricket::DCT_RTP) {
1888 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1889 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1890 << " already exists.";
1891 return nullptr;
1892 }
1893 rtp_data_channels_[channel->label()] = channel;
1894 } else {
1895 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1896 sctp_data_channels_.push_back(channel);
1897 channel->SignalClosed.connect(this,
1898 &PeerConnection::OnSctpDataChannelClosed);
1899 }
1900
1901 return channel;
1902}
1903
1904bool PeerConnection::HasDataChannels() const {
1905 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1906}
1907
1908void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1909 for (const auto& channel : sctp_data_channels_) {
1910 if (channel->id() < 0) {
1911 int sid;
1912 if (!sid_allocator_.AllocateSid(role, &sid)) {
1913 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1914 continue;
1915 }
1916 channel->SetSctpSid(sid);
1917 }
1918 }
1919}
1920
1921void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1922 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1923 ++it) {
1924 if (it->get() == channel) {
1925 if (channel->id() >= 0) {
1926 sid_allocator_.ReleaseSid(channel->id());
1927 }
deadbeef38686922015-12-07 15:32:23 -08001928 // Since this method is triggered by a signal from the DataChannel,
1929 // we can't free it directly here; we need to free it asynchronously.
1930 signaling_thread()->Post(
1931 this, MSG_DELETE,
1932 new rtc::TypedMessageData<rtc::scoped_refptr<DataChannel>>(channel));
deadbeefab9b2d12015-10-14 11:33:11 -07001933 sctp_data_channels_.erase(it);
1934 return;
1935 }
1936 }
1937}
1938
1939void PeerConnection::OnVoiceChannelDestroyed() {
1940 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1941}
1942
1943void PeerConnection::OnVideoChannelDestroyed() {
1944 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1945}
1946
1947void PeerConnection::OnDataChannelCreated() {
1948 for (const auto& channel : sctp_data_channels_) {
1949 channel->OnTransportChannelCreated();
1950 }
1951}
1952
1953void PeerConnection::OnDataChannelDestroyed() {
1954 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1955 // DataChannel may callback to us and try to modify the list.
1956 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1957 temp_rtp_dcs.swap(rtp_data_channels_);
1958 for (const auto& kv : temp_rtp_dcs) {
1959 kv.second->OnTransportChannelDestroyed();
1960 }
1961
1962 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1963 temp_sctp_dcs.swap(sctp_data_channels_);
1964 for (const auto& channel : temp_sctp_dcs) {
1965 channel->OnTransportChannelDestroyed();
1966 }
1967}
1968
1969void PeerConnection::OnDataChannelOpenMessage(
1970 const std::string& label,
1971 const InternalDataChannelInit& config) {
1972 rtc::scoped_refptr<DataChannel> channel(
1973 InternalCreateDataChannel(label, &config));
1974 if (!channel.get()) {
1975 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1976 return;
1977 }
1978
1979 observer_->OnDataChannel(
1980 DataChannelProxy::Create(signaling_thread(), channel));
1981}
1982
deadbeeffac06552015-11-25 11:26:01 -08001983RtpSenderInterface* PeerConnection::FindSenderById(const std::string& id) {
1984 auto it =
1985 std::find_if(senders_.begin(), senders_.end(),
1986 [id](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1987 return sender->id() == id;
1988 });
1989 return it != senders_.end() ? it->get() : nullptr;
1990}
1991
deadbeef70ab1a12015-09-28 16:53:55 -07001992std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1993PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1994 return std::find_if(
1995 senders_.begin(), senders_.end(),
1996 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1997 return sender->track() == track;
1998 });
1999}
2000
2001std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
2002PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
2003 return std::find_if(
2004 receivers_.begin(), receivers_.end(),
2005 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
2006 return receiver->track() == track;
2007 });
2008}
2009
deadbeefab9b2d12015-10-14 11:33:11 -07002010PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2011 cricket::MediaType media_type) {
2012 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2013 media_type == cricket::MEDIA_TYPE_VIDEO);
2014 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2015 : &remote_video_tracks_;
2016}
2017
2018PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2019 cricket::MediaType media_type) {
2020 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2021 media_type == cricket::MEDIA_TYPE_VIDEO);
2022 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2023 : &local_video_tracks_;
2024}
2025
2026const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2027 const PeerConnection::TrackInfos& infos,
2028 const std::string& stream_label,
2029 const std::string track_id) const {
2030 for (const TrackInfo& track_info : infos) {
2031 if (track_info.stream_label == stream_label &&
2032 track_info.track_id == track_id) {
2033 return &track_info;
2034 }
2035 }
2036 return nullptr;
2037}
2038
2039DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2040 for (const auto& channel : sctp_data_channels_) {
2041 if (channel->id() == sid) {
2042 return channel;
2043 }
2044 }
2045 return nullptr;
2046}
2047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048} // namespace webrtc