blob: caa892d00b9b04802c15908b04f97bd4ddf3cfb1 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00003 * Copyright 2012 Google Inc.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/peerconnection.h"
29
30#include <vector>
deadbeef0a6c4ca2015-10-06 11:38:28 -070031#include <cctype> // for isdigit
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032
deadbeefab9b2d12015-10-14 11:33:11 -070033#include "talk/app/webrtc/audiotrack.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034#include "talk/app/webrtc/dtmfsender.h"
35#include "talk/app/webrtc/jsepicecandidate.h"
36#include "talk/app/webrtc/jsepsessiondescription.h"
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +000037#include "talk/app/webrtc/mediaconstraintsinterface.h"
deadbeefab9b2d12015-10-14 11:33:11 -070038#include "talk/app/webrtc/mediastream.h"
39#include "talk/app/webrtc/mediastreamproxy.h"
40#include "talk/app/webrtc/mediastreamtrackproxy.h"
41#include "talk/app/webrtc/remoteaudiosource.h"
42#include "talk/app/webrtc/remotevideocapturer.h"
deadbeef70ab1a12015-09-28 16:53:55 -070043#include "talk/app/webrtc/rtpreceiver.h"
44#include "talk/app/webrtc/rtpsender.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045#include "talk/app/webrtc/streamcollection.h"
deadbeefab9b2d12015-10-14 11:33:11 -070046#include "talk/app/webrtc/videosource.h"
47#include "talk/app/webrtc/videotrack.h"
48#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049#include "talk/session/media/channelmanager.h"
tfarina5237aaf2015-11-10 23:44:30 -080050#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000051#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070053#include "webrtc/base/stringutils.h"
tfarina5237aaf2015-11-10 23:44:30 -080054#include "webrtc/p2p/client/basicportallocator.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010055#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57namespace {
58
deadbeefab9b2d12015-10-14 11:33:11 -070059using webrtc::DataChannel;
60using webrtc::MediaConstraintsInterface;
61using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062using webrtc::PeerConnectionInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070063using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070064using webrtc::StunConfigurations;
65using webrtc::TurnConfigurations;
66typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
67 StunConfiguration;
68typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
69 TurnConfiguration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070
deadbeefab9b2d12015-10-14 11:33:11 -070071static const char kDefaultStreamLabel[] = "default";
72static const char kDefaultAudioTrackLabel[] = "defaulta0";
73static const char kDefaultVideoTrackLabel[] = "defaultv0";
74
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075// The min number of tokens must present in Turn host uri.
76// e.g. user@turn.example.org
77static const size_t kTurnHostTokensNum = 2;
78// Number of tokens must be preset when TURN uri has transport param.
79static const size_t kTurnTransportTokensNum = 2;
80// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000081static const int kDefaultStunPort = 3478;
82static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000084static const char kUdpTransportType[] = "udp";
85static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086
87// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070088static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089
deadbeef0a6c4ca2015-10-06 11:38:28 -070090// NOTE: A loop below assumes that the first value of this enum is 0 and all
91// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070093 STUN = 0, // Indicates a STUN server.
94 STUNS, // Indicates a STUN server used with a TLS session.
95 TURN, // Indicates a TURN server
96 TURNS, // Indicates a TURN server used with a TLS session.
97 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098};
tfarina5237aaf2015-11-10 23:44:30 -080099static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -0700100 "kValidIceServiceTypes must have as many strings as ServiceType "
101 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102
103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117 std::string error;
118};
119
deadbeefab9b2d12015-10-14 11:33:11 -0700120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
126 std::string error;
127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136};
137
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000138// |in_str| should be of format
139// stunURI = scheme ":" stun-host [ ":" stun-port ]
140// scheme = "stun" / "stuns"
141// stun-host = IP-literal / IPv4address / reg-name
142// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700143//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000144// draft-petithuguenin-behave-turn-uris-01
145// turnURI = scheme ":" turn-host [ ":" turn-port ]
146// turn-host = username@IP-literal / IPv4address / reg-name
147bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
148 ServiceType* service_type,
149 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200150 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700151 if (colonpos == std::string::npos) {
152 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000153 return false;
154 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700155 if ((colonpos + 1) == in_str.length()) {
156 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
157 return false;
158 }
159 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800160 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700161 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000162 *service_type = static_cast<ServiceType>(i);
163 break;
164 }
165 }
166 if (*service_type == INVALID) {
167 return false;
168 }
169 *hostname = in_str.substr(colonpos + 1, std::string::npos);
170 return true;
171}
172
deadbeef0a6c4ca2015-10-06 11:38:28 -0700173bool ParsePort(const std::string& in_str, int* port) {
174 // Make sure port only contains digits. FromString doesn't check this.
175 for (const char& c : in_str) {
176 if (!std::isdigit(c)) {
177 return false;
178 }
179 }
180 return rtc::FromString(in_str, port);
181}
182
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000183// This method parses IPv6 and IPv4 literal strings, along with hostnames in
184// standard hostname:port format.
185// Consider following formats as correct.
186// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700187// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000188bool ParseHostnameAndPortFromString(const std::string& in_str,
189 std::string* host,
190 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700191 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000192 if (in_str.at(0) == '[') {
193 std::string::size_type closebracket = in_str.rfind(']');
194 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000195 std::string::size_type colonpos = in_str.find(':', closebracket);
196 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700197 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
198 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000199 return false;
200 }
201 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700202 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000203 } else {
204 return false;
205 }
206 } else {
207 std::string::size_type colonpos = in_str.find(':');
208 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700209 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000210 return false;
211 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700212 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000213 } else {
214 *host = in_str;
215 }
216 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700217 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000218}
219
deadbeef0a6c4ca2015-10-06 11:38:28 -0700220// Adds a StunConfiguration or TurnConfiguration to the appropriate list,
221// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200222bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
223 const std::string& url,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700224 StunConfigurations* stun_config,
225 TurnConfigurations* turn_config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000226 // draft-nandakumar-rtcweb-stun-uri-01
227 // stunURI = scheme ":" stun-host [ ":" stun-port ]
228 // scheme = "stun" / "stuns"
229 // stun-host = IP-literal / IPv4address / reg-name
230 // stun-port = *DIGIT
231
232 // draft-petithuguenin-behave-turn-uris-01
233 // turnURI = scheme ":" turn-host [ ":" turn-port ]
234 // [ "?transport=" transport ]
235 // scheme = "turn" / "turns"
236 // transport = "udp" / "tcp" / transport-ext
237 // transport-ext = 1*unreserved
238 // turn-host = IP-literal / IPv4address / reg-name
239 // turn-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700240 RTC_DCHECK(stun_config != nullptr);
241 RTC_DCHECK(turn_config != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200242 std::vector<std::string> tokens;
243 std::string turn_transport_type = kUdpTransportType;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700244 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200245 rtc::tokenize(url, '?', &tokens);
246 std::string uri_without_transport = tokens[0];
247 // Let's look into transport= param, if it exists.
248 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
249 std::string uri_transport_param = tokens[1];
250 rtc::tokenize(uri_transport_param, '=', &tokens);
251 if (tokens[0] == kTransport) {
252 // As per above grammar transport param will be consist of lower case
253 // letters.
254 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
255 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700256 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200258 turn_transport_type = tokens[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200262 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200264 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
265 &service_type,
266 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700267 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
268 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200269 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000270
deadbeef0a6c4ca2015-10-06 11:38:28 -0700271 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
272 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200273
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200274 // Let's break hostname.
275 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700276 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
277
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200278 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700279 if (tokens.size() > kTurnHostTokensNum) {
280 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
281 return false;
282 }
283 if (tokens.size() == kTurnHostTokensNum) {
284 if (tokens[0].empty() || tokens[1].empty()) {
285 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
286 return false;
287 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200288 username.assign(rtc::s_url_decode(tokens[0]));
289 hoststring = tokens[1];
290 } else {
291 hoststring = tokens[0];
292 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000293
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200294 int port = kDefaultStunPort;
295 if (service_type == TURNS) {
296 port = kDefaultStunTlsPort;
297 turn_transport_type = kTcpTransportType;
298 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000299
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200300 std::string address;
301 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700302 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
303 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200304 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000305
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200306 if (port <= 0 || port > 0xffff) {
307 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700308 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200309 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000310
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200311 switch (service_type) {
312 case STUN:
313 case STUNS:
314 stun_config->push_back(StunConfiguration(address, port));
315 break;
316 case TURN:
317 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200318 bool secure = (service_type == TURNS);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200319 turn_config->push_back(TurnConfiguration(address, port,
320 username,
321 server.password,
322 turn_transport_type,
323 secure));
324 break;
325 }
326 case INVALID:
327 default:
328 LOG(WARNING) << "Configuration not supported: " << url;
329 return false;
330 }
331 return true;
332}
333
deadbeef653b8e02015-11-11 12:55:10 -0800334void ConvertToCricketIceServers(
335 const std::vector<StunConfiguration>& stuns,
336 const std::vector<TurnConfiguration>& turns,
337 cricket::ServerAddresses* cricket_stuns,
338 std::vector<cricket::RelayServerConfig>* cricket_turns) {
339 RTC_DCHECK(cricket_stuns && cricket_turns);
340 for (const StunConfiguration& stun : stuns) {
341 cricket_stuns->insert(stun.server);
342 }
343
344 int priority = static_cast<int>(turns.size() - 1);
345 for (const TurnConfiguration& turn : turns) {
346 cricket::RelayCredentials credentials(turn.username, turn.password);
347 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
348 cricket::ProtocolType protocol;
349 // Using VERIFY because ParseIceServers should have already caught an
350 // invalid transport type.
351 if (!VERIFY(
352 cricket::StringToProto(turn.transport_type.c_str(), &protocol))) {
353 LOG(LS_WARNING) << "Ignoring TURN server " << turn.server << ". "
354 << "Reason= Incorrect " << turn.transport_type
355 << " transport parameter.";
356 } else {
357 relay_server.ports.push_back(
358 cricket::ProtocolAddress(turn.server, protocol, turn.secure));
359 relay_server.credentials = credentials;
360 relay_server.priority = priority;
361 cricket_turns->push_back(relay_server);
362 }
363 // First in the list gets highest priority.
364 --priority;
365 }
366}
367
deadbeefab9b2d12015-10-14 11:33:11 -0700368// Check if we can send |new_stream| on a PeerConnection.
369bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
370 webrtc::MediaStreamInterface* new_stream) {
371 if (!new_stream || !current_streams) {
372 return false;
373 }
374 if (current_streams->find(new_stream->label()) != nullptr) {
375 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
376 << " is already added.";
377 return false;
378 }
379 return true;
380}
381
382bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
383 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
384}
385
deadbeef5e97fb52015-10-15 12:49:08 -0700386// If the direction is "recvonly" or "inactive", treat the description
387// as containing no streams.
388// See: https://code.google.com/p/webrtc/issues/detail?id=5054
389std::vector<cricket::StreamParams> GetActiveStreams(
390 const cricket::MediaContentDescription* desc) {
391 return MediaContentDirectionHasSend(desc->direction())
392 ? desc->streams()
393 : std::vector<cricket::StreamParams>();
394}
395
deadbeefab9b2d12015-10-14 11:33:11 -0700396bool IsValidOfferToReceiveMedia(int value) {
397 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
398 return (value >= Options::kUndefined) &&
399 (value <= Options::kMaxOfferToReceiveMedia);
400}
401
402// Add the stream and RTP data channel info to |session_options|.
deadbeef8f46c632015-10-26 14:11:17 -0700403void SetStreams(cricket::MediaSessionOptions* session_options,
404 rtc::scoped_refptr<StreamCollection> streams,
405 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
406 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700407 session_options->streams.clear();
deadbeef8f46c632015-10-26 14:11:17 -0700408 if (streams != nullptr) {
409 for (size_t i = 0; i < streams->count(); ++i) {
410 MediaStreamInterface* stream = streams->at(i);
411 // For each audio track in the stream, add it to the MediaSessionOptions.
412 for (const auto& track : stream->GetAudioTracks()) {
413 session_options->AddSendStream(cricket::MEDIA_TYPE_AUDIO, track->id(),
414 stream->label());
415 }
416 // For each video track in the stream, add it to the MediaSessionOptions.
417 for (const auto& track : stream->GetVideoTracks()) {
418 session_options->AddSendStream(cricket::MEDIA_TYPE_VIDEO, track->id(),
419 stream->label());
420 }
421 }
deadbeefab9b2d12015-10-14 11:33:11 -0700422 }
423
424 // Check for data channels.
425 for (const auto& kv : rtp_data_channels) {
426 const DataChannel* channel = kv.second;
427 if (channel->state() == DataChannel::kConnecting ||
428 channel->state() == DataChannel::kOpen) {
429 // |streamid| and |sync_label| are both set to the DataChannel label
430 // here so they can be signaled the same way as MediaStreams and Tracks.
431 // For MediaStreams, the sync_label is the MediaStream label and the
432 // track label is the same as |streamid|.
433 const std::string& streamid = channel->label();
434 const std::string& sync_label = channel->label();
435 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
436 sync_label);
437 }
438 }
439}
440
deadbeef0a6c4ca2015-10-06 11:38:28 -0700441} // namespace
442
443namespace webrtc {
444
deadbeefab9b2d12015-10-14 11:33:11 -0700445// Factory class for creating remote MediaStreams and MediaStreamTracks.
446class RemoteMediaStreamFactory {
447 public:
448 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
449 cricket::ChannelManager* channel_manager)
450 : signaling_thread_(signaling_thread),
451 channel_manager_(channel_manager) {}
452
453 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
454 const std::string& stream_label) {
455 return MediaStreamProxy::Create(signaling_thread_,
456 MediaStream::Create(stream_label));
457 }
458
459 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
460 const std::string& track_id) {
461 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
462 stream, track_id, RemoteAudioSource::Create().get());
463 }
464
465 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
466 const std::string& track_id) {
467 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
468 stream, track_id,
469 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
470 nullptr)
471 .get());
472 }
473
474 private:
475 template <typename TI, typename T, typename TP, typename S>
476 TI* AddTrack(MediaStreamInterface* stream,
477 const std::string& track_id,
478 S* source) {
479 rtc::scoped_refptr<TI> track(
480 TP::Create(signaling_thread_, T::Create(track_id, source)));
481 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
482 if (stream->AddTrack(track)) {
483 return track;
484 }
485 return nullptr;
486 }
487
488 rtc::Thread* signaling_thread_;
489 cricket::ChannelManager* channel_manager_;
490};
491
492bool ConvertRtcOptionsForOffer(
493 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
494 cricket::MediaSessionOptions* session_options) {
495 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
496 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
497 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
498 return false;
499 }
500
deadbeefc80741f2015-10-22 13:14:45 -0700501 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700502 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
503 }
deadbeefc80741f2015-10-22 13:14:45 -0700504 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700505 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
506 }
507
508 session_options->vad_enabled = rtc_options.voice_activity_detection;
509 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700510 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700511
512 return true;
513}
514
515bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
516 cricket::MediaSessionOptions* session_options) {
517 bool value = false;
518 size_t mandatory_constraints_satisfied = 0;
519
520 // kOfferToReceiveAudio defaults to true according to spec.
521 if (!FindConstraint(constraints,
522 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
523 &mandatory_constraints_satisfied) ||
524 value) {
525 session_options->recv_audio = true;
526 }
527
528 // kOfferToReceiveVideo defaults to false according to spec. But
529 // if it is an answer and video is offered, we should still accept video
530 // per default.
531 value = false;
532 if (!FindConstraint(constraints,
533 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
534 &mandatory_constraints_satisfied) ||
535 value) {
536 session_options->recv_video = true;
537 }
538
539 if (FindConstraint(constraints,
540 MediaConstraintsInterface::kVoiceActivityDetection, &value,
541 &mandatory_constraints_satisfied)) {
542 session_options->vad_enabled = value;
543 }
544
545 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
546 &mandatory_constraints_satisfied)) {
547 session_options->bundle_enabled = value;
548 } else {
549 // kUseRtpMux defaults to true according to spec.
550 session_options->bundle_enabled = true;
551 }
deadbeefab9b2d12015-10-14 11:33:11 -0700552
553 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
554 &value, &mandatory_constraints_satisfied)) {
555 session_options->transport_options.ice_restart = value;
556 } else {
557 // kIceRestart defaults to false according to spec.
558 session_options->transport_options.ice_restart = false;
559 }
560
561 if (!constraints) {
562 return true;
563 }
564 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
565}
566
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200567bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700568 StunConfigurations* stun_config,
569 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200570 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
571 if (!server.urls.empty()) {
572 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200573 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700574 LOG(LS_ERROR) << "Empty uri.";
575 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200576 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200577 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
578 return false;
579 }
580 }
581 } else if (!server.uri.empty()) {
582 // Fallback to old .uri if new .urls isn't present.
583 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000584 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200585 }
586 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700587 LOG(LS_ERROR) << "Empty uri.";
588 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 }
590 }
591 return true;
592}
593
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000594PeerConnection::PeerConnection(PeerConnectionFactory* factory)
595 : factory_(factory),
596 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000597 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598 signaling_state_(kStable),
599 ice_state_(kIceNew),
600 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700601 ice_gathering_state_(kIceGatheringNew),
602 local_streams_(StreamCollection::Create()),
603 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000604
605PeerConnection::~PeerConnection() {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700606 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700607 // Need to detach RTP senders/receivers from WebRtcSession,
608 // since it's about to be destroyed.
609 for (const auto& sender : senders_) {
610 sender->Stop();
611 }
612 for (const auto& receiver : receivers_) {
613 receiver->Stop();
614 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000615}
616
617bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000618 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000620 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200621 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000622 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700623 RTC_DCHECK(observer != nullptr);
624 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000625 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700626 }
deadbeef653b8e02015-11-11 12:55:10 -0800627
628 // This Initialize function parses ICE servers an extra time, but it will
629 // be removed once all PortAllocaotrs support SetIceServers.
630 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
631 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
632 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
633 return false;
634 }
635 rtc::scoped_ptr<cricket::PortAllocator> allocator(
636 allocator_factory->CreatePortAllocator(stun_config, turn_config));
637 return Initialize(configuration, constraints, allocator.Pass(),
638 dtls_identity_store.Pass(), observer);
639}
640
641bool PeerConnection::Initialize(
642 const PeerConnectionInterface::RTCConfiguration& configuration,
643 const MediaConstraintsInterface* constraints,
644 rtc::scoped_ptr<cricket::PortAllocator> allocator,
645 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
646 PeerConnectionObserver* observer) {
647 RTC_DCHECK(observer != nullptr);
648 if (!observer) {
649 return false;
650 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000651 observer_ = observer;
652
deadbeef653b8e02015-11-11 12:55:10 -0800653 port_allocator_ = allocator.Pass();
654
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000655 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
656 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000657 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 return false;
659 }
deadbeef653b8e02015-11-11 12:55:10 -0800660
661 cricket::ServerAddresses cricket_stuns;
662 std::vector<cricket::RelayServerConfig> cricket_turns;
663 ConvertToCricketIceServers(stun_config, turn_config, &cricket_stuns,
664 &cricket_turns);
665 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000666
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000668 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000669 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700670 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000671 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000672 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000673 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700674 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
675 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000676 if (!value) {
677 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000678 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000679 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000680 "Disabled") {
681 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000682 }
683
Jiayang Liucac1b382015-04-30 12:35:24 -0700684 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
685 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
686 LOG(LS_INFO) << "TCP candidates are disabled.";
687 }
688
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000689 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690 // No step delay is used while allocating ports.
691 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
692
stefanc1aeaf02015-10-15 07:26:07 -0700693 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000694
stefanc1aeaf02015-10-15 07:26:07 -0700695 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
696 factory_->signaling_thread(), media_controller_->channel_manager()));
697
698 session_.reset(
699 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
700 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700701 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702
703 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000704 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700705 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000706 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700707 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000709 // Register PeerConnection as receiver of local ice candidates.
710 // All the callbacks will be posted to the application from PeerConnection.
711 session_->RegisterIceObserver(this);
712 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700713 session_->SignalVoiceChannelDestroyed.connect(
714 this, &PeerConnection::OnVoiceChannelDestroyed);
715 session_->SignalVideoChannelDestroyed.connect(
716 this, &PeerConnection::OnVideoChannelDestroyed);
717 session_->SignalDataChannelCreated.connect(
718 this, &PeerConnection::OnDataChannelCreated);
719 session_->SignalDataChannelDestroyed.connect(
720 this, &PeerConnection::OnDataChannelDestroyed);
721 session_->SignalDataChannelOpenMessage.connect(
722 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 return true;
724}
725
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000726rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700728 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729}
730
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000731rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700733 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734}
735
deadbeef8f46c632015-10-26 14:11:17 -0700736// TODO(deadbeef): Create RtpSenders immediately here, even if local
737// description hasn't yet been set.
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000738bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000739 if (IsClosed()) {
740 return false;
741 }
deadbeefab9b2d12015-10-14 11:33:11 -0700742 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 return false;
744 }
deadbeefab9b2d12015-10-14 11:33:11 -0700745
746 local_streams_->AddStream(local_stream);
747
deadbeef8f46c632015-10-26 14:11:17 -0700748 // Find tracks that have already been configured in SDP. This can occur if a
749 // local session description that contains the MSID of these tracks is set
750 // before AddLocalStream is called. It can also occur if the local session
751 // description is not changed and RemoveLocalStream is called and later
752 // AddLocalStream is called again with the same stream.
deadbeefab9b2d12015-10-14 11:33:11 -0700753 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700754 const TrackInfo* track_info =
755 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
756 if (track_info) {
757 CreateAudioSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700758 }
759 }
760 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700761 const TrackInfo* track_info =
762 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
763 if (track_info) {
764 CreateVideoSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700765 }
766 }
767
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000768 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769 observer_->OnRenegotiationNeeded();
770 return true;
771}
772
deadbeefab9b2d12015-10-14 11:33:11 -0700773// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
deadbeef8f46c632015-10-26 14:11:17 -0700774// indefinitely.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000775void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
deadbeefab9b2d12015-10-14 11:33:11 -0700776 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700777 const TrackInfo* track_info =
778 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
779 if (track_info) {
780 DestroyAudioSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700781 }
782 }
783 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700784 const TrackInfo* track_info =
785 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
786 if (track_info) {
787 DestroyVideoSender(local_stream, track.get());
deadbeefab9b2d12015-10-14 11:33:11 -0700788 }
789 }
790
791 local_streams_->RemoveStream(local_stream);
792
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793 if (IsClosed()) {
794 return;
795 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796 observer_->OnRenegotiationNeeded();
797}
798
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000799rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800 AudioTrackInterface* track) {
801 if (!track) {
802 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
803 return NULL;
804 }
deadbeefab9b2d12015-10-14 11:33:11 -0700805 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
807 return NULL;
808 }
809
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000810 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 DtmfSender::Create(track, signaling_thread(), session_.get()));
812 if (!sender.get()) {
813 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
814 return NULL;
815 }
816 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
817}
818
deadbeef70ab1a12015-09-28 16:53:55 -0700819std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
820 const {
821 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
822 for (const auto& sender : senders_) {
823 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
824 }
825 return senders;
826}
827
828std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
829PeerConnection::GetReceivers() const {
830 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
831 for (const auto& receiver : receivers_) {
832 receivers.push_back(
833 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
834 }
835 return receivers;
836}
837
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000839 MediaStreamTrackInterface* track,
840 StatsOutputLevel level) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700841 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 if (!VERIFY(observer != NULL)) {
843 LOG(LS_ERROR) << "GetStats - observer is NULL.";
844 return false;
845 }
846
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000847 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000848 signaling_thread()->Post(this, MSG_GETSTATS,
849 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 return true;
851}
852
853PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
854 return signaling_state_;
855}
856
857PeerConnectionInterface::IceState PeerConnection::ice_state() {
858 return ice_state_;
859}
860
861PeerConnectionInterface::IceConnectionState
862PeerConnection::ice_connection_state() {
863 return ice_connection_state_;
864}
865
866PeerConnectionInterface::IceGatheringState
867PeerConnection::ice_gathering_state() {
868 return ice_gathering_state_;
869}
870
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000871rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872PeerConnection::CreateDataChannel(
873 const std::string& label,
874 const DataChannelInit* config) {
deadbeefab9b2d12015-10-14 11:33:11 -0700875 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000876
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000877 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000878 if (config) {
879 internal_config.reset(new InternalDataChannelInit(*config));
880 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000881 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700882 InternalCreateDataChannel(label, internal_config.get()));
883 if (!channel.get()) {
884 return nullptr;
885 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000887 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
888 // the first SCTP DataChannel.
889 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
890 observer_->OnRenegotiationNeeded();
891 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000892
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000893 return DataChannelProxy::Create(signaling_thread(), channel.get());
894}
895
896void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
897 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700898 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
900 return;
901 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000902 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000903
904 bool value;
905 size_t mandatory_constraints = 0;
906
907 if (FindConstraint(constraints,
908 MediaConstraintsInterface::kOfferToReceiveAudio,
909 &value,
910 &mandatory_constraints)) {
911 options.offer_to_receive_audio =
912 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
913 }
914
915 if (FindConstraint(constraints,
916 MediaConstraintsInterface::kOfferToReceiveVideo,
917 &value,
918 &mandatory_constraints)) {
919 options.offer_to_receive_video =
920 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
921 }
922
923 if (FindConstraint(constraints,
924 MediaConstraintsInterface::kVoiceActivityDetection,
925 &value,
926 &mandatory_constraints)) {
927 options.voice_activity_detection = value;
928 }
929
930 if (FindConstraint(constraints,
931 MediaConstraintsInterface::kIceRestart,
932 &value,
933 &mandatory_constraints)) {
934 options.ice_restart = value;
935 }
936
937 if (FindConstraint(constraints,
938 MediaConstraintsInterface::kUseRtpMux,
939 &value,
940 &mandatory_constraints)) {
941 options.use_rtp_mux = value;
942 }
943
944 CreateOffer(observer, options);
945}
946
947void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
948 const RTCOfferAnswerOptions& options) {
deadbeefab9b2d12015-10-14 11:33:11 -0700949 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000950 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
951 return;
952 }
deadbeefab9b2d12015-10-14 11:33:11 -0700953
954 cricket::MediaSessionOptions session_options;
955 if (!GetOptionsForOffer(options, &session_options)) {
956 std::string error = "CreateOffer called with invalid options.";
957 LOG(LS_ERROR) << error;
958 PostCreateSessionDescriptionFailure(observer, error);
959 return;
960 }
961
962 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963}
964
965void PeerConnection::CreateAnswer(
966 CreateSessionDescriptionObserver* observer,
967 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700968 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
970 return;
971 }
deadbeefab9b2d12015-10-14 11:33:11 -0700972
973 cricket::MediaSessionOptions session_options;
974 if (!GetOptionsForAnswer(constraints, &session_options)) {
975 std::string error = "CreateAnswer called with invalid constraints.";
976 LOG(LS_ERROR) << error;
977 PostCreateSessionDescriptionFailure(observer, error);
978 return;
979 }
980
981 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982}
983
984void PeerConnection::SetLocalDescription(
985 SetSessionDescriptionObserver* observer,
986 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -0700987 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
989 return;
990 }
991 if (!desc) {
992 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
993 return;
994 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995 // Update stats here so that we have the most recent stats for tracks and
996 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000997 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998 std::string error;
999 if (!session_->SetLocalDescription(desc, &error)) {
1000 PostSetSessionDescriptionFailure(observer, error);
1001 return;
1002 }
deadbeefab9b2d12015-10-14 11:33:11 -07001003
1004 // If setting the description decided our SSL role, allocate any necessary
1005 // SCTP sids.
1006 rtc::SSLRole role;
1007 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1008 session_->GetSslRole(&role)) {
1009 AllocateSctpSids(role);
1010 }
1011
1012 // Update state and SSRC of local MediaStreams and DataChannels based on the
1013 // local session description.
1014 const cricket::ContentInfo* audio_content =
1015 GetFirstAudioContent(desc->description());
1016 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001017 if (audio_content->rejected) {
1018 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1019 } else {
1020 const cricket::AudioContentDescription* audio_desc =
1021 static_cast<const cricket::AudioContentDescription*>(
1022 audio_content->description);
1023 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1024 }
deadbeefab9b2d12015-10-14 11:33:11 -07001025 }
1026
1027 const cricket::ContentInfo* video_content =
1028 GetFirstVideoContent(desc->description());
1029 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001030 if (video_content->rejected) {
1031 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1032 } else {
1033 const cricket::VideoContentDescription* video_desc =
1034 static_cast<const cricket::VideoContentDescription*>(
1035 video_content->description);
1036 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1037 }
deadbeefab9b2d12015-10-14 11:33:11 -07001038 }
1039
1040 const cricket::ContentInfo* data_content =
1041 GetFirstDataContent(desc->description());
1042 if (data_content) {
1043 const cricket::DataContentDescription* data_desc =
1044 static_cast<const cricket::DataContentDescription*>(
1045 data_content->description);
1046 if (rtc::starts_with(data_desc->protocol().data(),
1047 cricket::kMediaProtocolRtpPrefix)) {
1048 UpdateLocalRtpDataChannels(data_desc->streams());
1049 }
1050 }
1051
1052 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001054
deadbeefcbecd352015-09-23 11:50:27 -07001055 // MaybeStartGathering needs to be called after posting
1056 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1057 // before signaling that SetLocalDescription completed.
1058 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059}
1060
1061void PeerConnection::SetRemoteDescription(
1062 SetSessionDescriptionObserver* observer,
1063 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -07001064 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1066 return;
1067 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068 if (!desc) {
1069 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1070 return;
1071 }
1072 // Update stats here so that we have the most recent stats for tracks and
1073 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001074 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 std::string error;
1076 if (!session_->SetRemoteDescription(desc, &error)) {
1077 PostSetSessionDescriptionFailure(observer, error);
1078 return;
1079 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080
deadbeefab9b2d12015-10-14 11:33:11 -07001081 // If setting the description decided our SSL role, allocate any necessary
1082 // SCTP sids.
1083 rtc::SSLRole role;
1084 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1085 session_->GetSslRole(&role)) {
1086 AllocateSctpSids(role);
1087 }
1088
1089 const cricket::SessionDescription* remote_desc = desc->description();
1090
1091 // We wait to signal new streams until we finish processing the description,
1092 // since only at that point will new streams have all their tracks.
1093 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1094
1095 // Find all audio rtp streams and create corresponding remote AudioTracks
1096 // and MediaStreams.
1097 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1098 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001099 if (audio_content->rejected) {
1100 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1101 } else {
1102 const cricket::AudioContentDescription* desc =
1103 static_cast<const cricket::AudioContentDescription*>(
1104 audio_content->description);
1105 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(),
1106 new_streams);
1107 remote_info_.default_audio_track_needed =
1108 !remote_desc->msid_supported() && desc->streams().empty() &&
1109 MediaContentDirectionHasSend(desc->direction());
1110 }
deadbeefab9b2d12015-10-14 11:33:11 -07001111 }
1112
1113 // Find all video rtp streams and create corresponding remote VideoTracks
1114 // and MediaStreams.
1115 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1116 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001117 if (video_content->rejected) {
1118 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1119 } else {
1120 const cricket::VideoContentDescription* desc =
1121 static_cast<const cricket::VideoContentDescription*>(
1122 video_content->description);
1123 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(),
1124 new_streams);
1125 remote_info_.default_video_track_needed =
1126 !remote_desc->msid_supported() && desc->streams().empty() &&
1127 MediaContentDirectionHasSend(desc->direction());
1128 }
deadbeefab9b2d12015-10-14 11:33:11 -07001129 }
1130
1131 // Update the DataChannels with the information from the remote peer.
1132 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
1133 if (data_content) {
deadbeef5e97fb52015-10-15 12:49:08 -07001134 const cricket::DataContentDescription* desc =
deadbeefab9b2d12015-10-14 11:33:11 -07001135 static_cast<const cricket::DataContentDescription*>(
1136 data_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001137 if (rtc::starts_with(desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001138 cricket::kMediaProtocolRtpPrefix)) {
deadbeef5e97fb52015-10-15 12:49:08 -07001139 UpdateRemoteRtpDataChannels(GetActiveStreams(desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001140 }
1141 }
1142
1143 // Iterate new_streams and notify the observer about new MediaStreams.
1144 for (size_t i = 0; i < new_streams->count(); ++i) {
1145 MediaStreamInterface* new_stream = new_streams->at(i);
1146 stats_->AddStream(new_stream);
1147 observer_->OnAddStream(new_stream);
1148 }
1149
1150 // Find removed MediaStreams.
1151 if (remote_info_.IsDefaultMediaStreamNeeded() &&
1152 remote_streams_->find(kDefaultStreamLabel) != nullptr) {
1153 // The default media stream already exists. No need to do anything.
1154 } else {
1155 UpdateEndedRemoteMediaStreams();
1156 remote_info_.msid_supported |= remote_streams_->count() > 0;
1157 }
1158 MaybeCreateDefaultStream();
1159
1160 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1161 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001162}
1163
deadbeefa67696b2015-09-29 11:56:26 -07001164bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001165 if (port_allocator_) {
1166 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1167 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1168 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1169 return false;
1170 }
1171
deadbeef653b8e02015-11-11 12:55:10 -08001172 cricket::ServerAddresses cricket_stuns;
1173 std::vector<cricket::RelayServerConfig> cricket_turns;
1174 ConvertToCricketIceServers(stuns, turns, &cricket_stuns, &cricket_turns);
1175 port_allocator_->SetIceServers(cricket_stuns, cricket_turns);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001176 }
honghaiz1f429e32015-09-28 07:57:34 -07001177 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001178 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001179}
1180
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001181bool PeerConnection::AddIceCandidate(
1182 const IceCandidateInterface* ice_candidate) {
1183 return session_->ProcessIceMessage(ice_candidate);
1184}
1185
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001186void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
1187 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001188
1189 if (session_) {
1190 session_->set_metrics_observer(uma_observer_);
1191 }
1192
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001193 // Send information about IPv4/IPv6 status.
1194 if (uma_observer_ && port_allocator_) {
1195 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001196 uma_observer_->IncrementEnumCounter(
1197 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1198 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001199 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001200 uma_observer_->IncrementEnumCounter(
1201 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1202 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001203 }
1204 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001205}
1206
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001207const SessionDescriptionInterface* PeerConnection::local_description() const {
1208 return session_->local_description();
1209}
1210
1211const SessionDescriptionInterface* PeerConnection::remote_description() const {
1212 return session_->remote_description();
1213}
1214
1215void PeerConnection::Close() {
1216 // Update stats here so that we have the most recent stats for tracks and
1217 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001218 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001219
deadbeefd59daf82015-10-14 15:02:44 -07001220 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221}
1222
deadbeefd59daf82015-10-14 15:02:44 -07001223void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1224 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001225 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001226 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001228 break;
deadbeefd59daf82015-10-14 15:02:44 -07001229 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001230 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1231 break;
deadbeefd59daf82015-10-14 15:02:44 -07001232 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1234 break;
deadbeefd59daf82015-10-14 15:02:44 -07001235 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1237 break;
deadbeefd59daf82015-10-14 15:02:44 -07001238 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1240 break;
deadbeefd59daf82015-10-14 15:02:44 -07001241 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242 ChangeSignalingState(PeerConnectionInterface::kStable);
1243 break;
deadbeefd59daf82015-10-14 15:02:44 -07001244 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245 ChangeSignalingState(PeerConnectionInterface::kClosed);
1246 break;
1247 default:
1248 break;
1249 }
1250}
1251
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001252void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001253 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001254 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1255 SetSessionDescriptionMsg* param =
1256 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1257 param->observer->OnSuccess();
1258 delete param;
1259 break;
1260 }
1261 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1262 SetSessionDescriptionMsg* param =
1263 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1264 param->observer->OnFailure(param->error);
1265 delete param;
1266 break;
1267 }
deadbeefab9b2d12015-10-14 11:33:11 -07001268 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1269 CreateSessionDescriptionMsg* param =
1270 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1271 param->observer->OnFailure(param->error);
1272 delete param;
1273 break;
1274 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001275 case MSG_GETSTATS: {
1276 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001277 StatsReports reports;
1278 stats_->GetStats(param->track, &reports);
1279 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 delete param;
1281 break;
1282 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001284 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 break;
1286 }
1287}
1288
deadbeefab9b2d12015-10-14 11:33:11 -07001289void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1290 AudioTrackInterface* audio_track,
1291 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001292 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293}
1294
deadbeefab9b2d12015-10-14 11:33:11 -07001295void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1296 VideoTrackInterface* video_track,
1297 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001298 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299}
1300
deadbeef70ab1a12015-09-28 16:53:55 -07001301// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1302// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001303void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1304 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001305 auto it = FindReceiverForTrack(audio_track);
1306 if (it == receivers_.end()) {
1307 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1308 << " doesn't exist.";
1309 } else {
1310 (*it)->Stop();
1311 receivers_.erase(it);
1312 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313}
1314
deadbeefab9b2d12015-10-14 11:33:11 -07001315void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1316 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001317 auto it = FindReceiverForTrack(video_track);
1318 if (it == receivers_.end()) {
1319 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1320 << " doesn't exist.";
1321 } else {
1322 (*it)->Stop();
1323 receivers_.erase(it);
1324 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325}
deadbeef70ab1a12015-09-28 16:53:55 -07001326
deadbeef8f46c632015-10-26 14:11:17 -07001327void PeerConnection::CreateAudioSender(MediaStreamInterface* stream,
1328 AudioTrackInterface* audio_track,
1329 uint32_t ssrc) {
1330 senders_.push_back(new AudioRtpSender(audio_track, ssrc, session_.get()));
1331 stats_->AddLocalAudioTrack(audio_track, ssrc);
1332}
1333
1334void PeerConnection::CreateVideoSender(MediaStreamInterface* stream,
1335 VideoTrackInterface* video_track,
1336 uint32_t ssrc) {
1337 senders_.push_back(new VideoRtpSender(video_track, ssrc, session_.get()));
1338}
1339
1340// TODO(deadbeef): Keep RtpSenders around even if track goes away in local
1341// description.
1342void PeerConnection::DestroyAudioSender(MediaStreamInterface* stream,
1343 AudioTrackInterface* audio_track,
1344 uint32_t ssrc) {
1345 auto it = FindSenderForTrack(audio_track);
1346 if (it == senders_.end()) {
1347 LOG(LS_WARNING) << "RtpSender for track with id " << audio_track->id()
1348 << " doesn't exist.";
1349 return;
1350 } else {
1351 (*it)->Stop();
1352 senders_.erase(it);
1353 }
1354 stats_->RemoveLocalAudioTrack(audio_track, ssrc);
1355}
1356
1357void PeerConnection::DestroyVideoSender(MediaStreamInterface* stream,
1358 VideoTrackInterface* video_track) {
1359 auto it = FindSenderForTrack(video_track);
1360 if (it == senders_.end()) {
1361 LOG(LS_WARNING) << "RtpSender for track with id " << video_track->id()
1362 << " doesn't exist.";
1363 return;
1364 } else {
1365 (*it)->Stop();
1366 senders_.erase(it);
1367 }
1368}
1369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370void PeerConnection::OnIceConnectionChange(
1371 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001372 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001373 // After transitioning to "closed", ignore any additional states from
1374 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001375 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001376 return;
1377 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001379 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380}
1381
1382void PeerConnection::OnIceGatheringChange(
1383 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001384 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385 if (IsClosed()) {
1386 return;
1387 }
1388 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001389 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390}
1391
1392void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001393 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001394 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395}
1396
1397void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001398 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001399 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400}
1401
Peter Thatcher54360512015-07-08 11:08:35 -07001402void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001403 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001404 observer_->OnIceConnectionReceivingChange(receiving);
1405}
1406
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407void PeerConnection::ChangeSignalingState(
1408 PeerConnectionInterface::SignalingState signaling_state) {
1409 signaling_state_ = signaling_state;
1410 if (signaling_state == kClosed) {
1411 ice_connection_state_ = kIceConnectionClosed;
1412 observer_->OnIceConnectionChange(ice_connection_state_);
1413 if (ice_gathering_state_ != kIceGatheringComplete) {
1414 ice_gathering_state_ = kIceGatheringComplete;
1415 observer_->OnIceGatheringChange(ice_gathering_state_);
1416 }
1417 }
1418 observer_->OnSignalingChange(signaling_state_);
1419 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1420}
1421
deadbeefab9b2d12015-10-14 11:33:11 -07001422void PeerConnection::PostSetSessionDescriptionFailure(
1423 SetSessionDescriptionObserver* observer,
1424 const std::string& error) {
1425 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1426 msg->error = error;
1427 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1428}
1429
1430void PeerConnection::PostCreateSessionDescriptionFailure(
1431 CreateSessionDescriptionObserver* observer,
1432 const std::string& error) {
1433 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1434 msg->error = error;
1435 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1436}
1437
1438bool PeerConnection::GetOptionsForOffer(
1439 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1440 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001441 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1442 return false;
1443 }
1444
deadbeef8f46c632015-10-26 14:11:17 -07001445 SetStreams(session_options, local_streams_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001446 // Offer to receive audio/video if the constraint is not set and there are
1447 // send streams, or we're currently receiving.
1448 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1449 session_options->recv_audio =
1450 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1451 !remote_audio_tracks_.empty();
1452 }
1453 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1454 session_options->recv_video =
1455 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1456 !remote_video_tracks_.empty();
1457 }
1458 session_options->bundle_enabled =
1459 session_options->bundle_enabled &&
1460 (session_options->has_audio() || session_options->has_video() ||
1461 session_options->has_data());
1462
deadbeefab9b2d12015-10-14 11:33:11 -07001463 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1464 session_options->data_channel_type = cricket::DCT_SCTP;
1465 }
1466 return true;
1467}
1468
1469bool PeerConnection::GetOptionsForAnswer(
1470 const MediaConstraintsInterface* constraints,
1471 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001472 session_options->recv_audio = false;
1473 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001474 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1475 return false;
1476 }
1477
deadbeef8f46c632015-10-26 14:11:17 -07001478 SetStreams(session_options, local_streams_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001479 session_options->bundle_enabled =
1480 session_options->bundle_enabled &&
1481 (session_options->has_audio() || session_options->has_video() ||
1482 session_options->has_data());
1483
deadbeefab9b2d12015-10-14 11:33:11 -07001484 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1485 // are not signaled in the SDP so does not go through that path and must be
1486 // handled here.
1487 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1488 session_options->data_channel_type = cricket::DCT_SCTP;
1489 }
1490 return true;
1491}
1492
deadbeeffaac4972015-11-12 15:33:07 -08001493void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1494 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
1495 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), media_type,
1496 nullptr);
1497}
1498
deadbeefab9b2d12015-10-14 11:33:11 -07001499void PeerConnection::UpdateRemoteStreamsList(
1500 const cricket::StreamParamsVec& streams,
1501 cricket::MediaType media_type,
1502 StreamCollection* new_streams) {
1503 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1504
1505 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeef8f46c632015-10-26 14:11:17 -07001506 // the
1507 // new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001508 auto track_it = current_tracks->begin();
1509 while (track_it != current_tracks->end()) {
1510 const TrackInfo& info = *track_it;
1511 const cricket::StreamParams* params =
1512 cricket::GetStreamBySsrc(streams, info.ssrc);
1513 if (!params || params->id != info.track_id) {
1514 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1515 track_it = current_tracks->erase(track_it);
1516 } else {
1517 ++track_it;
1518 }
1519 }
1520
1521 // Find new and active tracks.
1522 for (const cricket::StreamParams& params : streams) {
1523 // The sync_label is the MediaStream label and the |stream.id| is the
1524 // track id.
1525 const std::string& stream_label = params.sync_label;
1526 const std::string& track_id = params.id;
1527 uint32_t ssrc = params.first_ssrc();
1528
1529 rtc::scoped_refptr<MediaStreamInterface> stream =
1530 remote_streams_->find(stream_label);
1531 if (!stream) {
1532 // This is a new MediaStream. Create a new remote MediaStream.
1533 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1534 remote_streams_->AddStream(stream);
1535 new_streams->AddStream(stream);
1536 }
1537
1538 const TrackInfo* track_info =
1539 FindTrackInfo(*current_tracks, stream_label, track_id);
1540 if (!track_info) {
1541 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1542 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1543 }
1544 }
1545}
1546
1547void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1548 const std::string& track_id,
1549 uint32_t ssrc,
1550 cricket::MediaType media_type) {
1551 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1552
1553 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1554 AudioTrackInterface* audio_track =
1555 remote_stream_factory_->AddAudioTrack(stream, track_id);
1556 CreateAudioReceiver(stream, audio_track, ssrc);
1557 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1558 VideoTrackInterface* video_track =
1559 remote_stream_factory_->AddVideoTrack(stream, track_id);
1560 CreateVideoReceiver(stream, video_track, ssrc);
1561 } else {
1562 RTC_DCHECK(false && "Invalid media type");
1563 }
1564}
1565
1566void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1567 const std::string& track_id,
1568 cricket::MediaType media_type) {
1569 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1570
1571 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1572 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1573 stream->FindAudioTrack(track_id);
1574 if (audio_track) {
1575 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1576 stream->RemoveTrack(audio_track);
1577 DestroyAudioReceiver(stream, audio_track);
1578 }
1579 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1580 rtc::scoped_refptr<VideoTrackInterface> video_track =
1581 stream->FindVideoTrack(track_id);
1582 if (video_track) {
1583 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1584 stream->RemoveTrack(video_track);
1585 DestroyVideoReceiver(stream, video_track);
1586 }
1587 } else {
1588 ASSERT(false && "Invalid media type");
1589 }
1590}
1591
1592void PeerConnection::UpdateEndedRemoteMediaStreams() {
1593 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1594 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1595 MediaStreamInterface* stream = remote_streams_->at(i);
1596 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1597 streams_to_remove.push_back(stream);
1598 }
1599 }
1600
1601 for (const auto& stream : streams_to_remove) {
1602 remote_streams_->RemoveStream(stream);
1603 observer_->OnRemoveStream(stream);
1604 }
1605}
1606
1607void PeerConnection::MaybeCreateDefaultStream() {
1608 if (!remote_info_.IsDefaultMediaStreamNeeded()) {
1609 return;
1610 }
1611
1612 bool default_created = false;
1613
1614 rtc::scoped_refptr<MediaStreamInterface> default_remote_stream =
1615 remote_streams_->find(kDefaultStreamLabel);
1616 if (default_remote_stream == nullptr) {
1617 default_created = true;
1618 default_remote_stream =
1619 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1620 remote_streams_->AddStream(default_remote_stream);
1621 }
1622 if (remote_info_.default_audio_track_needed &&
1623 default_remote_stream->GetAudioTracks().size() == 0) {
1624 remote_audio_tracks_.push_back(
1625 TrackInfo(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0));
1626 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
1627 cricket::MEDIA_TYPE_AUDIO);
1628 }
1629 if (remote_info_.default_video_track_needed &&
1630 default_remote_stream->GetVideoTracks().size() == 0) {
1631 remote_video_tracks_.push_back(
1632 TrackInfo(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0));
1633 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
1634 cricket::MEDIA_TYPE_VIDEO);
1635 }
1636 if (default_created) {
1637 stats_->AddStream(default_remote_stream);
1638 observer_->OnAddStream(default_remote_stream);
1639 }
1640}
1641
1642void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1643 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1644 for (TrackInfos::iterator track_it = current_tracks->begin();
1645 track_it != current_tracks->end(); ++track_it) {
1646 const TrackInfo& info = *track_it;
1647 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1648 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1649 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1650 // There's no guarantee the track is still available, e.g. the track may
1651 // have been removed from the stream by javascript.
1652 if (track) {
1653 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1654 }
1655 }
1656 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1657 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1658 // There's no guarantee the track is still available, e.g. the track may
1659 // have been removed from the stream by javascript.
1660 if (track) {
1661 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1662 }
1663 }
1664 }
1665}
1666
1667void PeerConnection::UpdateLocalTracks(
1668 const std::vector<cricket::StreamParams>& streams,
1669 cricket::MediaType media_type) {
1670 TrackInfos* current_tracks = GetLocalTracks(media_type);
1671
1672 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1673 // don't match the new StreamParam.
1674 TrackInfos::iterator track_it = current_tracks->begin();
1675 while (track_it != current_tracks->end()) {
1676 const TrackInfo& info = *track_it;
1677 const cricket::StreamParams* params =
1678 cricket::GetStreamBySsrc(streams, info.ssrc);
1679 if (!params || params->id != info.track_id ||
1680 params->sync_label != info.stream_label) {
1681 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1682 media_type);
1683 track_it = current_tracks->erase(track_it);
1684 } else {
1685 ++track_it;
1686 }
1687 }
1688
1689 // Find new and active tracks.
1690 for (const cricket::StreamParams& params : streams) {
1691 // The sync_label is the MediaStream label and the |stream.id| is the
1692 // track id.
1693 const std::string& stream_label = params.sync_label;
1694 const std::string& track_id = params.id;
1695 uint32_t ssrc = params.first_ssrc();
1696 const TrackInfo* track_info =
1697 FindTrackInfo(*current_tracks, stream_label, track_id);
1698 if (!track_info) {
1699 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1700 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1701 }
1702 }
1703}
1704
1705void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1706 const std::string& track_id,
1707 uint32_t ssrc,
1708 cricket::MediaType media_type) {
deadbeef8f46c632015-10-26 14:11:17 -07001709 MediaStreamInterface* stream = local_streams_->find(stream_label);
1710 if (!stream) {
1711 LOG(LS_WARNING) << "An unknown local MediaStream with label "
1712 << stream_label << " has been configured.";
deadbeefab9b2d12015-10-14 11:33:11 -07001713 return;
1714 }
1715
deadbeef8f46c632015-10-26 14:11:17 -07001716 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1717 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1718 if (!audio_track) {
1719 LOG(LS_WARNING) << "An unknown local AudioTrack with id , " << track_id
1720 << " has been configured.";
1721 return;
1722 }
1723 CreateAudioSender(stream, audio_track, ssrc);
1724 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1725 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1726 if (!video_track) {
1727 LOG(LS_WARNING) << "An unknown local VideoTrack with id , " << track_id
1728 << " has been configured.";
1729 return;
1730 }
1731 CreateVideoSender(stream, video_track, ssrc);
1732 } else {
1733 RTC_DCHECK(false && "Invalid media type");
deadbeefab9b2d12015-10-14 11:33:11 -07001734 }
1735}
1736
1737void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1738 const std::string& track_id,
1739 uint32_t ssrc,
1740 cricket::MediaType media_type) {
deadbeef8f46c632015-10-26 14:11:17 -07001741 MediaStreamInterface* stream = local_streams_->find(stream_label);
1742 if (!stream) {
1743 // This is the normal case. I.e., RemoveLocalStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001744 // SessionDescriptions has been renegotiated.
1745 return;
1746 }
deadbeef8f46c632015-10-26 14:11:17 -07001747 // A track has been removed from the SessionDescription but the MediaStream
1748 // is still associated with PeerConnection. This only occurs if the SDP
1749 // doesn't match with the calls to AddLocalStream and RemoveLocalStream.
1750 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1751 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1752 if (!audio_track) {
1753 return;
1754 }
1755 DestroyAudioSender(stream, audio_track, ssrc);
1756 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1757 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1758 if (!video_track) {
1759 return;
1760 }
1761 DestroyVideoSender(stream, video_track);
1762 } else {
1763 RTC_DCHECK(false && "Invalid media type.");
deadbeefab9b2d12015-10-14 11:33:11 -07001764 }
1765}
1766
1767void PeerConnection::UpdateLocalRtpDataChannels(
1768 const cricket::StreamParamsVec& streams) {
1769 std::vector<std::string> existing_channels;
1770
1771 // Find new and active data channels.
1772 for (const cricket::StreamParams& params : streams) {
1773 // |it->sync_label| is actually the data channel label. The reason is that
1774 // we use the same naming of data channels as we do for
1775 // MediaStreams and Tracks.
1776 // For MediaStreams, the sync_label is the MediaStream label and the
1777 // track label is the same as |streamid|.
1778 const std::string& channel_label = params.sync_label;
1779 auto data_channel_it = rtp_data_channels_.find(channel_label);
1780 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1781 continue;
1782 }
1783 // Set the SSRC the data channel should use for sending.
1784 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1785 existing_channels.push_back(data_channel_it->first);
1786 }
1787
1788 UpdateClosingRtpDataChannels(existing_channels, true);
1789}
1790
1791void PeerConnection::UpdateRemoteRtpDataChannels(
1792 const cricket::StreamParamsVec& streams) {
1793 std::vector<std::string> existing_channels;
1794
1795 // Find new and active data channels.
1796 for (const cricket::StreamParams& params : streams) {
1797 // The data channel label is either the mslabel or the SSRC if the mslabel
1798 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1799 std::string label = params.sync_label.empty()
1800 ? rtc::ToString(params.first_ssrc())
1801 : params.sync_label;
1802 auto data_channel_it = rtp_data_channels_.find(label);
1803 if (data_channel_it == rtp_data_channels_.end()) {
1804 // This is a new data channel.
1805 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1806 } else {
1807 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1808 }
1809 existing_channels.push_back(label);
1810 }
1811
1812 UpdateClosingRtpDataChannels(existing_channels, false);
1813}
1814
1815void PeerConnection::UpdateClosingRtpDataChannels(
1816 const std::vector<std::string>& active_channels,
1817 bool is_local_update) {
1818 auto it = rtp_data_channels_.begin();
1819 while (it != rtp_data_channels_.end()) {
1820 DataChannel* data_channel = it->second;
1821 if (std::find(active_channels.begin(), active_channels.end(),
1822 data_channel->label()) != active_channels.end()) {
1823 ++it;
1824 continue;
1825 }
1826
1827 if (is_local_update) {
1828 data_channel->SetSendSsrc(0);
1829 } else {
1830 data_channel->RemotePeerRequestClose();
1831 }
1832
1833 if (data_channel->state() == DataChannel::kClosed) {
1834 rtp_data_channels_.erase(it);
1835 it = rtp_data_channels_.begin();
1836 } else {
1837 ++it;
1838 }
1839 }
1840}
1841
1842void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1843 uint32_t remote_ssrc) {
1844 rtc::scoped_refptr<DataChannel> channel(
1845 InternalCreateDataChannel(label, nullptr));
1846 if (!channel.get()) {
1847 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1848 << "CreateDataChannel failed.";
1849 return;
1850 }
1851 channel->SetReceiveSsrc(remote_ssrc);
1852 observer_->OnDataChannel(
1853 DataChannelProxy::Create(signaling_thread(), channel));
1854}
1855
1856rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1857 const std::string& label,
1858 const InternalDataChannelInit* config) {
1859 if (IsClosed()) {
1860 return nullptr;
1861 }
1862 if (session_->data_channel_type() == cricket::DCT_NONE) {
1863 LOG(LS_ERROR)
1864 << "InternalCreateDataChannel: Data is not supported in this call.";
1865 return nullptr;
1866 }
1867 InternalDataChannelInit new_config =
1868 config ? (*config) : InternalDataChannelInit();
1869 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1870 if (new_config.id < 0) {
1871 rtc::SSLRole role;
1872 if (session_->GetSslRole(&role) &&
1873 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1874 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1875 return nullptr;
1876 }
1877 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1878 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1879 << "because the id is already in use or out of range.";
1880 return nullptr;
1881 }
1882 }
1883
1884 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1885 session_.get(), session_->data_channel_type(), label, new_config));
1886 if (!channel) {
1887 sid_allocator_.ReleaseSid(new_config.id);
1888 return nullptr;
1889 }
1890
1891 if (channel->data_channel_type() == cricket::DCT_RTP) {
1892 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1893 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1894 << " already exists.";
1895 return nullptr;
1896 }
1897 rtp_data_channels_[channel->label()] = channel;
1898 } else {
1899 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1900 sctp_data_channels_.push_back(channel);
1901 channel->SignalClosed.connect(this,
1902 &PeerConnection::OnSctpDataChannelClosed);
1903 }
1904
1905 return channel;
1906}
1907
1908bool PeerConnection::HasDataChannels() const {
1909 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1910}
1911
1912void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1913 for (const auto& channel : sctp_data_channels_) {
1914 if (channel->id() < 0) {
1915 int sid;
1916 if (!sid_allocator_.AllocateSid(role, &sid)) {
1917 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1918 continue;
1919 }
1920 channel->SetSctpSid(sid);
1921 }
1922 }
1923}
1924
1925void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1926 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1927 ++it) {
1928 if (it->get() == channel) {
1929 if (channel->id() >= 0) {
1930 sid_allocator_.ReleaseSid(channel->id());
1931 }
1932 sctp_data_channels_.erase(it);
1933 return;
1934 }
1935 }
1936}
1937
1938void PeerConnection::OnVoiceChannelDestroyed() {
1939 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1940}
1941
1942void PeerConnection::OnVideoChannelDestroyed() {
1943 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1944}
1945
1946void PeerConnection::OnDataChannelCreated() {
1947 for (const auto& channel : sctp_data_channels_) {
1948 channel->OnTransportChannelCreated();
1949 }
1950}
1951
1952void PeerConnection::OnDataChannelDestroyed() {
1953 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1954 // DataChannel may callback to us and try to modify the list.
1955 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1956 temp_rtp_dcs.swap(rtp_data_channels_);
1957 for (const auto& kv : temp_rtp_dcs) {
1958 kv.second->OnTransportChannelDestroyed();
1959 }
1960
1961 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1962 temp_sctp_dcs.swap(sctp_data_channels_);
1963 for (const auto& channel : temp_sctp_dcs) {
1964 channel->OnTransportChannelDestroyed();
1965 }
1966}
1967
1968void PeerConnection::OnDataChannelOpenMessage(
1969 const std::string& label,
1970 const InternalDataChannelInit& config) {
1971 rtc::scoped_refptr<DataChannel> channel(
1972 InternalCreateDataChannel(label, &config));
1973 if (!channel.get()) {
1974 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1975 return;
1976 }
1977
1978 observer_->OnDataChannel(
1979 DataChannelProxy::Create(signaling_thread(), channel));
1980}
1981
deadbeef70ab1a12015-09-28 16:53:55 -07001982std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1983PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1984 return std::find_if(
1985 senders_.begin(), senders_.end(),
1986 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1987 return sender->track() == track;
1988 });
1989}
1990
1991std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1992PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1993 return std::find_if(
1994 receivers_.begin(), receivers_.end(),
1995 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1996 return receiver->track() == track;
1997 });
1998}
1999
deadbeefab9b2d12015-10-14 11:33:11 -07002000PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2001 cricket::MediaType media_type) {
2002 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2003 media_type == cricket::MEDIA_TYPE_VIDEO);
2004 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2005 : &remote_video_tracks_;
2006}
2007
2008PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2009 cricket::MediaType media_type) {
2010 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2011 media_type == cricket::MEDIA_TYPE_VIDEO);
2012 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2013 : &local_video_tracks_;
2014}
2015
2016const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2017 const PeerConnection::TrackInfos& infos,
2018 const std::string& stream_label,
2019 const std::string track_id) const {
2020 for (const TrackInfo& track_info : infos) {
2021 if (track_info.stream_label == stream_label &&
2022 track_info.track_id == track_id) {
2023 return &track_info;
2024 }
2025 }
2026 return nullptr;
2027}
2028
2029DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2030 for (const auto& channel : sctp_data_channels_) {
2031 if (channel->id() == sid) {
2032 return channel;
2033 }
2034 }
2035 return nullptr;
2036}
2037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038} // namespace webrtc