blob: ea28bf67cb1ff0642a4ff27c98b6b4661ae024bc [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.org269fb4b2014-10-28 22:20:11 +000049#include "webrtc/p2p/client/basicportallocator.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050#include "talk/session/media/channelmanager.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"
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +000054#include "webrtc/system_wrappers/interface/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
56namespace {
57
deadbeefab9b2d12015-10-14 11:33:11 -070058using webrtc::DataChannel;
59using webrtc::MediaConstraintsInterface;
60using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061using webrtc::PeerConnectionInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070062using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070063using webrtc::StunConfigurations;
64using webrtc::TurnConfigurations;
65typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
66 StunConfiguration;
67typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
68 TurnConfiguration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069
deadbeefab9b2d12015-10-14 11:33:11 -070070static const char kDefaultStreamLabel[] = "default";
71static const char kDefaultAudioTrackLabel[] = "defaulta0";
72static const char kDefaultVideoTrackLabel[] = "defaultv0";
73
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074// The min number of tokens must present in Turn host uri.
75// e.g. user@turn.example.org
76static const size_t kTurnHostTokensNum = 2;
77// Number of tokens must be preset when TURN uri has transport param.
78static const size_t kTurnTransportTokensNum = 2;
79// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000080static const int kDefaultStunPort = 3478;
81static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000083static const char kUdpTransportType[] = "udp";
84static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085
86// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070087static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
deadbeef0a6c4ca2015-10-06 11:38:28 -070089// NOTE: A loop below assumes that the first value of this enum is 0 and all
90// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070092 STUN = 0, // Indicates a STUN server.
93 STUNS, // Indicates a STUN server used with a TLS session.
94 TURN, // Indicates a TURN server
95 TURNS, // Indicates a TURN server used with a TLS session.
96 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097};
deadbeef0a6c4ca2015-10-06 11:38:28 -070098static_assert(INVALID == ARRAY_SIZE(kValidIceServiceTypes),
99 "kValidIceServiceTypes must have as many strings as ServiceType "
100 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101
102enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_GETSTATS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107};
108
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000109struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 explicit SetSessionDescriptionMsg(
111 webrtc::SetSessionDescriptionObserver* observer)
112 : observer(observer) {
113 }
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 std::string error;
117};
118
deadbeefab9b2d12015-10-14 11:33:11 -0700119struct CreateSessionDescriptionMsg : public rtc::MessageData {
120 explicit CreateSessionDescriptionMsg(
121 webrtc::CreateSessionDescriptionObserver* observer)
122 : observer(observer) {}
123
124 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
125 std::string error;
126};
127
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000128struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000129 GetStatsMsg(webrtc::StatsObserver* observer,
130 webrtc::MediaStreamTrackInterface* track)
131 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135};
136
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000137// |in_str| should be of format
138// stunURI = scheme ":" stun-host [ ":" stun-port ]
139// scheme = "stun" / "stuns"
140// stun-host = IP-literal / IPv4address / reg-name
141// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700142//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000143// draft-petithuguenin-behave-turn-uris-01
144// turnURI = scheme ":" turn-host [ ":" turn-port ]
145// turn-host = username@IP-literal / IPv4address / reg-name
146bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
147 ServiceType* service_type,
148 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200149 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700150 if (colonpos == std::string::npos) {
151 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000152 return false;
153 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700154 if ((colonpos + 1) == in_str.length()) {
155 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
156 return false;
157 }
158 *service_type = INVALID;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000159 for (size_t i = 0; i < ARRAY_SIZE(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700160 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000161 *service_type = static_cast<ServiceType>(i);
162 break;
163 }
164 }
165 if (*service_type == INVALID) {
166 return false;
167 }
168 *hostname = in_str.substr(colonpos + 1, std::string::npos);
169 return true;
170}
171
deadbeef0a6c4ca2015-10-06 11:38:28 -0700172bool ParsePort(const std::string& in_str, int* port) {
173 // Make sure port only contains digits. FromString doesn't check this.
174 for (const char& c : in_str) {
175 if (!std::isdigit(c)) {
176 return false;
177 }
178 }
179 return rtc::FromString(in_str, port);
180}
181
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000182// This method parses IPv6 and IPv4 literal strings, along with hostnames in
183// standard hostname:port format.
184// Consider following formats as correct.
185// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700186// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000187bool ParseHostnameAndPortFromString(const std::string& in_str,
188 std::string* host,
189 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700190 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000191 if (in_str.at(0) == '[') {
192 std::string::size_type closebracket = in_str.rfind(']');
193 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000194 std::string::size_type colonpos = in_str.find(':', closebracket);
195 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700196 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
197 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000198 return false;
199 }
200 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 } else {
203 return false;
204 }
205 } else {
206 std::string::size_type colonpos = in_str.find(':');
207 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700208 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000209 return false;
210 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700211 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000212 } else {
213 *host = in_str;
214 }
215 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700216 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000217}
218
deadbeef0a6c4ca2015-10-06 11:38:28 -0700219// Adds a StunConfiguration or TurnConfiguration to the appropriate list,
220// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200221bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
222 const std::string& url,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700223 StunConfigurations* stun_config,
224 TurnConfigurations* turn_config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000225 // draft-nandakumar-rtcweb-stun-uri-01
226 // stunURI = scheme ":" stun-host [ ":" stun-port ]
227 // scheme = "stun" / "stuns"
228 // stun-host = IP-literal / IPv4address / reg-name
229 // stun-port = *DIGIT
230
231 // draft-petithuguenin-behave-turn-uris-01
232 // turnURI = scheme ":" turn-host [ ":" turn-port ]
233 // [ "?transport=" transport ]
234 // scheme = "turn" / "turns"
235 // transport = "udp" / "tcp" / transport-ext
236 // transport-ext = 1*unreserved
237 // turn-host = IP-literal / IPv4address / reg-name
238 // turn-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700239 RTC_DCHECK(stun_config != nullptr);
240 RTC_DCHECK(turn_config != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200241 std::vector<std::string> tokens;
242 std::string turn_transport_type = kUdpTransportType;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700243 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200244 rtc::tokenize(url, '?', &tokens);
245 std::string uri_without_transport = tokens[0];
246 // Let's look into transport= param, if it exists.
247 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
248 std::string uri_transport_param = tokens[1];
249 rtc::tokenize(uri_transport_param, '=', &tokens);
250 if (tokens[0] == kTransport) {
251 // As per above grammar transport param will be consist of lower case
252 // letters.
253 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
254 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700255 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200257 turn_transport_type = tokens[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200259 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200261 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200263 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
264 &service_type,
265 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700266 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
267 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200268 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000269
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
271 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200272
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200273 // Let's break hostname.
274 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700275 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
276
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200277 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700278 if (tokens.size() > kTurnHostTokensNum) {
279 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
280 return false;
281 }
282 if (tokens.size() == kTurnHostTokensNum) {
283 if (tokens[0].empty() || tokens[1].empty()) {
284 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
285 return false;
286 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200287 username.assign(rtc::s_url_decode(tokens[0]));
288 hoststring = tokens[1];
289 } else {
290 hoststring = tokens[0];
291 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000292
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200293 int port = kDefaultStunPort;
294 if (service_type == TURNS) {
295 port = kDefaultStunTlsPort;
296 turn_transport_type = kTcpTransportType;
297 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000298
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 std::string address;
300 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700301 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
302 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200303 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000304
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200305 if (port <= 0 || port > 0xffff) {
306 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700307 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200308 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000309
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200310 switch (service_type) {
311 case STUN:
312 case STUNS:
313 stun_config->push_back(StunConfiguration(address, port));
314 break;
315 case TURN:
316 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200317 bool secure = (service_type == TURNS);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200318 turn_config->push_back(TurnConfiguration(address, port,
319 username,
320 server.password,
321 turn_transport_type,
322 secure));
323 break;
324 }
325 case INVALID:
326 default:
327 LOG(WARNING) << "Configuration not supported: " << url;
328 return false;
329 }
330 return true;
331}
332
deadbeefd3b26d92015-10-26 17:55:21 -0700333void ConvertToCricketIceServers(
334 const std::vector<StunConfiguration>& stuns,
335 const std::vector<TurnConfiguration>& turns,
336 cricket::ServerAddresses* cricket_stuns,
337 std::vector<cricket::RelayServerConfig>* cricket_turns) {
338 RTC_DCHECK(cricket_stuns && cricket_turns);
339 for (const StunConfiguration& stun : stuns) {
340 cricket_stuns->insert(stun.server);
341 }
342
343 int priority = static_cast<int>(turns.size() - 1);
344 for (const TurnConfiguration& turn : turns) {
345 cricket::RelayCredentials credentials(turn.username, turn.password);
346 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
347 cricket::ProtocolType protocol;
348 // Using VERIFY because ParseIceServers should have already caught an
349 // invalid transport type.
350 if (!VERIFY(
351 cricket::StringToProto(turn.transport_type.c_str(), &protocol))) {
352 LOG(LS_WARNING) << "Ignoring TURN server " << turn.server << ". "
353 << "Reason= Incorrect " << turn.transport_type
354 << " transport parameter.";
355 } else {
356 relay_server.ports.push_back(
357 cricket::ProtocolAddress(turn.server, protocol, turn.secure));
358 relay_server.credentials = credentials;
359 relay_server.priority = priority;
360 cricket_turns->push_back(relay_server);
361 }
362 // First in the list gets highest priority.
363 --priority;
364 }
365}
366
deadbeefab9b2d12015-10-14 11:33:11 -0700367// Check if we can send |new_stream| on a PeerConnection.
368bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
369 webrtc::MediaStreamInterface* new_stream) {
370 if (!new_stream || !current_streams) {
371 return false;
372 }
373 if (current_streams->find(new_stream->label()) != nullptr) {
374 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
375 << " is already added.";
376 return false;
377 }
378 return true;
379}
380
381bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
382 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
383}
384
deadbeef5e97fb52015-10-15 12:49:08 -0700385// If the direction is "recvonly" or "inactive", treat the description
386// as containing no streams.
387// See: https://code.google.com/p/webrtc/issues/detail?id=5054
388std::vector<cricket::StreamParams> GetActiveStreams(
389 const cricket::MediaContentDescription* desc) {
390 return MediaContentDirectionHasSend(desc->direction())
391 ? desc->streams()
392 : std::vector<cricket::StreamParams>();
393}
394
deadbeefab9b2d12015-10-14 11:33:11 -0700395bool IsValidOfferToReceiveMedia(int value) {
396 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
397 return (value >= Options::kUndefined) &&
398 (value <= Options::kMaxOfferToReceiveMedia);
399}
400
401// Add the stream and RTP data channel info to |session_options|.
deadbeef8f46c632015-10-26 14:11:17 -0700402void SetStreams(cricket::MediaSessionOptions* session_options,
403 rtc::scoped_refptr<StreamCollection> streams,
404 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
405 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700406 session_options->streams.clear();
deadbeef8f46c632015-10-26 14:11:17 -0700407 if (streams != nullptr) {
408 for (size_t i = 0; i < streams->count(); ++i) {
409 MediaStreamInterface* stream = streams->at(i);
410 // For each audio track in the stream, add it to the MediaSessionOptions.
411 for (const auto& track : stream->GetAudioTracks()) {
412 session_options->AddSendStream(cricket::MEDIA_TYPE_AUDIO, track->id(),
413 stream->label());
414 }
415 // For each video track in the stream, add it to the MediaSessionOptions.
416 for (const auto& track : stream->GetVideoTracks()) {
417 session_options->AddSendStream(cricket::MEDIA_TYPE_VIDEO, track->id(),
418 stream->label());
419 }
420 }
deadbeefab9b2d12015-10-14 11:33:11 -0700421 }
422
423 // Check for data channels.
424 for (const auto& kv : rtp_data_channels) {
425 const DataChannel* channel = kv.second;
426 if (channel->state() == DataChannel::kConnecting ||
427 channel->state() == DataChannel::kOpen) {
428 // |streamid| and |sync_label| are both set to the DataChannel label
429 // here so they can be signaled the same way as MediaStreams and Tracks.
430 // For MediaStreams, the sync_label is the MediaStream label and the
431 // track label is the same as |streamid|.
432 const std::string& streamid = channel->label();
433 const std::string& sync_label = channel->label();
434 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
435 sync_label);
436 }
437 }
438}
439
deadbeef0a6c4ca2015-10-06 11:38:28 -0700440} // namespace
441
442namespace webrtc {
443
deadbeefab9b2d12015-10-14 11:33:11 -0700444// Factory class for creating remote MediaStreams and MediaStreamTracks.
445class RemoteMediaStreamFactory {
446 public:
447 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
448 cricket::ChannelManager* channel_manager)
449 : signaling_thread_(signaling_thread),
450 channel_manager_(channel_manager) {}
451
452 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
453 const std::string& stream_label) {
454 return MediaStreamProxy::Create(signaling_thread_,
455 MediaStream::Create(stream_label));
456 }
457
458 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
459 const std::string& track_id) {
460 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
461 stream, track_id, RemoteAudioSource::Create().get());
462 }
463
464 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
465 const std::string& track_id) {
466 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
467 stream, track_id,
468 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
469 nullptr)
470 .get());
471 }
472
473 private:
474 template <typename TI, typename T, typename TP, typename S>
475 TI* AddTrack(MediaStreamInterface* stream,
476 const std::string& track_id,
477 S* source) {
478 rtc::scoped_refptr<TI> track(
479 TP::Create(signaling_thread_, T::Create(track_id, source)));
480 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
481 if (stream->AddTrack(track)) {
482 return track;
483 }
484 return nullptr;
485 }
486
487 rtc::Thread* signaling_thread_;
488 cricket::ChannelManager* channel_manager_;
489};
490
491bool ConvertRtcOptionsForOffer(
492 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
493 cricket::MediaSessionOptions* session_options) {
494 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
495 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
496 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
497 return false;
498 }
499
deadbeefc80741f2015-10-22 13:14:45 -0700500 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700501 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
502 }
deadbeefc80741f2015-10-22 13:14:45 -0700503 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700504 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
505 }
506
507 session_options->vad_enabled = rtc_options.voice_activity_detection;
508 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700509 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700510
511 return true;
512}
513
514bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
515 cricket::MediaSessionOptions* session_options) {
516 bool value = false;
517 size_t mandatory_constraints_satisfied = 0;
518
519 // kOfferToReceiveAudio defaults to true according to spec.
520 if (!FindConstraint(constraints,
521 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
522 &mandatory_constraints_satisfied) ||
523 value) {
524 session_options->recv_audio = true;
525 }
526
527 // kOfferToReceiveVideo defaults to false according to spec. But
528 // if it is an answer and video is offered, we should still accept video
529 // per default.
530 value = false;
531 if (!FindConstraint(constraints,
532 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
533 &mandatory_constraints_satisfied) ||
534 value) {
535 session_options->recv_video = true;
536 }
537
538 if (FindConstraint(constraints,
539 MediaConstraintsInterface::kVoiceActivityDetection, &value,
540 &mandatory_constraints_satisfied)) {
541 session_options->vad_enabled = value;
542 }
543
544 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
545 &mandatory_constraints_satisfied)) {
546 session_options->bundle_enabled = value;
547 } else {
548 // kUseRtpMux defaults to true according to spec.
549 session_options->bundle_enabled = true;
550 }
deadbeefab9b2d12015-10-14 11:33:11 -0700551
552 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
553 &value, &mandatory_constraints_satisfied)) {
554 session_options->transport_options.ice_restart = value;
555 } else {
556 // kIceRestart defaults to false according to spec.
557 session_options->transport_options.ice_restart = false;
558 }
559
560 if (!constraints) {
561 return true;
562 }
563 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
564}
565
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200566bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700567 StunConfigurations* stun_config,
568 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200569 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
570 if (!server.urls.empty()) {
571 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200572 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700573 LOG(LS_ERROR) << "Empty uri.";
574 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200575 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200576 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
577 return false;
578 }
579 }
580 } else if (!server.uri.empty()) {
581 // Fallback to old .uri if new .urls isn't present.
582 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000583 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200584 }
585 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700586 LOG(LS_ERROR) << "Empty uri.";
587 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000588 }
589 }
590 return true;
591}
592
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593PeerConnection::PeerConnection(PeerConnectionFactory* factory)
594 : factory_(factory),
595 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000596 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597 signaling_state_(kStable),
598 ice_state_(kIceNew),
599 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700600 ice_gathering_state_(kIceGatheringNew),
601 local_streams_(StreamCollection::Create()),
602 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603
604PeerConnection::~PeerConnection() {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700605 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700606 // Need to detach RTP senders/receivers from WebRtcSession,
607 // since it's about to be destroyed.
608 for (const auto& sender : senders_) {
609 sender->Stop();
610 }
611 for (const auto& receiver : receivers_) {
612 receiver->Stop();
613 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000614}
615
616bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000617 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000618 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000619 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200620 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700622 RTC_DCHECK(observer != nullptr);
623 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000624 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700625 }
deadbeefd3b26d92015-10-26 17:55:21 -0700626
627 // This Initialize function parses ICE servers an extra time, but it will
628 // be removed once all PortAllocaotrs support SetIceServers.
629 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
630 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
631 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
632 return false;
633 }
634 rtc::scoped_ptr<cricket::PortAllocator> allocator(
635 allocator_factory->CreatePortAllocator(stun_config, turn_config));
636 return Initialize(configuration, constraints, allocator.Pass(),
637 dtls_identity_store.Pass(), observer);
638}
639
640bool PeerConnection::Initialize(
641 const PeerConnectionInterface::RTCConfiguration& configuration,
642 const MediaConstraintsInterface* constraints,
643 rtc::scoped_ptr<cricket::PortAllocator> allocator,
644 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
645 PeerConnectionObserver* observer) {
646 RTC_DCHECK(observer != nullptr);
647 if (!observer) {
648 return false;
649 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000650 observer_ = observer;
651
deadbeefd3b26d92015-10-26 17:55:21 -0700652 port_allocator_ = allocator.Pass();
653
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000654 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
655 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000656 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 return false;
658 }
deadbeefd3b26d92015-10-26 17:55:21 -0700659
660 cricket::ServerAddresses cricket_stuns;
661 std::vector<cricket::RelayServerConfig> cricket_turns;
662 ConvertToCricketIceServers(stun_config, turn_config, &cricket_stuns,
663 &cricket_turns);
664 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000665
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000667 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000668 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700669 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000670 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000671 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000672 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700673 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
674 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000675 if (!value) {
676 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000677 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000678 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000679 "Disabled") {
680 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000681 }
682
Jiayang Liucac1b382015-04-30 12:35:24 -0700683 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
684 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
685 LOG(LS_INFO) << "TCP candidates are disabled.";
686 }
687
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000688 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 // No step delay is used while allocating ports.
690 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
691
stefanc1aeaf02015-10-15 07:26:07 -0700692 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693
stefanc1aeaf02015-10-15 07:26:07 -0700694 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
695 factory_->signaling_thread(), media_controller_->channel_manager()));
696
697 session_.reset(
698 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
699 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700700 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701
702 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000703 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700704 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700706 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708 // Register PeerConnection as receiver of local ice candidates.
709 // All the callbacks will be posted to the application from PeerConnection.
710 session_->RegisterIceObserver(this);
711 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700712 session_->SignalVoiceChannelDestroyed.connect(
713 this, &PeerConnection::OnVoiceChannelDestroyed);
714 session_->SignalVideoChannelDestroyed.connect(
715 this, &PeerConnection::OnVideoChannelDestroyed);
716 session_->SignalDataChannelCreated.connect(
717 this, &PeerConnection::OnDataChannelCreated);
718 session_->SignalDataChannelDestroyed.connect(
719 this, &PeerConnection::OnDataChannelDestroyed);
720 session_->SignalDataChannelOpenMessage.connect(
721 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 return true;
723}
724
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000725rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700727 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728}
729
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000730rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700732 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733}
734
deadbeef8f46c632015-10-26 14:11:17 -0700735// TODO(deadbeef): Create RtpSenders immediately here, even if local
736// description hasn't yet been set.
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000737bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000738 if (IsClosed()) {
739 return false;
740 }
deadbeefab9b2d12015-10-14 11:33:11 -0700741 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742 return false;
743 }
deadbeefab9b2d12015-10-14 11:33:11 -0700744
745 local_streams_->AddStream(local_stream);
746
deadbeef8f46c632015-10-26 14:11:17 -0700747 // Find tracks that have already been configured in SDP. This can occur if a
748 // local session description that contains the MSID of these tracks is set
749 // before AddLocalStream is called. It can also occur if the local session
750 // description is not changed and RemoveLocalStream is called and later
751 // AddLocalStream is called again with the same stream.
deadbeefab9b2d12015-10-14 11:33:11 -0700752 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700753 const TrackInfo* track_info =
754 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
755 if (track_info) {
756 CreateAudioSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700757 }
758 }
759 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700760 const TrackInfo* track_info =
761 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
762 if (track_info) {
763 CreateVideoSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700764 }
765 }
766
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000767 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000768 observer_->OnRenegotiationNeeded();
769 return true;
770}
771
deadbeefab9b2d12015-10-14 11:33:11 -0700772// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
deadbeef8f46c632015-10-26 14:11:17 -0700773// indefinitely.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000774void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
deadbeefab9b2d12015-10-14 11:33:11 -0700775 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700776 const TrackInfo* track_info =
777 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
778 if (track_info) {
779 DestroyAudioSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700780 }
781 }
782 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700783 const TrackInfo* track_info =
784 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
785 if (track_info) {
786 DestroyVideoSender(local_stream, track.get());
deadbeefab9b2d12015-10-14 11:33:11 -0700787 }
788 }
789
790 local_streams_->RemoveStream(local_stream);
791
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000792 if (IsClosed()) {
793 return;
794 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 observer_->OnRenegotiationNeeded();
796}
797
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000798rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799 AudioTrackInterface* track) {
800 if (!track) {
801 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
802 return NULL;
803 }
deadbeefab9b2d12015-10-14 11:33:11 -0700804 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
806 return NULL;
807 }
808
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000809 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810 DtmfSender::Create(track, signaling_thread(), session_.get()));
811 if (!sender.get()) {
812 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
813 return NULL;
814 }
815 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
816}
817
deadbeef70ab1a12015-09-28 16:53:55 -0700818std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
819 const {
820 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
821 for (const auto& sender : senders_) {
822 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
823 }
824 return senders;
825}
826
827std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
828PeerConnection::GetReceivers() const {
829 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
830 for (const auto& receiver : receivers_) {
831 receivers.push_back(
832 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
833 }
834 return receivers;
835}
836
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000837bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000838 MediaStreamTrackInterface* track,
839 StatsOutputLevel level) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700840 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 if (!VERIFY(observer != NULL)) {
842 LOG(LS_ERROR) << "GetStats - observer is NULL.";
843 return false;
844 }
845
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000846 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000847 signaling_thread()->Post(this, MSG_GETSTATS,
848 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849 return true;
850}
851
852PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
853 return signaling_state_;
854}
855
856PeerConnectionInterface::IceState PeerConnection::ice_state() {
857 return ice_state_;
858}
859
860PeerConnectionInterface::IceConnectionState
861PeerConnection::ice_connection_state() {
862 return ice_connection_state_;
863}
864
865PeerConnectionInterface::IceGatheringState
866PeerConnection::ice_gathering_state() {
867 return ice_gathering_state_;
868}
869
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000870rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871PeerConnection::CreateDataChannel(
872 const std::string& label,
873 const DataChannelInit* config) {
deadbeefab9b2d12015-10-14 11:33:11 -0700874 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000875
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000876 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000877 if (config) {
878 internal_config.reset(new InternalDataChannelInit(*config));
879 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000880 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700881 InternalCreateDataChannel(label, internal_config.get()));
882 if (!channel.get()) {
883 return nullptr;
884 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000885
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000886 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
887 // the first SCTP DataChannel.
888 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
889 observer_->OnRenegotiationNeeded();
890 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000891
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892 return DataChannelProxy::Create(signaling_thread(), channel.get());
893}
894
895void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
896 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700897 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
899 return;
900 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000901 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000902
903 bool value;
904 size_t mandatory_constraints = 0;
905
906 if (FindConstraint(constraints,
907 MediaConstraintsInterface::kOfferToReceiveAudio,
908 &value,
909 &mandatory_constraints)) {
910 options.offer_to_receive_audio =
911 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
912 }
913
914 if (FindConstraint(constraints,
915 MediaConstraintsInterface::kOfferToReceiveVideo,
916 &value,
917 &mandatory_constraints)) {
918 options.offer_to_receive_video =
919 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
920 }
921
922 if (FindConstraint(constraints,
923 MediaConstraintsInterface::kVoiceActivityDetection,
924 &value,
925 &mandatory_constraints)) {
926 options.voice_activity_detection = value;
927 }
928
929 if (FindConstraint(constraints,
930 MediaConstraintsInterface::kIceRestart,
931 &value,
932 &mandatory_constraints)) {
933 options.ice_restart = value;
934 }
935
936 if (FindConstraint(constraints,
937 MediaConstraintsInterface::kUseRtpMux,
938 &value,
939 &mandatory_constraints)) {
940 options.use_rtp_mux = value;
941 }
942
943 CreateOffer(observer, options);
944}
945
946void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
947 const RTCOfferAnswerOptions& options) {
deadbeefab9b2d12015-10-14 11:33:11 -0700948 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000949 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
950 return;
951 }
deadbeefab9b2d12015-10-14 11:33:11 -0700952
953 cricket::MediaSessionOptions session_options;
954 if (!GetOptionsForOffer(options, &session_options)) {
955 std::string error = "CreateOffer called with invalid options.";
956 LOG(LS_ERROR) << error;
957 PostCreateSessionDescriptionFailure(observer, error);
958 return;
959 }
960
961 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962}
963
964void PeerConnection::CreateAnswer(
965 CreateSessionDescriptionObserver* observer,
966 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700967 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
969 return;
970 }
deadbeefab9b2d12015-10-14 11:33:11 -0700971
972 cricket::MediaSessionOptions session_options;
973 if (!GetOptionsForAnswer(constraints, &session_options)) {
974 std::string error = "CreateAnswer called with invalid constraints.";
975 LOG(LS_ERROR) << error;
976 PostCreateSessionDescriptionFailure(observer, error);
977 return;
978 }
979
980 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000981}
982
983void PeerConnection::SetLocalDescription(
984 SetSessionDescriptionObserver* observer,
985 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -0700986 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
988 return;
989 }
990 if (!desc) {
991 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
992 return;
993 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 // Update stats here so that we have the most recent stats for tracks and
995 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000996 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 std::string error;
998 if (!session_->SetLocalDescription(desc, &error)) {
999 PostSetSessionDescriptionFailure(observer, error);
1000 return;
1001 }
deadbeefab9b2d12015-10-14 11:33:11 -07001002
1003 // If setting the description decided our SSL role, allocate any necessary
1004 // SCTP sids.
1005 rtc::SSLRole role;
1006 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1007 session_->GetSslRole(&role)) {
1008 AllocateSctpSids(role);
1009 }
1010
1011 // Update state and SSRC of local MediaStreams and DataChannels based on the
1012 // local session description.
1013 const cricket::ContentInfo* audio_content =
1014 GetFirstAudioContent(desc->description());
1015 if (audio_content) {
1016 const cricket::AudioContentDescription* audio_desc =
1017 static_cast<const cricket::AudioContentDescription*>(
1018 audio_content->description);
1019 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1020 }
1021
1022 const cricket::ContentInfo* video_content =
1023 GetFirstVideoContent(desc->description());
1024 if (video_content) {
1025 const cricket::VideoContentDescription* video_desc =
1026 static_cast<const cricket::VideoContentDescription*>(
1027 video_content->description);
1028 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1029 }
1030
1031 const cricket::ContentInfo* data_content =
1032 GetFirstDataContent(desc->description());
1033 if (data_content) {
1034 const cricket::DataContentDescription* data_desc =
1035 static_cast<const cricket::DataContentDescription*>(
1036 data_content->description);
1037 if (rtc::starts_with(data_desc->protocol().data(),
1038 cricket::kMediaProtocolRtpPrefix)) {
1039 UpdateLocalRtpDataChannels(data_desc->streams());
1040 }
1041 }
1042
1043 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001045
deadbeefcbecd352015-09-23 11:50:27 -07001046 // MaybeStartGathering needs to be called after posting
1047 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1048 // before signaling that SetLocalDescription completed.
1049 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050}
1051
1052void PeerConnection::SetRemoteDescription(
1053 SetSessionDescriptionObserver* observer,
1054 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -07001055 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1057 return;
1058 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059 if (!desc) {
1060 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1061 return;
1062 }
1063 // Update stats here so that we have the most recent stats for tracks and
1064 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001065 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 std::string error;
1067 if (!session_->SetRemoteDescription(desc, &error)) {
1068 PostSetSessionDescriptionFailure(observer, error);
1069 return;
1070 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071
deadbeefab9b2d12015-10-14 11:33:11 -07001072 // If setting the description decided our SSL role, allocate any necessary
1073 // SCTP sids.
1074 rtc::SSLRole role;
1075 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1076 session_->GetSslRole(&role)) {
1077 AllocateSctpSids(role);
1078 }
1079
1080 const cricket::SessionDescription* remote_desc = desc->description();
1081
1082 // We wait to signal new streams until we finish processing the description,
1083 // since only at that point will new streams have all their tracks.
1084 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1085
1086 // Find all audio rtp streams and create corresponding remote AudioTracks
1087 // and MediaStreams.
1088 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1089 if (audio_content) {
1090 const cricket::AudioContentDescription* desc =
1091 static_cast<const cricket::AudioContentDescription*>(
1092 audio_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001093 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(), new_streams);
deadbeefab9b2d12015-10-14 11:33:11 -07001094 remote_info_.default_audio_track_needed =
deadbeefc80741f2015-10-22 13:14:45 -07001095 !remote_desc->msid_supported() && desc->streams().empty() &&
1096 MediaContentDirectionHasSend(desc->direction());
deadbeefab9b2d12015-10-14 11:33:11 -07001097 }
1098
1099 // Find all video rtp streams and create corresponding remote VideoTracks
1100 // and MediaStreams.
1101 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1102 if (video_content) {
1103 const cricket::VideoContentDescription* desc =
1104 static_cast<const cricket::VideoContentDescription*>(
1105 video_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001106 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(), new_streams);
deadbeefab9b2d12015-10-14 11:33:11 -07001107 remote_info_.default_video_track_needed =
deadbeefc80741f2015-10-22 13:14:45 -07001108 !remote_desc->msid_supported() && desc->streams().empty() &&
1109 MediaContentDirectionHasSend(desc->direction());
deadbeefab9b2d12015-10-14 11:33:11 -07001110 }
1111
1112 // Update the DataChannels with the information from the remote peer.
1113 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
1114 if (data_content) {
deadbeef5e97fb52015-10-15 12:49:08 -07001115 const cricket::DataContentDescription* desc =
deadbeefab9b2d12015-10-14 11:33:11 -07001116 static_cast<const cricket::DataContentDescription*>(
1117 data_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001118 if (rtc::starts_with(desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001119 cricket::kMediaProtocolRtpPrefix)) {
deadbeef5e97fb52015-10-15 12:49:08 -07001120 UpdateRemoteRtpDataChannels(GetActiveStreams(desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001121 }
1122 }
1123
1124 // Iterate new_streams and notify the observer about new MediaStreams.
1125 for (size_t i = 0; i < new_streams->count(); ++i) {
1126 MediaStreamInterface* new_stream = new_streams->at(i);
1127 stats_->AddStream(new_stream);
1128 observer_->OnAddStream(new_stream);
1129 }
1130
1131 // Find removed MediaStreams.
1132 if (remote_info_.IsDefaultMediaStreamNeeded() &&
1133 remote_streams_->find(kDefaultStreamLabel) != nullptr) {
1134 // The default media stream already exists. No need to do anything.
1135 } else {
1136 UpdateEndedRemoteMediaStreams();
1137 remote_info_.msid_supported |= remote_streams_->count() > 0;
1138 }
1139 MaybeCreateDefaultStream();
1140
1141 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1142 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001143}
1144
deadbeefa67696b2015-09-29 11:56:26 -07001145bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001146 if (port_allocator_) {
1147 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1148 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1149 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1150 return false;
1151 }
1152
deadbeefd3b26d92015-10-26 17:55:21 -07001153 cricket::ServerAddresses cricket_stuns;
1154 std::vector<cricket::RelayServerConfig> cricket_turns;
1155 ConvertToCricketIceServers(stuns, turns, &cricket_stuns, &cricket_turns);
1156 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001157 }
honghaiz1f429e32015-09-28 07:57:34 -07001158 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001159 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001160}
1161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162bool PeerConnection::AddIceCandidate(
1163 const IceCandidateInterface* ice_candidate) {
1164 return session_->ProcessIceMessage(ice_candidate);
1165}
1166
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001167void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
1168 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001169
1170 if (session_) {
1171 session_->set_metrics_observer(uma_observer_);
1172 }
1173
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001174 // Send information about IPv4/IPv6 status.
1175 if (uma_observer_ && port_allocator_) {
1176 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001177 uma_observer_->IncrementEnumCounter(
1178 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1179 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001180 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001181 uma_observer_->IncrementEnumCounter(
1182 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1183 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001184 }
1185 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001186}
1187
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188const SessionDescriptionInterface* PeerConnection::local_description() const {
1189 return session_->local_description();
1190}
1191
1192const SessionDescriptionInterface* PeerConnection::remote_description() const {
1193 return session_->remote_description();
1194}
1195
1196void PeerConnection::Close() {
1197 // Update stats here so that we have the most recent stats for tracks and
1198 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001199 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200
deadbeefd59daf82015-10-14 15:02:44 -07001201 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202}
1203
deadbeefd59daf82015-10-14 15:02:44 -07001204void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1205 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001207 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001208 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001209 break;
deadbeefd59daf82015-10-14 15:02:44 -07001210 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1212 break;
deadbeefd59daf82015-10-14 15:02:44 -07001213 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001214 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1215 break;
deadbeefd59daf82015-10-14 15:02:44 -07001216 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1218 break;
deadbeefd59daf82015-10-14 15:02:44 -07001219 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1221 break;
deadbeefd59daf82015-10-14 15:02:44 -07001222 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223 ChangeSignalingState(PeerConnectionInterface::kStable);
1224 break;
deadbeefd59daf82015-10-14 15:02:44 -07001225 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001226 ChangeSignalingState(PeerConnectionInterface::kClosed);
1227 break;
1228 default:
1229 break;
1230 }
1231}
1232
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001233void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001234 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1236 SetSessionDescriptionMsg* param =
1237 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1238 param->observer->OnSuccess();
1239 delete param;
1240 break;
1241 }
1242 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1243 SetSessionDescriptionMsg* param =
1244 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1245 param->observer->OnFailure(param->error);
1246 delete param;
1247 break;
1248 }
deadbeefab9b2d12015-10-14 11:33:11 -07001249 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1250 CreateSessionDescriptionMsg* param =
1251 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1252 param->observer->OnFailure(param->error);
1253 delete param;
1254 break;
1255 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 case MSG_GETSTATS: {
1257 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001258 StatsReports reports;
1259 stats_->GetStats(param->track, &reports);
1260 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261 delete param;
1262 break;
1263 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001265 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266 break;
1267 }
1268}
1269
deadbeefab9b2d12015-10-14 11:33:11 -07001270void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1271 AudioTrackInterface* audio_track,
1272 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001273 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274}
1275
deadbeefab9b2d12015-10-14 11:33:11 -07001276void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1277 VideoTrackInterface* video_track,
1278 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001279 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280}
1281
deadbeef70ab1a12015-09-28 16:53:55 -07001282// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1283// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001284void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1285 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001286 auto it = FindReceiverForTrack(audio_track);
1287 if (it == receivers_.end()) {
1288 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1289 << " doesn't exist.";
1290 } else {
1291 (*it)->Stop();
1292 receivers_.erase(it);
1293 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001294}
1295
deadbeefab9b2d12015-10-14 11:33:11 -07001296void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1297 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001298 auto it = FindReceiverForTrack(video_track);
1299 if (it == receivers_.end()) {
1300 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1301 << " doesn't exist.";
1302 } else {
1303 (*it)->Stop();
1304 receivers_.erase(it);
1305 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306}
deadbeef70ab1a12015-09-28 16:53:55 -07001307
deadbeef8f46c632015-10-26 14:11:17 -07001308void PeerConnection::CreateAudioSender(MediaStreamInterface* stream,
1309 AudioTrackInterface* audio_track,
1310 uint32_t ssrc) {
1311 senders_.push_back(new AudioRtpSender(audio_track, ssrc, session_.get()));
1312 stats_->AddLocalAudioTrack(audio_track, ssrc);
1313}
1314
1315void PeerConnection::CreateVideoSender(MediaStreamInterface* stream,
1316 VideoTrackInterface* video_track,
1317 uint32_t ssrc) {
1318 senders_.push_back(new VideoRtpSender(video_track, ssrc, session_.get()));
1319}
1320
1321// TODO(deadbeef): Keep RtpSenders around even if track goes away in local
1322// description.
1323void PeerConnection::DestroyAudioSender(MediaStreamInterface* stream,
1324 AudioTrackInterface* audio_track,
1325 uint32_t ssrc) {
1326 auto it = FindSenderForTrack(audio_track);
1327 if (it == senders_.end()) {
1328 LOG(LS_WARNING) << "RtpSender for track with id " << audio_track->id()
1329 << " doesn't exist.";
1330 return;
1331 } else {
1332 (*it)->Stop();
1333 senders_.erase(it);
1334 }
1335 stats_->RemoveLocalAudioTrack(audio_track, ssrc);
1336}
1337
1338void PeerConnection::DestroyVideoSender(MediaStreamInterface* stream,
1339 VideoTrackInterface* video_track) {
1340 auto it = FindSenderForTrack(video_track);
1341 if (it == senders_.end()) {
1342 LOG(LS_WARNING) << "RtpSender for track with id " << video_track->id()
1343 << " doesn't exist.";
1344 return;
1345 } else {
1346 (*it)->Stop();
1347 senders_.erase(it);
1348 }
1349}
1350
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351void PeerConnection::OnIceConnectionChange(
1352 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001353 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001354 // After transitioning to "closed", ignore any additional states from
1355 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001356 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001357 return;
1358 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001360 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361}
1362
1363void PeerConnection::OnIceGatheringChange(
1364 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001365 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 if (IsClosed()) {
1367 return;
1368 }
1369 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001370 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371}
1372
1373void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001374 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001375 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376}
1377
1378void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001379 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001380 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381}
1382
Peter Thatcher54360512015-07-08 11:08:35 -07001383void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001384 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001385 observer_->OnIceConnectionReceivingChange(receiving);
1386}
1387
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388void PeerConnection::ChangeSignalingState(
1389 PeerConnectionInterface::SignalingState signaling_state) {
1390 signaling_state_ = signaling_state;
1391 if (signaling_state == kClosed) {
1392 ice_connection_state_ = kIceConnectionClosed;
1393 observer_->OnIceConnectionChange(ice_connection_state_);
1394 if (ice_gathering_state_ != kIceGatheringComplete) {
1395 ice_gathering_state_ = kIceGatheringComplete;
1396 observer_->OnIceGatheringChange(ice_gathering_state_);
1397 }
1398 }
1399 observer_->OnSignalingChange(signaling_state_);
1400 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1401}
1402
deadbeefab9b2d12015-10-14 11:33:11 -07001403void PeerConnection::PostSetSessionDescriptionFailure(
1404 SetSessionDescriptionObserver* observer,
1405 const std::string& error) {
1406 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1407 msg->error = error;
1408 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1409}
1410
1411void PeerConnection::PostCreateSessionDescriptionFailure(
1412 CreateSessionDescriptionObserver* observer,
1413 const std::string& error) {
1414 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1415 msg->error = error;
1416 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1417}
1418
1419bool PeerConnection::GetOptionsForOffer(
1420 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1421 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001422 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1423 return false;
1424 }
1425
deadbeef8f46c632015-10-26 14:11:17 -07001426 SetStreams(session_options, local_streams_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001427 // Offer to receive audio/video if the constraint is not set and there are
1428 // send streams, or we're currently receiving.
1429 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1430 session_options->recv_audio =
1431 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1432 !remote_audio_tracks_.empty();
1433 }
1434 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1435 session_options->recv_video =
1436 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1437 !remote_video_tracks_.empty();
1438 }
1439 session_options->bundle_enabled =
1440 session_options->bundle_enabled &&
1441 (session_options->has_audio() || session_options->has_video() ||
1442 session_options->has_data());
1443
deadbeefab9b2d12015-10-14 11:33:11 -07001444 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1445 session_options->data_channel_type = cricket::DCT_SCTP;
1446 }
1447 return true;
1448}
1449
1450bool PeerConnection::GetOptionsForAnswer(
1451 const MediaConstraintsInterface* constraints,
1452 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001453 session_options->recv_audio = false;
1454 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001455 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1456 return false;
1457 }
1458
deadbeef8f46c632015-10-26 14:11:17 -07001459 SetStreams(session_options, local_streams_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001460 session_options->bundle_enabled =
1461 session_options->bundle_enabled &&
1462 (session_options->has_audio() || session_options->has_video() ||
1463 session_options->has_data());
1464
deadbeefab9b2d12015-10-14 11:33:11 -07001465 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1466 // are not signaled in the SDP so does not go through that path and must be
1467 // handled here.
1468 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1469 session_options->data_channel_type = cricket::DCT_SCTP;
1470 }
1471 return true;
1472}
1473
1474void PeerConnection::UpdateRemoteStreamsList(
1475 const cricket::StreamParamsVec& streams,
1476 cricket::MediaType media_type,
1477 StreamCollection* new_streams) {
1478 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1479
1480 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeef8f46c632015-10-26 14:11:17 -07001481 // the
1482 // new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001483 auto track_it = current_tracks->begin();
1484 while (track_it != current_tracks->end()) {
1485 const TrackInfo& info = *track_it;
1486 const cricket::StreamParams* params =
1487 cricket::GetStreamBySsrc(streams, info.ssrc);
1488 if (!params || params->id != info.track_id) {
1489 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1490 track_it = current_tracks->erase(track_it);
1491 } else {
1492 ++track_it;
1493 }
1494 }
1495
1496 // Find new and active tracks.
1497 for (const cricket::StreamParams& params : streams) {
1498 // The sync_label is the MediaStream label and the |stream.id| is the
1499 // track id.
1500 const std::string& stream_label = params.sync_label;
1501 const std::string& track_id = params.id;
1502 uint32_t ssrc = params.first_ssrc();
1503
1504 rtc::scoped_refptr<MediaStreamInterface> stream =
1505 remote_streams_->find(stream_label);
1506 if (!stream) {
1507 // This is a new MediaStream. Create a new remote MediaStream.
1508 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1509 remote_streams_->AddStream(stream);
1510 new_streams->AddStream(stream);
1511 }
1512
1513 const TrackInfo* track_info =
1514 FindTrackInfo(*current_tracks, stream_label, track_id);
1515 if (!track_info) {
1516 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1517 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1518 }
1519 }
1520}
1521
1522void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1523 const std::string& track_id,
1524 uint32_t ssrc,
1525 cricket::MediaType media_type) {
1526 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1527
1528 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1529 AudioTrackInterface* audio_track =
1530 remote_stream_factory_->AddAudioTrack(stream, track_id);
1531 CreateAudioReceiver(stream, audio_track, ssrc);
1532 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1533 VideoTrackInterface* video_track =
1534 remote_stream_factory_->AddVideoTrack(stream, track_id);
1535 CreateVideoReceiver(stream, video_track, ssrc);
1536 } else {
1537 RTC_DCHECK(false && "Invalid media type");
1538 }
1539}
1540
1541void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1542 const std::string& track_id,
1543 cricket::MediaType media_type) {
1544 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1545
1546 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1547 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1548 stream->FindAudioTrack(track_id);
1549 if (audio_track) {
1550 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1551 stream->RemoveTrack(audio_track);
1552 DestroyAudioReceiver(stream, audio_track);
1553 }
1554 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1555 rtc::scoped_refptr<VideoTrackInterface> video_track =
1556 stream->FindVideoTrack(track_id);
1557 if (video_track) {
1558 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1559 stream->RemoveTrack(video_track);
1560 DestroyVideoReceiver(stream, video_track);
1561 }
1562 } else {
1563 ASSERT(false && "Invalid media type");
1564 }
1565}
1566
1567void PeerConnection::UpdateEndedRemoteMediaStreams() {
1568 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1569 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1570 MediaStreamInterface* stream = remote_streams_->at(i);
1571 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1572 streams_to_remove.push_back(stream);
1573 }
1574 }
1575
1576 for (const auto& stream : streams_to_remove) {
1577 remote_streams_->RemoveStream(stream);
1578 observer_->OnRemoveStream(stream);
1579 }
1580}
1581
1582void PeerConnection::MaybeCreateDefaultStream() {
1583 if (!remote_info_.IsDefaultMediaStreamNeeded()) {
1584 return;
1585 }
1586
1587 bool default_created = false;
1588
1589 rtc::scoped_refptr<MediaStreamInterface> default_remote_stream =
1590 remote_streams_->find(kDefaultStreamLabel);
1591 if (default_remote_stream == nullptr) {
1592 default_created = true;
1593 default_remote_stream =
1594 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1595 remote_streams_->AddStream(default_remote_stream);
1596 }
1597 if (remote_info_.default_audio_track_needed &&
1598 default_remote_stream->GetAudioTracks().size() == 0) {
1599 remote_audio_tracks_.push_back(
1600 TrackInfo(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0));
1601 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
1602 cricket::MEDIA_TYPE_AUDIO);
1603 }
1604 if (remote_info_.default_video_track_needed &&
1605 default_remote_stream->GetVideoTracks().size() == 0) {
1606 remote_video_tracks_.push_back(
1607 TrackInfo(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0));
1608 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
1609 cricket::MEDIA_TYPE_VIDEO);
1610 }
1611 if (default_created) {
1612 stats_->AddStream(default_remote_stream);
1613 observer_->OnAddStream(default_remote_stream);
1614 }
1615}
1616
1617void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1618 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1619 for (TrackInfos::iterator track_it = current_tracks->begin();
1620 track_it != current_tracks->end(); ++track_it) {
1621 const TrackInfo& info = *track_it;
1622 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1623 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1624 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1625 // There's no guarantee the track is still available, e.g. the track may
1626 // have been removed from the stream by javascript.
1627 if (track) {
1628 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1629 }
1630 }
1631 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1632 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1633 // There's no guarantee the track is still available, e.g. the track may
1634 // have been removed from the stream by javascript.
1635 if (track) {
1636 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1637 }
1638 }
1639 }
1640}
1641
1642void PeerConnection::UpdateLocalTracks(
1643 const std::vector<cricket::StreamParams>& streams,
1644 cricket::MediaType media_type) {
1645 TrackInfos* current_tracks = GetLocalTracks(media_type);
1646
1647 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1648 // don't match the new StreamParam.
1649 TrackInfos::iterator track_it = current_tracks->begin();
1650 while (track_it != current_tracks->end()) {
1651 const TrackInfo& info = *track_it;
1652 const cricket::StreamParams* params =
1653 cricket::GetStreamBySsrc(streams, info.ssrc);
1654 if (!params || params->id != info.track_id ||
1655 params->sync_label != info.stream_label) {
1656 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1657 media_type);
1658 track_it = current_tracks->erase(track_it);
1659 } else {
1660 ++track_it;
1661 }
1662 }
1663
1664 // Find new and active tracks.
1665 for (const cricket::StreamParams& params : streams) {
1666 // The sync_label is the MediaStream label and the |stream.id| is the
1667 // track id.
1668 const std::string& stream_label = params.sync_label;
1669 const std::string& track_id = params.id;
1670 uint32_t ssrc = params.first_ssrc();
1671 const TrackInfo* track_info =
1672 FindTrackInfo(*current_tracks, stream_label, track_id);
1673 if (!track_info) {
1674 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1675 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1676 }
1677 }
1678}
1679
1680void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1681 const std::string& track_id,
1682 uint32_t ssrc,
1683 cricket::MediaType media_type) {
deadbeef8f46c632015-10-26 14:11:17 -07001684 MediaStreamInterface* stream = local_streams_->find(stream_label);
1685 if (!stream) {
1686 LOG(LS_WARNING) << "An unknown local MediaStream with label "
1687 << stream_label << " has been configured.";
deadbeefab9b2d12015-10-14 11:33:11 -07001688 return;
1689 }
1690
deadbeef8f46c632015-10-26 14:11:17 -07001691 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1692 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1693 if (!audio_track) {
1694 LOG(LS_WARNING) << "An unknown local AudioTrack with id , " << track_id
1695 << " has been configured.";
1696 return;
1697 }
1698 CreateAudioSender(stream, audio_track, ssrc);
1699 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1700 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1701 if (!video_track) {
1702 LOG(LS_WARNING) << "An unknown local VideoTrack with id , " << track_id
1703 << " has been configured.";
1704 return;
1705 }
1706 CreateVideoSender(stream, video_track, ssrc);
1707 } else {
1708 RTC_DCHECK(false && "Invalid media type");
deadbeefab9b2d12015-10-14 11:33:11 -07001709 }
1710}
1711
1712void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1713 const std::string& track_id,
1714 uint32_t ssrc,
1715 cricket::MediaType media_type) {
deadbeef8f46c632015-10-26 14:11:17 -07001716 MediaStreamInterface* stream = local_streams_->find(stream_label);
1717 if (!stream) {
1718 // This is the normal case. I.e., RemoveLocalStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001719 // SessionDescriptions has been renegotiated.
1720 return;
1721 }
deadbeef8f46c632015-10-26 14:11:17 -07001722 // A track has been removed from the SessionDescription but the MediaStream
1723 // is still associated with PeerConnection. This only occurs if the SDP
1724 // doesn't match with the calls to AddLocalStream and RemoveLocalStream.
1725 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1726 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1727 if (!audio_track) {
1728 return;
1729 }
1730 DestroyAudioSender(stream, audio_track, ssrc);
1731 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1732 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1733 if (!video_track) {
1734 return;
1735 }
1736 DestroyVideoSender(stream, video_track);
1737 } else {
1738 RTC_DCHECK(false && "Invalid media type.");
deadbeefab9b2d12015-10-14 11:33:11 -07001739 }
1740}
1741
1742void PeerConnection::UpdateLocalRtpDataChannels(
1743 const cricket::StreamParamsVec& streams) {
1744 std::vector<std::string> existing_channels;
1745
1746 // Find new and active data channels.
1747 for (const cricket::StreamParams& params : streams) {
1748 // |it->sync_label| is actually the data channel label. The reason is that
1749 // we use the same naming of data channels as we do for
1750 // MediaStreams and Tracks.
1751 // For MediaStreams, the sync_label is the MediaStream label and the
1752 // track label is the same as |streamid|.
1753 const std::string& channel_label = params.sync_label;
1754 auto data_channel_it = rtp_data_channels_.find(channel_label);
1755 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1756 continue;
1757 }
1758 // Set the SSRC the data channel should use for sending.
1759 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1760 existing_channels.push_back(data_channel_it->first);
1761 }
1762
1763 UpdateClosingRtpDataChannels(existing_channels, true);
1764}
1765
1766void PeerConnection::UpdateRemoteRtpDataChannels(
1767 const cricket::StreamParamsVec& streams) {
1768 std::vector<std::string> existing_channels;
1769
1770 // Find new and active data channels.
1771 for (const cricket::StreamParams& params : streams) {
1772 // The data channel label is either the mslabel or the SSRC if the mslabel
1773 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1774 std::string label = params.sync_label.empty()
1775 ? rtc::ToString(params.first_ssrc())
1776 : params.sync_label;
1777 auto data_channel_it = rtp_data_channels_.find(label);
1778 if (data_channel_it == rtp_data_channels_.end()) {
1779 // This is a new data channel.
1780 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1781 } else {
1782 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1783 }
1784 existing_channels.push_back(label);
1785 }
1786
1787 UpdateClosingRtpDataChannels(existing_channels, false);
1788}
1789
1790void PeerConnection::UpdateClosingRtpDataChannels(
1791 const std::vector<std::string>& active_channels,
1792 bool is_local_update) {
1793 auto it = rtp_data_channels_.begin();
1794 while (it != rtp_data_channels_.end()) {
1795 DataChannel* data_channel = it->second;
1796 if (std::find(active_channels.begin(), active_channels.end(),
1797 data_channel->label()) != active_channels.end()) {
1798 ++it;
1799 continue;
1800 }
1801
1802 if (is_local_update) {
1803 data_channel->SetSendSsrc(0);
1804 } else {
1805 data_channel->RemotePeerRequestClose();
1806 }
1807
1808 if (data_channel->state() == DataChannel::kClosed) {
1809 rtp_data_channels_.erase(it);
1810 it = rtp_data_channels_.begin();
1811 } else {
1812 ++it;
1813 }
1814 }
1815}
1816
1817void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1818 uint32_t remote_ssrc) {
1819 rtc::scoped_refptr<DataChannel> channel(
1820 InternalCreateDataChannel(label, nullptr));
1821 if (!channel.get()) {
1822 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1823 << "CreateDataChannel failed.";
1824 return;
1825 }
1826 channel->SetReceiveSsrc(remote_ssrc);
1827 observer_->OnDataChannel(
1828 DataChannelProxy::Create(signaling_thread(), channel));
1829}
1830
1831rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1832 const std::string& label,
1833 const InternalDataChannelInit* config) {
1834 if (IsClosed()) {
1835 return nullptr;
1836 }
1837 if (session_->data_channel_type() == cricket::DCT_NONE) {
1838 LOG(LS_ERROR)
1839 << "InternalCreateDataChannel: Data is not supported in this call.";
1840 return nullptr;
1841 }
1842 InternalDataChannelInit new_config =
1843 config ? (*config) : InternalDataChannelInit();
1844 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1845 if (new_config.id < 0) {
1846 rtc::SSLRole role;
1847 if (session_->GetSslRole(&role) &&
1848 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1849 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1850 return nullptr;
1851 }
1852 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1853 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1854 << "because the id is already in use or out of range.";
1855 return nullptr;
1856 }
1857 }
1858
1859 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1860 session_.get(), session_->data_channel_type(), label, new_config));
1861 if (!channel) {
1862 sid_allocator_.ReleaseSid(new_config.id);
1863 return nullptr;
1864 }
1865
1866 if (channel->data_channel_type() == cricket::DCT_RTP) {
1867 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1868 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1869 << " already exists.";
1870 return nullptr;
1871 }
1872 rtp_data_channels_[channel->label()] = channel;
1873 } else {
1874 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1875 sctp_data_channels_.push_back(channel);
1876 channel->SignalClosed.connect(this,
1877 &PeerConnection::OnSctpDataChannelClosed);
1878 }
1879
1880 return channel;
1881}
1882
1883bool PeerConnection::HasDataChannels() const {
1884 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1885}
1886
1887void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1888 for (const auto& channel : sctp_data_channels_) {
1889 if (channel->id() < 0) {
1890 int sid;
1891 if (!sid_allocator_.AllocateSid(role, &sid)) {
1892 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1893 continue;
1894 }
1895 channel->SetSctpSid(sid);
1896 }
1897 }
1898}
1899
1900void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1901 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1902 ++it) {
1903 if (it->get() == channel) {
1904 if (channel->id() >= 0) {
1905 sid_allocator_.ReleaseSid(channel->id());
1906 }
1907 sctp_data_channels_.erase(it);
1908 return;
1909 }
1910 }
1911}
1912
1913void PeerConnection::OnVoiceChannelDestroyed() {
1914 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1915}
1916
1917void PeerConnection::OnVideoChannelDestroyed() {
1918 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1919}
1920
1921void PeerConnection::OnDataChannelCreated() {
1922 for (const auto& channel : sctp_data_channels_) {
1923 channel->OnTransportChannelCreated();
1924 }
1925}
1926
1927void PeerConnection::OnDataChannelDestroyed() {
1928 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1929 // DataChannel may callback to us and try to modify the list.
1930 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1931 temp_rtp_dcs.swap(rtp_data_channels_);
1932 for (const auto& kv : temp_rtp_dcs) {
1933 kv.second->OnTransportChannelDestroyed();
1934 }
1935
1936 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1937 temp_sctp_dcs.swap(sctp_data_channels_);
1938 for (const auto& channel : temp_sctp_dcs) {
1939 channel->OnTransportChannelDestroyed();
1940 }
1941}
1942
1943void PeerConnection::OnDataChannelOpenMessage(
1944 const std::string& label,
1945 const InternalDataChannelInit& config) {
1946 rtc::scoped_refptr<DataChannel> channel(
1947 InternalCreateDataChannel(label, &config));
1948 if (!channel.get()) {
1949 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1950 return;
1951 }
1952
1953 observer_->OnDataChannel(
1954 DataChannelProxy::Create(signaling_thread(), channel));
1955}
1956
deadbeef70ab1a12015-09-28 16:53:55 -07001957std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1958PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1959 return std::find_if(
1960 senders_.begin(), senders_.end(),
1961 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1962 return sender->track() == track;
1963 });
1964}
1965
1966std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1967PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1968 return std::find_if(
1969 receivers_.begin(), receivers_.end(),
1970 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1971 return receiver->track() == track;
1972 });
1973}
1974
deadbeefab9b2d12015-10-14 11:33:11 -07001975PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1976 cricket::MediaType media_type) {
1977 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1978 media_type == cricket::MEDIA_TYPE_VIDEO);
1979 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1980 : &remote_video_tracks_;
1981}
1982
1983PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
1984 cricket::MediaType media_type) {
1985 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1986 media_type == cricket::MEDIA_TYPE_VIDEO);
1987 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
1988 : &local_video_tracks_;
1989}
1990
1991const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
1992 const PeerConnection::TrackInfos& infos,
1993 const std::string& stream_label,
1994 const std::string track_id) const {
1995 for (const TrackInfo& track_info : infos) {
1996 if (track_info.stream_label == stream_label &&
1997 track_info.track_id == track_id) {
1998 return &track_info;
1999 }
2000 }
2001 return nullptr;
2002}
2003
2004DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2005 for (const auto& channel : sctp_data_channels_) {
2006 if (channel->id() == sid) {
2007 return channel;
2008 }
2009 }
2010 return nullptr;
2011}
2012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013} // namespace webrtc