blob: e217f8089fe8f98b7d942034857d48fc7ee42aa0 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070037#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010038#include "webrtc/base/trace_event.h"
ivoc14d5dbe2016-07-04 07:06:55 -070039#include "webrtc/call.h"
kjellandera96e2d72016-02-04 23:52:28 -080040#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010041#include "webrtc/pc/channelmanager.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010042#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043
44namespace {
45
deadbeefab9b2d12015-10-14 11:33:11 -070046using webrtc::DataChannel;
47using webrtc::MediaConstraintsInterface;
48using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070050using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080051using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070052using webrtc::RtpSenderProxy;
53using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070054using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
deadbeefab9b2d12015-10-14 11:33:11 -070056static const char kDefaultStreamLabel[] = "default";
57static const char kDefaultAudioTrackLabel[] = "defaulta0";
58static const char kDefaultVideoTrackLabel[] = "defaultv0";
59
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060// The min number of tokens must present in Turn host uri.
61// e.g. user@turn.example.org
62static const size_t kTurnHostTokensNum = 2;
63// Number of tokens must be preset when TURN uri has transport param.
64static const size_t kTurnTransportTokensNum = 2;
65// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000066static const int kDefaultStunPort = 3478;
67static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069
70// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070071static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
zhihuang8f65cdf2016-05-06 18:40:30 -070073// The length of RTCP CNAMEs.
74static const int kRtcpCnameLength = 16;
75
deadbeef0a6c4ca2015-10-06 11:38:28 -070076// NOTE: A loop below assumes that the first value of this enum is 0 and all
77// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070079 STUN = 0, // Indicates a STUN server.
80 STUNS, // Indicates a STUN server used with a TLS session.
81 TURN, // Indicates a TURN server
82 TURNS, // Indicates a TURN server used with a TLS session.
83 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000084};
tfarina5237aaf2015-11-10 23:44:30 -080085static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070086 "kValidIceServiceTypes must have as many strings as ServiceType "
87 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
89enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000090 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070092 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080094 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095};
96
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000097struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098 explicit SetSessionDescriptionMsg(
99 webrtc::SetSessionDescriptionObserver* observer)
100 : observer(observer) {
101 }
102
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000103 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 std::string error;
105};
106
deadbeefab9b2d12015-10-14 11:33:11 -0700107struct CreateSessionDescriptionMsg : public rtc::MessageData {
108 explicit CreateSessionDescriptionMsg(
109 webrtc::CreateSessionDescriptionObserver* observer)
110 : observer(observer) {}
111
112 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
113 std::string error;
114};
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000117 GetStatsMsg(webrtc::StatsObserver* observer,
118 webrtc::MediaStreamTrackInterface* track)
119 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000120 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000121 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000122 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000123};
124
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000125// |in_str| should be of format
126// stunURI = scheme ":" stun-host [ ":" stun-port ]
127// scheme = "stun" / "stuns"
128// stun-host = IP-literal / IPv4address / reg-name
129// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700130//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000131// draft-petithuguenin-behave-turn-uris-01
132// turnURI = scheme ":" turn-host [ ":" turn-port ]
133// turn-host = username@IP-literal / IPv4address / reg-name
134bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
135 ServiceType* service_type,
136 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200137 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700138 if (colonpos == std::string::npos) {
139 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000140 return false;
141 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700142 if ((colonpos + 1) == in_str.length()) {
143 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
144 return false;
145 }
146 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800147 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700148 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000149 *service_type = static_cast<ServiceType>(i);
150 break;
151 }
152 }
153 if (*service_type == INVALID) {
154 return false;
155 }
156 *hostname = in_str.substr(colonpos + 1, std::string::npos);
157 return true;
158}
159
deadbeef0a6c4ca2015-10-06 11:38:28 -0700160bool ParsePort(const std::string& in_str, int* port) {
161 // Make sure port only contains digits. FromString doesn't check this.
162 for (const char& c : in_str) {
163 if (!std::isdigit(c)) {
164 return false;
165 }
166 }
167 return rtc::FromString(in_str, port);
168}
169
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000170// This method parses IPv6 and IPv4 literal strings, along with hostnames in
171// standard hostname:port format.
172// Consider following formats as correct.
173// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700174// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000175bool ParseHostnameAndPortFromString(const std::string& in_str,
176 std::string* host,
177 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700178 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000179 if (in_str.at(0) == '[') {
180 std::string::size_type closebracket = in_str.rfind(']');
181 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000182 std::string::size_type colonpos = in_str.find(':', closebracket);
183 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700184 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
185 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000186 return false;
187 }
188 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700189 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000190 } else {
191 return false;
192 }
193 } else {
194 std::string::size_type colonpos = in_str.find(':');
195 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700196 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000197 return false;
198 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700199 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000200 } else {
201 *host = in_str;
202 }
203 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700204 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000205}
206
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800207// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700208// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200209bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
210 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800211 cricket::ServerAddresses* stun_servers,
212 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213 // draft-nandakumar-rtcweb-stun-uri-01
214 // stunURI = scheme ":" stun-host [ ":" stun-port ]
215 // scheme = "stun" / "stuns"
216 // stun-host = IP-literal / IPv4address / reg-name
217 // stun-port = *DIGIT
218
219 // draft-petithuguenin-behave-turn-uris-01
220 // turnURI = scheme ":" turn-host [ ":" turn-port ]
221 // [ "?transport=" transport ]
222 // scheme = "turn" / "turns"
223 // transport = "udp" / "tcp" / transport-ext
224 // transport-ext = 1*unreserved
225 // turn-host = IP-literal / IPv4address / reg-name
226 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800227 RTC_DCHECK(stun_servers != nullptr);
228 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200229 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800230 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700231 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200232 rtc::tokenize(url, '?', &tokens);
233 std::string uri_without_transport = tokens[0];
234 // Let's look into transport= param, if it exists.
235 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
236 std::string uri_transport_param = tokens[1];
237 rtc::tokenize(uri_transport_param, '=', &tokens);
238 if (tokens[0] == kTransport) {
239 // As per above grammar transport param will be consist of lower case
240 // letters.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800241 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
242 (turn_transport_type != cricket::PROTO_UDP &&
243 turn_transport_type != cricket::PROTO_TCP)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200244 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700245 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000246 }
247 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200248 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200250 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700251 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200252 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
253 &service_type,
254 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700255 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
256 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200257 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000258
deadbeef0a6c4ca2015-10-06 11:38:28 -0700259 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
260 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200261
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200262 // Let's break hostname.
263 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700264 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
265
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200266 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700267 if (tokens.size() > kTurnHostTokensNum) {
268 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
269 return false;
270 }
271 if (tokens.size() == kTurnHostTokensNum) {
272 if (tokens[0].empty() || tokens[1].empty()) {
273 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
274 return false;
275 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200276 username.assign(rtc::s_url_decode(tokens[0]));
277 hoststring = tokens[1];
278 } else {
279 hoststring = tokens[0];
280 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000281
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200282 int port = kDefaultStunPort;
283 if (service_type == TURNS) {
284 port = kDefaultStunTlsPort;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800285 turn_transport_type = cricket::PROTO_TCP;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200286 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000287
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200288 std::string address;
289 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
291 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200292 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000293
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200294 if (port <= 0 || port > 0xffff) {
295 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700296 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000298
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 switch (service_type) {
300 case STUN:
301 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800302 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200303 break;
304 case TURN:
305 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200306 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800307 turn_servers->push_back(
308 cricket::RelayServerConfig(address, port, username, server.password,
309 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200310 break;
311 }
312 case INVALID:
313 default:
314 LOG(WARNING) << "Configuration not supported: " << url;
315 return false;
316 }
317 return true;
318}
319
deadbeefab9b2d12015-10-14 11:33:11 -0700320// Check if we can send |new_stream| on a PeerConnection.
321bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
322 webrtc::MediaStreamInterface* new_stream) {
323 if (!new_stream || !current_streams) {
324 return false;
325 }
326 if (current_streams->find(new_stream->label()) != nullptr) {
327 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
328 << " is already added.";
329 return false;
330 }
331 return true;
332}
333
334bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
335 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
336}
337
deadbeef5e97fb52015-10-15 12:49:08 -0700338// If the direction is "recvonly" or "inactive", treat the description
339// as containing no streams.
340// See: https://code.google.com/p/webrtc/issues/detail?id=5054
341std::vector<cricket::StreamParams> GetActiveStreams(
342 const cricket::MediaContentDescription* desc) {
343 return MediaContentDirectionHasSend(desc->direction())
344 ? desc->streams()
345 : std::vector<cricket::StreamParams>();
346}
347
deadbeefab9b2d12015-10-14 11:33:11 -0700348bool IsValidOfferToReceiveMedia(int value) {
349 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
350 return (value >= Options::kUndefined) &&
351 (value <= Options::kMaxOfferToReceiveMedia);
352}
353
354// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800355void AddSendStreams(
356 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700357 const std::vector<rtc::scoped_refptr<
358 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800359 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
360 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700361 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800362 for (const auto& sender : senders) {
363 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700364 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700365 }
366
367 // Check for data channels.
368 for (const auto& kv : rtp_data_channels) {
369 const DataChannel* channel = kv.second;
370 if (channel->state() == DataChannel::kConnecting ||
371 channel->state() == DataChannel::kOpen) {
372 // |streamid| and |sync_label| are both set to the DataChannel label
373 // here so they can be signaled the same way as MediaStreams and Tracks.
374 // For MediaStreams, the sync_label is the MediaStream label and the
375 // track label is the same as |streamid|.
376 const std::string& streamid = channel->label();
377 const std::string& sync_label = channel->label();
378 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
379 sync_label);
380 }
381 }
382}
383
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700384uint32_t ConvertIceTransportTypeToCandidateFilter(
385 PeerConnectionInterface::IceTransportsType type) {
386 switch (type) {
387 case PeerConnectionInterface::kNone:
388 return cricket::CF_NONE;
389 case PeerConnectionInterface::kRelay:
390 return cricket::CF_RELAY;
391 case PeerConnectionInterface::kNoHost:
392 return (cricket::CF_ALL & ~cricket::CF_HOST);
393 case PeerConnectionInterface::kAll:
394 return cricket::CF_ALL;
395 default:
396 ASSERT(false);
397 }
398 return cricket::CF_NONE;
399}
400
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700401// Helper method to set a voice/video channel on all applicable senders
402// and receivers when one is created/destroyed by WebRtcSession.
403//
404// Used by On(Voice|Video)Channel(Created|Destroyed)
405template <class SENDER,
406 class RECEIVER,
407 class CHANNEL,
408 class SENDERS,
409 class RECEIVERS>
410void SetChannelOnSendersAndReceivers(CHANNEL* channel,
411 SENDERS& senders,
412 RECEIVERS& receivers,
413 cricket::MediaType media_type) {
414 for (auto& sender : senders) {
415 if (sender->media_type() == media_type) {
416 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
417 }
418 }
419 for (auto& receiver : receivers) {
420 if (receiver->media_type() == media_type) {
421 if (!channel) {
422 receiver->internal()->Stop();
423 }
424 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
425 }
426 }
427}
428
deadbeef0a6c4ca2015-10-06 11:38:28 -0700429} // namespace
430
431namespace webrtc {
432
zhihuang8f65cdf2016-05-06 18:40:30 -0700433// Generate a RTCP CNAME when a PeerConnection is created.
434std::string GenerateRtcpCname() {
435 std::string cname;
436 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
437 LOG(LS_ERROR) << "Failed to generate CNAME.";
438 RTC_DCHECK(false);
439 }
440 return cname;
441}
442
htaa2a49d92016-03-04 02:51:39 -0800443bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700444 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800445 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700446 cricket::MediaSessionOptions* session_options) {
447 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
448 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
449 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
450 return false;
451 }
452
htaaac2dea2016-03-10 13:35:55 -0800453 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700454 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700455 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800456 } else {
457 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700458 }
htaaac2dea2016-03-10 13:35:55 -0800459 // For offers, we only offer video if we have it or it's forced by options.
460 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700461 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700462 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800463 } else if (is_offer) {
464 session_options->recv_video = false;
465 } else {
466 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700467 }
468
469 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700470 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800471 for (auto& kv : session_options->transport_options) {
472 kv.second.ice_restart = rtc_options.ice_restart;
473 }
deadbeefab9b2d12015-10-14 11:33:11 -0700474
475 return true;
476}
477
478bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
479 cricket::MediaSessionOptions* session_options) {
480 bool value = false;
481 size_t mandatory_constraints_satisfied = 0;
482
483 // kOfferToReceiveAudio defaults to true according to spec.
484 if (!FindConstraint(constraints,
485 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
486 &mandatory_constraints_satisfied) ||
487 value) {
488 session_options->recv_audio = true;
489 }
490
491 // kOfferToReceiveVideo defaults to false according to spec. But
492 // if it is an answer and video is offered, we should still accept video
493 // per default.
494 value = false;
495 if (!FindConstraint(constraints,
496 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
497 &mandatory_constraints_satisfied) ||
498 value) {
499 session_options->recv_video = true;
500 }
501
502 if (FindConstraint(constraints,
503 MediaConstraintsInterface::kVoiceActivityDetection, &value,
504 &mandatory_constraints_satisfied)) {
505 session_options->vad_enabled = value;
506 }
507
508 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
509 &mandatory_constraints_satisfied)) {
510 session_options->bundle_enabled = value;
511 } else {
512 // kUseRtpMux defaults to true according to spec.
513 session_options->bundle_enabled = true;
514 }
deadbeefab9b2d12015-10-14 11:33:11 -0700515
deadbeef0ed85b22016-02-23 17:24:52 -0800516 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700517 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
518 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700519 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800520 ice_restart = true;
521 }
522 for (auto& kv : session_options->transport_options) {
523 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700524 }
525
526 if (!constraints) {
527 return true;
528 }
529 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
530}
531
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200532bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800533 cricket::ServerAddresses* stun_servers,
534 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200535 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
536 if (!server.urls.empty()) {
537 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200538 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700539 LOG(LS_ERROR) << "Empty uri.";
540 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200541 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800542 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200543 return false;
544 }
545 }
546 } else if (!server.uri.empty()) {
547 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800548 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000549 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200550 }
551 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700552 LOG(LS_ERROR) << "Empty uri.";
553 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000554 }
555 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800556 // Candidates must have unique priorities, so that connectivity checks
557 // are performed in a well-defined order.
558 int priority = static_cast<int>(turn_servers->size() - 1);
559 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
560 // First in the list gets highest priority.
561 turn_server.priority = priority--;
562 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000563 return true;
564}
565
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000566PeerConnection::PeerConnection(PeerConnectionFactory* factory)
567 : factory_(factory),
568 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000569 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000570 signaling_state_(kStable),
571 ice_state_(kIceNew),
572 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700573 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700574 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700575 local_streams_(StreamCollection::Create()),
576 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000577
578PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100579 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700580 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700581 // Need to detach RTP senders/receivers from WebRtcSession,
582 // since it's about to be destroyed.
583 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700584 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700585 }
586 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700587 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700588 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700589 // Destroy stats_ because it depends on session_.
590 stats_.reset(nullptr);
591 // Now destroy session_ before destroying other members,
592 // because its destruction fires signals (such as VoiceChannelDestroyed)
593 // which will trigger some final actions in PeerConnection...
594 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700595 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700596 network_thread()->Invoke<void>(RTC_FROM_HERE,
597 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598}
599
600bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000601 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700602 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200603 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800604 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100605 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800606 RTC_DCHECK(observer != nullptr);
607 if (!observer) {
608 return false;
609 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000610 observer_ = observer;
611
kwiberg0eb15ed2015-12-17 03:04:15 -0800612 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800613
deadbeef91dd5672016-05-18 16:55:30 -0700614 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700615 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700616 if (!network_thread()->Invoke<bool>(
617 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
618 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619 return false;
620 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621
nissec36b31b2016-04-11 23:25:29 -0700622 media_controller_.reset(
623 factory_->CreateMediaController(configuration.media_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624
zhihuang29ff8442016-07-27 11:07:25 -0700625 session_.reset(new WebRtcSession(
626 media_controller_.get(), factory_->network_thread(),
627 factory_->worker_thread(), factory_->signaling_thread(),
628 port_allocator_.get(),
629 std::unique_ptr<cricket::TransportController>(
630 factory_->CreateTransportController(port_allocator_.get()))));
631
deadbeefab9b2d12015-10-14 11:33:11 -0700632 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000633
634 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200635 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800636 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000637 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700638 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000639
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 // Register PeerConnection as receiver of local ice candidates.
641 // All the callbacks will be posted to the application from PeerConnection.
642 session_->RegisterIceObserver(this);
643 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700644 session_->SignalVoiceChannelCreated.connect(
645 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700646 session_->SignalVoiceChannelDestroyed.connect(
647 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700648 session_->SignalVideoChannelCreated.connect(
649 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700650 session_->SignalVideoChannelDestroyed.connect(
651 this, &PeerConnection::OnVideoChannelDestroyed);
652 session_->SignalDataChannelCreated.connect(
653 this, &PeerConnection::OnDataChannelCreated);
654 session_->SignalDataChannelDestroyed.connect(
655 this, &PeerConnection::OnDataChannelDestroyed);
656 session_->SignalDataChannelOpenMessage.connect(
657 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 return true;
659}
660
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000661rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700663 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664}
665
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000666rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700668 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669}
670
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000671bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100672 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 if (IsClosed()) {
674 return false;
675 }
deadbeefab9b2d12015-10-14 11:33:11 -0700676 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677 return false;
678 }
deadbeefab9b2d12015-10-14 11:33:11 -0700679
680 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800681 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
682 observer->SignalAudioTrackAdded.connect(this,
683 &PeerConnection::OnAudioTrackAdded);
684 observer->SignalAudioTrackRemoved.connect(
685 this, &PeerConnection::OnAudioTrackRemoved);
686 observer->SignalVideoTrackAdded.connect(this,
687 &PeerConnection::OnVideoTrackAdded);
688 observer->SignalVideoTrackRemoved.connect(
689 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700690 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700691
deadbeefab9b2d12015-10-14 11:33:11 -0700692 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800693 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700694 }
695 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800696 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700697 }
698
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000699 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 observer_->OnRenegotiationNeeded();
701 return true;
702}
703
704void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100705 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700706 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800707 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700708 }
709 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800710 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700711 }
712
713 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800714 stream_observers_.erase(
715 std::remove_if(
716 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700717 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800718 return observer->stream()->label().compare(local_stream->label()) ==
719 0;
720 }),
721 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700722
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 if (IsClosed()) {
724 return;
725 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 observer_->OnRenegotiationNeeded();
727}
728
deadbeefe1f9d832016-01-14 15:35:42 -0800729rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
730 MediaStreamTrackInterface* track,
731 std::vector<MediaStreamInterface*> streams) {
732 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
733 if (IsClosed()) {
734 return nullptr;
735 }
736 if (streams.size() >= 2) {
737 LOG(LS_ERROR)
738 << "Adding a track with two streams is not currently supported.";
739 return nullptr;
740 }
741 // TODO(deadbeef): Support adding a track to two different senders.
742 if (FindSenderForTrack(track) != senders_.end()) {
743 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
744 return nullptr;
745 }
746
747 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700748 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800749 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700750 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800751 signaling_thread(),
752 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700753 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800754 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700755 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800756 }
757 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700758 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800759 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700760 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800761 }
762 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700763 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800764 signaling_thread(),
765 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700766 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800767 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700768 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800769 }
770 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700771 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800772 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700773 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800774 }
775 } else {
776 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
777 return rtc::scoped_refptr<RtpSenderInterface>();
778 }
779
780 senders_.push_back(new_sender);
781 observer_->OnRenegotiationNeeded();
782 return new_sender;
783}
784
785bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
786 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
787 if (IsClosed()) {
788 return false;
789 }
790
791 auto it = std::find(senders_.begin(), senders_.end(), sender);
792 if (it == senders_.end()) {
793 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
794 return false;
795 }
deadbeefa601f5c2016-06-06 14:27:39 -0700796 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800797 senders_.erase(it);
798
799 observer_->OnRenegotiationNeeded();
800 return true;
801}
802
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000803rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100805 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700806 if (IsClosed()) {
807 return nullptr;
808 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809 if (!track) {
810 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
811 return NULL;
812 }
deadbeefab9b2d12015-10-14 11:33:11 -0700813 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
815 return NULL;
816 }
817
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000818 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 DtmfSender::Create(track, signaling_thread(), session_.get()));
820 if (!sender.get()) {
821 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
822 return NULL;
823 }
824 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
825}
826
deadbeeffac06552015-11-25 11:26:01 -0800827rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800828 const std::string& kind,
829 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700831 if (IsClosed()) {
832 return nullptr;
833 }
deadbeefa601f5c2016-06-06 14:27:39 -0700834 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800835 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700836 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700837 signaling_thread(),
838 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800839 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700840 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700841 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800842 } else {
843 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800844 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800845 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800846 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700847 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800848 }
deadbeeffac06552015-11-25 11:26:01 -0800849 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800850 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800851}
852
deadbeef70ab1a12015-09-28 16:53:55 -0700853std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
854 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700855 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
856 for (const auto& sender : senders_) {
857 ret.push_back(sender.get());
858 }
859 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700860}
861
862std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
863PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700864 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
865 for (const auto& receiver : receivers_) {
866 ret.push_back(receiver.get());
867 }
868 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700869}
870
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000872 MediaStreamTrackInterface* track,
873 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100874 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700875 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876 if (!VERIFY(observer != NULL)) {
877 LOG(LS_ERROR) << "GetStats - observer is NULL.";
878 return false;
879 }
880
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000881 stats_->UpdateStats(level);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700882 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000883 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884 return true;
885}
886
887PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
888 return signaling_state_;
889}
890
891PeerConnectionInterface::IceState PeerConnection::ice_state() {
892 return ice_state_;
893}
894
895PeerConnectionInterface::IceConnectionState
896PeerConnection::ice_connection_state() {
897 return ice_connection_state_;
898}
899
900PeerConnectionInterface::IceGatheringState
901PeerConnection::ice_gathering_state() {
902 return ice_gathering_state_;
903}
904
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000905rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906PeerConnection::CreateDataChannel(
907 const std::string& label,
908 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100909 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700910 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000911
kwibergd1fe2812016-04-27 06:47:29 -0700912 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000913 if (config) {
914 internal_config.reset(new InternalDataChannelInit(*config));
915 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000916 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700917 InternalCreateDataChannel(label, internal_config.get()));
918 if (!channel.get()) {
919 return nullptr;
920 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000922 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
923 // the first SCTP DataChannel.
924 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
925 observer_->OnRenegotiationNeeded();
926 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000927
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928 return DataChannelProxy::Create(signaling_thread(), channel.get());
929}
930
931void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
932 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100933 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700934 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
936 return;
937 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000938 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000939
940 bool value;
941 size_t mandatory_constraints = 0;
942
943 if (FindConstraint(constraints,
944 MediaConstraintsInterface::kOfferToReceiveAudio,
945 &value,
946 &mandatory_constraints)) {
947 options.offer_to_receive_audio =
948 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
949 }
950
951 if (FindConstraint(constraints,
952 MediaConstraintsInterface::kOfferToReceiveVideo,
953 &value,
954 &mandatory_constraints)) {
955 options.offer_to_receive_video =
956 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
957 }
958
959 if (FindConstraint(constraints,
960 MediaConstraintsInterface::kVoiceActivityDetection,
961 &value,
962 &mandatory_constraints)) {
963 options.voice_activity_detection = value;
964 }
965
966 if (FindConstraint(constraints,
967 MediaConstraintsInterface::kIceRestart,
968 &value,
969 &mandatory_constraints)) {
970 options.ice_restart = value;
971 }
972
973 if (FindConstraint(constraints,
974 MediaConstraintsInterface::kUseRtpMux,
975 &value,
976 &mandatory_constraints)) {
977 options.use_rtp_mux = value;
978 }
979
980 CreateOffer(observer, options);
981}
982
983void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
984 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100985 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700986 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000987 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
988 return;
989 }
deadbeefab9b2d12015-10-14 11:33:11 -0700990
991 cricket::MediaSessionOptions session_options;
992 if (!GetOptionsForOffer(options, &session_options)) {
993 std::string error = "CreateOffer called with invalid options.";
994 LOG(LS_ERROR) << error;
995 PostCreateSessionDescriptionFailure(observer, error);
996 return;
997 }
998
999 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000}
1001
1002void PeerConnection::CreateAnswer(
1003 CreateSessionDescriptionObserver* observer,
1004 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001005 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001006 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1008 return;
1009 }
deadbeefab9b2d12015-10-14 11:33:11 -07001010
1011 cricket::MediaSessionOptions session_options;
1012 if (!GetOptionsForAnswer(constraints, &session_options)) {
1013 std::string error = "CreateAnswer called with invalid constraints.";
1014 LOG(LS_ERROR) << error;
1015 PostCreateSessionDescriptionFailure(observer, error);
1016 return;
1017 }
1018
htaa2a49d92016-03-04 02:51:39 -08001019 session_->CreateAnswer(observer, session_options);
1020}
1021
1022void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1023 const RTCOfferAnswerOptions& options) {
1024 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1025 if (!VERIFY(observer != nullptr)) {
1026 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1027 return;
1028 }
1029
1030 cricket::MediaSessionOptions session_options;
1031 if (!GetOptionsForAnswer(options, &session_options)) {
1032 std::string error = "CreateAnswer called with invalid options.";
1033 LOG(LS_ERROR) << error;
1034 PostCreateSessionDescriptionFailure(observer, error);
1035 return;
1036 }
1037
1038 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039}
1040
1041void PeerConnection::SetLocalDescription(
1042 SetSessionDescriptionObserver* observer,
1043 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001044 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001045 if (IsClosed()) {
1046 return;
1047 }
deadbeefab9b2d12015-10-14 11:33:11 -07001048 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1050 return;
1051 }
1052 if (!desc) {
1053 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1054 return;
1055 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 // Update stats here so that we have the most recent stats for tracks and
1057 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001058 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059 std::string error;
1060 if (!session_->SetLocalDescription(desc, &error)) {
1061 PostSetSessionDescriptionFailure(observer, error);
1062 return;
1063 }
deadbeefab9b2d12015-10-14 11:33:11 -07001064
1065 // If setting the description decided our SSL role, allocate any necessary
1066 // SCTP sids.
1067 rtc::SSLRole role;
1068 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001069 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001070 AllocateSctpSids(role);
1071 }
1072
1073 // Update state and SSRC of local MediaStreams and DataChannels based on the
1074 // local session description.
1075 const cricket::ContentInfo* audio_content =
1076 GetFirstAudioContent(desc->description());
1077 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001078 if (audio_content->rejected) {
1079 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1080 } else {
1081 const cricket::AudioContentDescription* audio_desc =
1082 static_cast<const cricket::AudioContentDescription*>(
1083 audio_content->description);
1084 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1085 }
deadbeefab9b2d12015-10-14 11:33:11 -07001086 }
1087
1088 const cricket::ContentInfo* video_content =
1089 GetFirstVideoContent(desc->description());
1090 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001091 if (video_content->rejected) {
1092 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1093 } else {
1094 const cricket::VideoContentDescription* video_desc =
1095 static_cast<const cricket::VideoContentDescription*>(
1096 video_content->description);
1097 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1098 }
deadbeefab9b2d12015-10-14 11:33:11 -07001099 }
1100
1101 const cricket::ContentInfo* data_content =
1102 GetFirstDataContent(desc->description());
1103 if (data_content) {
1104 const cricket::DataContentDescription* data_desc =
1105 static_cast<const cricket::DataContentDescription*>(
1106 data_content->description);
1107 if (rtc::starts_with(data_desc->protocol().data(),
1108 cricket::kMediaProtocolRtpPrefix)) {
1109 UpdateLocalRtpDataChannels(data_desc->streams());
1110 }
1111 }
1112
1113 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001114 signaling_thread()->Post(RTC_FROM_HERE, this,
1115 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001116
deadbeefcbecd352015-09-23 11:50:27 -07001117 // MaybeStartGathering needs to be called after posting
1118 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1119 // before signaling that SetLocalDescription completed.
1120 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001121}
1122
1123void PeerConnection::SetRemoteDescription(
1124 SetSessionDescriptionObserver* observer,
1125 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001126 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001127 if (IsClosed()) {
1128 return;
1129 }
deadbeefab9b2d12015-10-14 11:33:11 -07001130 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001131 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1132 return;
1133 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001134 if (!desc) {
1135 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1136 return;
1137 }
1138 // Update stats here so that we have the most recent stats for tracks and
1139 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001140 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001141 std::string error;
1142 if (!session_->SetRemoteDescription(desc, &error)) {
1143 PostSetSessionDescriptionFailure(observer, error);
1144 return;
1145 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146
deadbeefab9b2d12015-10-14 11:33:11 -07001147 // If setting the description decided our SSL role, allocate any necessary
1148 // SCTP sids.
1149 rtc::SSLRole role;
1150 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001151 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001152 AllocateSctpSids(role);
1153 }
1154
1155 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001156 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1157 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1158 const cricket::AudioContentDescription* audio_desc =
1159 GetFirstAudioContentDescription(remote_desc);
1160 const cricket::VideoContentDescription* video_desc =
1161 GetFirstVideoContentDescription(remote_desc);
1162 const cricket::DataContentDescription* data_desc =
1163 GetFirstDataContentDescription(remote_desc);
1164
1165 // Check if the descriptions include streams, just in case the peer supports
1166 // MSID, but doesn't indicate so with "a=msid-semantic".
1167 if (remote_desc->msid_supported() ||
1168 (audio_desc && !audio_desc->streams().empty()) ||
1169 (video_desc && !video_desc->streams().empty())) {
1170 remote_peer_supports_msid_ = true;
1171 }
deadbeefab9b2d12015-10-14 11:33:11 -07001172
1173 // We wait to signal new streams until we finish processing the description,
1174 // since only at that point will new streams have all their tracks.
1175 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1176
1177 // Find all audio rtp streams and create corresponding remote AudioTracks
1178 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001179 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001180 if (audio_content->rejected) {
1181 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1182 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001183 bool default_audio_track_needed =
1184 !remote_peer_supports_msid_ &&
1185 MediaContentDirectionHasSend(audio_desc->direction());
1186 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1187 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001188 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001189 }
deadbeefab9b2d12015-10-14 11:33:11 -07001190 }
1191
1192 // Find all video rtp streams and create corresponding remote VideoTracks
1193 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001194 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001195 if (video_content->rejected) {
1196 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1197 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001198 bool default_video_track_needed =
1199 !remote_peer_supports_msid_ &&
1200 MediaContentDirectionHasSend(video_desc->direction());
1201 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1202 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001203 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001204 }
deadbeefab9b2d12015-10-14 11:33:11 -07001205 }
1206
1207 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001208 if (data_desc) {
1209 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001210 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001211 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001212 }
1213 }
1214
1215 // Iterate new_streams and notify the observer about new MediaStreams.
1216 for (size_t i = 0; i < new_streams->count(); ++i) {
1217 MediaStreamInterface* new_stream = new_streams->at(i);
1218 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001219 // Call both the raw pointer and scoped_refptr versions of the method
1220 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001221 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001222 observer_->OnAddStream(
1223 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001224 }
1225
deadbeefbda7e0b2015-12-08 17:13:40 -08001226 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001227
1228 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001229 signaling_thread()->Post(RTC_FROM_HERE, this,
1230 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001231}
1232
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001233bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001234 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001235 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001236 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001237 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001238 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001239 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001240 return false;
1241 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001242 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001243
1244 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1245 session_->SetIceConfig(session_->ParseIceConfig(configuration));
1246 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001247}
1248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001249bool PeerConnection::AddIceCandidate(
1250 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001251 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001252 if (IsClosed()) {
1253 return false;
1254 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001255 return session_->ProcessIceMessage(ice_candidate);
1256}
1257
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001258bool PeerConnection::RemoveIceCandidates(
1259 const std::vector<cricket::Candidate>& candidates) {
1260 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1261 return session_->RemoveRemoteIceCandidates(candidates);
1262}
1263
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001264void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001265 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001266 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001267
1268 if (session_) {
1269 session_->set_metrics_observer(uma_observer_);
1270 }
1271
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001272 // Send information about IPv4/IPv6 status.
1273 if (uma_observer_ && port_allocator_) {
1274 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001275 uma_observer_->IncrementEnumCounter(
1276 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1277 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001278 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001279 uma_observer_->IncrementEnumCounter(
1280 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1281 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001282 }
1283 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001284}
1285
ivoc14d5dbe2016-07-04 07:06:55 -07001286bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1287 int64_t max_size_bytes) {
1288 return factory_->worker_thread()->Invoke<bool>(
1289 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1290 max_size_bytes));
1291}
1292
1293void PeerConnection::StopRtcEventLog() {
1294 factory_->worker_thread()->Invoke<void>(
1295 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1296}
1297
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298const SessionDescriptionInterface* PeerConnection::local_description() const {
1299 return session_->local_description();
1300}
1301
1302const SessionDescriptionInterface* PeerConnection::remote_description() const {
1303 return session_->remote_description();
1304}
1305
1306void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001307 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 // Update stats here so that we have the most recent stats for tracks and
1309 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001310 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311
deadbeefd59daf82015-10-14 15:02:44 -07001312 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313}
1314
deadbeefd59daf82015-10-14 15:02:44 -07001315void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1316 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001318 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001320 break;
deadbeefd59daf82015-10-14 15:02:44 -07001321 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1323 break;
deadbeefd59daf82015-10-14 15:02:44 -07001324 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1326 break;
deadbeefd59daf82015-10-14 15:02:44 -07001327 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1329 break;
deadbeefd59daf82015-10-14 15:02:44 -07001330 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001331 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1332 break;
deadbeefd59daf82015-10-14 15:02:44 -07001333 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 ChangeSignalingState(PeerConnectionInterface::kStable);
1335 break;
deadbeefd59daf82015-10-14 15:02:44 -07001336 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 ChangeSignalingState(PeerConnectionInterface::kClosed);
1338 break;
1339 default:
1340 break;
1341 }
1342}
1343
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001344void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1347 SetSessionDescriptionMsg* param =
1348 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1349 param->observer->OnSuccess();
1350 delete param;
1351 break;
1352 }
1353 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1354 SetSessionDescriptionMsg* param =
1355 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1356 param->observer->OnFailure(param->error);
1357 delete param;
1358 break;
1359 }
deadbeefab9b2d12015-10-14 11:33:11 -07001360 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1361 CreateSessionDescriptionMsg* param =
1362 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1363 param->observer->OnFailure(param->error);
1364 delete param;
1365 break;
1366 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367 case MSG_GETSTATS: {
1368 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001369 StatsReports reports;
1370 stats_->GetStats(param->track, &reports);
1371 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 delete param;
1373 break;
1374 }
deadbeefbd292462015-12-14 18:15:29 -08001375 case MSG_FREE_DATACHANNELS: {
1376 sctp_data_channels_to_free_.clear();
1377 break;
1378 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001380 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381 break;
1382 }
1383}
1384
deadbeefab9b2d12015-10-14 11:33:11 -07001385void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001386 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001387 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001388 receivers_.push_back(
1389 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001390 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
1391 session_->voice_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392}
1393
deadbeefab9b2d12015-10-14 11:33:11 -07001394void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001395 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001396 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001397 receivers_.push_back(
1398 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1399 signaling_thread(),
1400 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001401 ssrc, session_->video_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402}
1403
deadbeef70ab1a12015-09-28 16:53:55 -07001404// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1405// description.
perkjd61bf802016-03-24 03:16:19 -07001406void PeerConnection::DestroyReceiver(const std::string& track_id) {
1407 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001408 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001409 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001410 << " doesn't exist.";
1411 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001412 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001413 receivers_.erase(it);
1414 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415}
1416
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001417void PeerConnection::OnIceConnectionChange(
1418 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001419 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001420 // After transitioning to "closed", ignore any additional states from
1421 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001422 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001423 return;
1424 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001426 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427}
1428
1429void PeerConnection::OnIceGatheringChange(
1430 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001431 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 if (IsClosed()) {
1433 return;
1434 }
1435 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001436 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437}
1438
1439void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001440 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001441 if (IsClosed()) {
1442 return;
1443 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001444 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445}
1446
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001447void PeerConnection::OnIceCandidatesRemoved(
1448 const std::vector<cricket::Candidate>& candidates) {
1449 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001450 if (IsClosed()) {
1451 return;
1452 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001453 observer_->OnIceCandidatesRemoved(candidates);
1454}
1455
Peter Thatcher54360512015-07-08 11:08:35 -07001456void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001457 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001458 if (IsClosed()) {
1459 return;
1460 }
Peter Thatcher54360512015-07-08 11:08:35 -07001461 observer_->OnIceConnectionReceivingChange(receiving);
1462}
1463
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464void PeerConnection::ChangeSignalingState(
1465 PeerConnectionInterface::SignalingState signaling_state) {
1466 signaling_state_ = signaling_state;
1467 if (signaling_state == kClosed) {
1468 ice_connection_state_ = kIceConnectionClosed;
1469 observer_->OnIceConnectionChange(ice_connection_state_);
1470 if (ice_gathering_state_ != kIceGatheringComplete) {
1471 ice_gathering_state_ = kIceGatheringComplete;
1472 observer_->OnIceGatheringChange(ice_gathering_state_);
1473 }
1474 }
1475 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476}
1477
deadbeefeb459812015-12-15 19:24:43 -08001478void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1479 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001480 if (IsClosed()) {
1481 return;
1482 }
deadbeefeb459812015-12-15 19:24:43 -08001483 auto sender = FindSenderForTrack(track);
1484 if (sender != senders_.end()) {
1485 // We already have a sender for this track, so just change the stream_id
1486 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001487 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001488 return;
1489 }
1490
1491 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001492 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1493 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001494 signaling_thread(),
1495 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1496 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001497 senders_.push_back(new_sender);
1498 // If the sender has already been configured in SDP, we call SetSsrc,
1499 // which will connect the sender to the underlying transport. This can
1500 // occur if a local session description that contains the ID of the sender
1501 // is set before AddStream is called. It can also occur if the local
1502 // session description is not changed and RemoveStream is called, and
1503 // later AddStream is called again with the same stream.
1504 const TrackInfo* track_info =
1505 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1506 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001507 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001508 }
1509}
1510
1511// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1512// indefinitely, when we have unified plan SDP.
1513void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1514 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001515 if (IsClosed()) {
1516 return;
1517 }
deadbeefeb459812015-12-15 19:24:43 -08001518 auto sender = FindSenderForTrack(track);
1519 if (sender == senders_.end()) {
1520 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1521 << " doesn't exist.";
1522 return;
1523 }
deadbeefa601f5c2016-06-06 14:27:39 -07001524 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001525 senders_.erase(sender);
1526}
1527
1528void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1529 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001530 if (IsClosed()) {
1531 return;
1532 }
deadbeefeb459812015-12-15 19:24:43 -08001533 auto sender = FindSenderForTrack(track);
1534 if (sender != senders_.end()) {
1535 // We already have a sender for this track, so just change the stream_id
1536 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001537 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001538 return;
1539 }
1540
1541 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001542 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1543 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001544 signaling_thread(), new VideoRtpSender(track, stream->label(),
1545 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001546 senders_.push_back(new_sender);
1547 const TrackInfo* track_info =
1548 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1549 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001550 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001551 }
1552}
1553
1554void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1555 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001556 if (IsClosed()) {
1557 return;
1558 }
deadbeefeb459812015-12-15 19:24:43 -08001559 auto sender = FindSenderForTrack(track);
1560 if (sender == senders_.end()) {
1561 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1562 << " doesn't exist.";
1563 return;
1564 }
deadbeefa601f5c2016-06-06 14:27:39 -07001565 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001566 senders_.erase(sender);
1567}
1568
deadbeefab9b2d12015-10-14 11:33:11 -07001569void PeerConnection::PostSetSessionDescriptionFailure(
1570 SetSessionDescriptionObserver* observer,
1571 const std::string& error) {
1572 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1573 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001574 signaling_thread()->Post(RTC_FROM_HERE, this,
1575 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001576}
1577
1578void PeerConnection::PostCreateSessionDescriptionFailure(
1579 CreateSessionDescriptionObserver* observer,
1580 const std::string& error) {
1581 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1582 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001583 signaling_thread()->Post(RTC_FROM_HERE, this,
1584 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001585}
1586
1587bool PeerConnection::GetOptionsForOffer(
1588 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1589 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001590 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1591 // ContentInfos.
1592 if (session_->local_description()) {
1593 for (const cricket::ContentInfo& content :
1594 session_->local_description()->description()->contents()) {
1595 session_options->transport_options[content.name] =
1596 cricket::TransportOptions();
1597 }
1598 }
htaaac2dea2016-03-10 13:35:55 -08001599 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001600 return false;
1601 }
1602
deadbeeffac06552015-11-25 11:26:01 -08001603 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001604 // Offer to receive audio/video if the constraint is not set and there are
1605 // send streams, or we're currently receiving.
1606 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1607 session_options->recv_audio =
1608 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1609 !remote_audio_tracks_.empty();
1610 }
1611 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1612 session_options->recv_video =
1613 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1614 !remote_video_tracks_.empty();
1615 }
1616 session_options->bundle_enabled =
1617 session_options->bundle_enabled &&
1618 (session_options->has_audio() || session_options->has_video() ||
1619 session_options->has_data());
1620
deadbeefab9b2d12015-10-14 11:33:11 -07001621 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1622 session_options->data_channel_type = cricket::DCT_SCTP;
1623 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001624
1625 session_options->rtcp_cname = rtcp_cname_;
deadbeefab9b2d12015-10-14 11:33:11 -07001626 return true;
1627}
1628
htaa2a49d92016-03-04 02:51:39 -08001629void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001630 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001631 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1632 // ContentInfos.
1633 if (session_->remote_description()) {
1634 // Initialize the transport_options map.
1635 for (const cricket::ContentInfo& content :
1636 session_->remote_description()->description()->contents()) {
1637 session_options->transport_options[content.name] =
1638 cricket::TransportOptions();
1639 }
1640 }
deadbeeffac06552015-11-25 11:26:01 -08001641 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001642 session_options->bundle_enabled =
1643 session_options->bundle_enabled &&
1644 (session_options->has_audio() || session_options->has_video() ||
1645 session_options->has_data());
1646
deadbeefab9b2d12015-10-14 11:33:11 -07001647 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1648 // are not signaled in the SDP so does not go through that path and must be
1649 // handled here.
1650 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1651 session_options->data_channel_type = cricket::DCT_SCTP;
1652 }
htaa2a49d92016-03-04 02:51:39 -08001653}
1654
1655bool PeerConnection::GetOptionsForAnswer(
1656 const MediaConstraintsInterface* constraints,
1657 cricket::MediaSessionOptions* session_options) {
1658 session_options->recv_audio = false;
1659 session_options->recv_video = false;
1660 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1661 return false;
1662 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001663 session_options->rtcp_cname = rtcp_cname_;
1664
htaa2a49d92016-03-04 02:51:39 -08001665 FinishOptionsForAnswer(session_options);
1666 return true;
1667}
1668
1669bool PeerConnection::GetOptionsForAnswer(
1670 const RTCOfferAnswerOptions& options,
1671 cricket::MediaSessionOptions* session_options) {
1672 session_options->recv_audio = false;
1673 session_options->recv_video = false;
htaaac2dea2016-03-10 13:35:55 -08001674 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001675 return false;
1676 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001677 session_options->rtcp_cname = rtcp_cname_;
1678
htaa2a49d92016-03-04 02:51:39 -08001679 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001680 return true;
1681}
1682
deadbeeffaac4972015-11-12 15:33:07 -08001683void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1684 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001685 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1686 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001687}
1688
deadbeefab9b2d12015-10-14 11:33:11 -07001689void PeerConnection::UpdateRemoteStreamsList(
1690 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001691 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001692 cricket::MediaType media_type,
1693 StreamCollection* new_streams) {
1694 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1695
1696 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001697 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001698 auto track_it = current_tracks->begin();
1699 while (track_it != current_tracks->end()) {
1700 const TrackInfo& info = *track_it;
1701 const cricket::StreamParams* params =
1702 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001703 bool track_exists = params && params->id == info.track_id;
1704 // If this is a default track, and we still need it, don't remove it.
1705 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1706 track_exists) {
1707 ++track_it;
1708 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001709 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1710 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001711 }
1712 }
1713
1714 // Find new and active tracks.
1715 for (const cricket::StreamParams& params : streams) {
1716 // The sync_label is the MediaStream label and the |stream.id| is the
1717 // track id.
1718 const std::string& stream_label = params.sync_label;
1719 const std::string& track_id = params.id;
1720 uint32_t ssrc = params.first_ssrc();
1721
1722 rtc::scoped_refptr<MediaStreamInterface> stream =
1723 remote_streams_->find(stream_label);
1724 if (!stream) {
1725 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001726 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1727 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001728 remote_streams_->AddStream(stream);
1729 new_streams->AddStream(stream);
1730 }
1731
1732 const TrackInfo* track_info =
1733 FindTrackInfo(*current_tracks, stream_label, track_id);
1734 if (!track_info) {
1735 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1736 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1737 }
1738 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001739
1740 // Add default track if necessary.
1741 if (default_track_needed) {
1742 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1743 remote_streams_->find(kDefaultStreamLabel);
1744 if (!default_stream) {
1745 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001746 default_stream = MediaStreamProxy::Create(
1747 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001748 remote_streams_->AddStream(default_stream);
1749 new_streams->AddStream(default_stream);
1750 }
1751 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1752 ? kDefaultAudioTrackLabel
1753 : kDefaultVideoTrackLabel;
1754 const TrackInfo* default_track_info =
1755 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1756 if (!default_track_info) {
1757 current_tracks->push_back(
1758 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1759 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1760 }
1761 }
deadbeefab9b2d12015-10-14 11:33:11 -07001762}
1763
1764void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1765 const std::string& track_id,
1766 uint32_t ssrc,
1767 cricket::MediaType media_type) {
1768 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1769
1770 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001771 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001772 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001773 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001774 } else {
1775 RTC_DCHECK(false && "Invalid media type");
1776 }
1777}
1778
1779void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1780 const std::string& track_id,
1781 cricket::MediaType media_type) {
1782 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1783
1784 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001785 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1786 // will be notified which will end the AudioRtpReceiver::track().
1787 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001788 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1789 stream->FindAudioTrack(track_id);
1790 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001791 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001792 }
1793 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001794 // Stopping or destroying a VideoRtpReceiver will end the
1795 // VideoRtpReceiver::track().
1796 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001797 rtc::scoped_refptr<VideoTrackInterface> video_track =
1798 stream->FindVideoTrack(track_id);
1799 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001800 // There's no guarantee the track is still available, e.g. the track may
1801 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001802 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001803 }
1804 } else {
1805 ASSERT(false && "Invalid media type");
1806 }
1807}
1808
1809void PeerConnection::UpdateEndedRemoteMediaStreams() {
1810 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1811 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1812 MediaStreamInterface* stream = remote_streams_->at(i);
1813 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1814 streams_to_remove.push_back(stream);
1815 }
1816 }
1817
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001818 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001819 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001820 // Call both the raw pointer and scoped_refptr versions of the method
1821 // for compatibility.
1822 observer_->OnRemoveStream(stream.get());
1823 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001824 }
1825}
1826
deadbeefab9b2d12015-10-14 11:33:11 -07001827void PeerConnection::UpdateLocalTracks(
1828 const std::vector<cricket::StreamParams>& streams,
1829 cricket::MediaType media_type) {
1830 TrackInfos* current_tracks = GetLocalTracks(media_type);
1831
1832 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1833 // don't match the new StreamParam.
1834 TrackInfos::iterator track_it = current_tracks->begin();
1835 while (track_it != current_tracks->end()) {
1836 const TrackInfo& info = *track_it;
1837 const cricket::StreamParams* params =
1838 cricket::GetStreamBySsrc(streams, info.ssrc);
1839 if (!params || params->id != info.track_id ||
1840 params->sync_label != info.stream_label) {
1841 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1842 media_type);
1843 track_it = current_tracks->erase(track_it);
1844 } else {
1845 ++track_it;
1846 }
1847 }
1848
1849 // Find new and active tracks.
1850 for (const cricket::StreamParams& params : streams) {
1851 // The sync_label is the MediaStream label and the |stream.id| is the
1852 // track id.
1853 const std::string& stream_label = params.sync_label;
1854 const std::string& track_id = params.id;
1855 uint32_t ssrc = params.first_ssrc();
1856 const TrackInfo* track_info =
1857 FindTrackInfo(*current_tracks, stream_label, track_id);
1858 if (!track_info) {
1859 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1860 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1861 }
1862 }
1863}
1864
1865void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1866 const std::string& track_id,
1867 uint32_t ssrc,
1868 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001869 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001870 if (!sender) {
1871 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1872 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001873 return;
1874 }
1875
deadbeeffac06552015-11-25 11:26:01 -08001876 if (sender->media_type() != media_type) {
1877 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1878 << " description with an unexpected media type.";
1879 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001880 }
deadbeeffac06552015-11-25 11:26:01 -08001881
1882 sender->set_stream_id(stream_label);
1883 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001884}
1885
1886void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1887 const std::string& track_id,
1888 uint32_t ssrc,
1889 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001890 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001891 if (!sender) {
1892 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001893 // SessionDescriptions has been renegotiated.
1894 return;
1895 }
deadbeeffac06552015-11-25 11:26:01 -08001896
1897 // A sender has been removed from the SessionDescription but it's still
1898 // associated with the PeerConnection. This only occurs if the SDP doesn't
1899 // match with the calls to CreateSender, AddStream and RemoveStream.
1900 if (sender->media_type() != media_type) {
1901 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1902 << " description with an unexpected media type.";
1903 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001904 }
deadbeeffac06552015-11-25 11:26:01 -08001905
1906 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001907}
1908
1909void PeerConnection::UpdateLocalRtpDataChannels(
1910 const cricket::StreamParamsVec& streams) {
1911 std::vector<std::string> existing_channels;
1912
1913 // Find new and active data channels.
1914 for (const cricket::StreamParams& params : streams) {
1915 // |it->sync_label| is actually the data channel label. The reason is that
1916 // we use the same naming of data channels as we do for
1917 // MediaStreams and Tracks.
1918 // For MediaStreams, the sync_label is the MediaStream label and the
1919 // track label is the same as |streamid|.
1920 const std::string& channel_label = params.sync_label;
1921 auto data_channel_it = rtp_data_channels_.find(channel_label);
1922 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1923 continue;
1924 }
1925 // Set the SSRC the data channel should use for sending.
1926 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1927 existing_channels.push_back(data_channel_it->first);
1928 }
1929
1930 UpdateClosingRtpDataChannels(existing_channels, true);
1931}
1932
1933void PeerConnection::UpdateRemoteRtpDataChannels(
1934 const cricket::StreamParamsVec& streams) {
1935 std::vector<std::string> existing_channels;
1936
1937 // Find new and active data channels.
1938 for (const cricket::StreamParams& params : streams) {
1939 // The data channel label is either the mslabel or the SSRC if the mslabel
1940 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1941 std::string label = params.sync_label.empty()
1942 ? rtc::ToString(params.first_ssrc())
1943 : params.sync_label;
1944 auto data_channel_it = rtp_data_channels_.find(label);
1945 if (data_channel_it == rtp_data_channels_.end()) {
1946 // This is a new data channel.
1947 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1948 } else {
1949 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1950 }
1951 existing_channels.push_back(label);
1952 }
1953
1954 UpdateClosingRtpDataChannels(existing_channels, false);
1955}
1956
1957void PeerConnection::UpdateClosingRtpDataChannels(
1958 const std::vector<std::string>& active_channels,
1959 bool is_local_update) {
1960 auto it = rtp_data_channels_.begin();
1961 while (it != rtp_data_channels_.end()) {
1962 DataChannel* data_channel = it->second;
1963 if (std::find(active_channels.begin(), active_channels.end(),
1964 data_channel->label()) != active_channels.end()) {
1965 ++it;
1966 continue;
1967 }
1968
1969 if (is_local_update) {
1970 data_channel->SetSendSsrc(0);
1971 } else {
1972 data_channel->RemotePeerRequestClose();
1973 }
1974
1975 if (data_channel->state() == DataChannel::kClosed) {
1976 rtp_data_channels_.erase(it);
1977 it = rtp_data_channels_.begin();
1978 } else {
1979 ++it;
1980 }
1981 }
1982}
1983
1984void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1985 uint32_t remote_ssrc) {
1986 rtc::scoped_refptr<DataChannel> channel(
1987 InternalCreateDataChannel(label, nullptr));
1988 if (!channel.get()) {
1989 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1990 << "CreateDataChannel failed.";
1991 return;
1992 }
1993 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07001994 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
1995 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001996 // Call both the raw pointer and scoped_refptr versions of the method
1997 // for compatibility.
1998 observer_->OnDataChannel(proxy_channel.get());
1999 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002000}
2001
2002rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2003 const std::string& label,
2004 const InternalDataChannelInit* config) {
2005 if (IsClosed()) {
2006 return nullptr;
2007 }
2008 if (session_->data_channel_type() == cricket::DCT_NONE) {
2009 LOG(LS_ERROR)
2010 << "InternalCreateDataChannel: Data is not supported in this call.";
2011 return nullptr;
2012 }
2013 InternalDataChannelInit new_config =
2014 config ? (*config) : InternalDataChannelInit();
2015 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2016 if (new_config.id < 0) {
2017 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002018 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002019 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2020 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2021 return nullptr;
2022 }
2023 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2024 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2025 << "because the id is already in use or out of range.";
2026 return nullptr;
2027 }
2028 }
2029
2030 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2031 session_.get(), session_->data_channel_type(), label, new_config));
2032 if (!channel) {
2033 sid_allocator_.ReleaseSid(new_config.id);
2034 return nullptr;
2035 }
2036
2037 if (channel->data_channel_type() == cricket::DCT_RTP) {
2038 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2039 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2040 << " already exists.";
2041 return nullptr;
2042 }
2043 rtp_data_channels_[channel->label()] = channel;
2044 } else {
2045 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2046 sctp_data_channels_.push_back(channel);
2047 channel->SignalClosed.connect(this,
2048 &PeerConnection::OnSctpDataChannelClosed);
2049 }
2050
2051 return channel;
2052}
2053
2054bool PeerConnection::HasDataChannels() const {
2055 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2056}
2057
2058void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2059 for (const auto& channel : sctp_data_channels_) {
2060 if (channel->id() < 0) {
2061 int sid;
2062 if (!sid_allocator_.AllocateSid(role, &sid)) {
2063 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2064 continue;
2065 }
2066 channel->SetSctpSid(sid);
2067 }
2068 }
2069}
2070
2071void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002072 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002073 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2074 ++it) {
2075 if (it->get() == channel) {
2076 if (channel->id() >= 0) {
2077 sid_allocator_.ReleaseSid(channel->id());
2078 }
deadbeefbd292462015-12-14 18:15:29 -08002079 // Since this method is triggered by a signal from the DataChannel,
2080 // we can't free it directly here; we need to free it asynchronously.
2081 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002082 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002083 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2084 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002085 return;
2086 }
2087 }
2088}
2089
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002090void PeerConnection::OnVoiceChannelCreated() {
2091 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2092 session_->voice_channel(), senders_, receivers_,
2093 cricket::MEDIA_TYPE_AUDIO);
2094}
2095
deadbeefab9b2d12015-10-14 11:33:11 -07002096void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002097 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2098 cricket::VoiceChannel>(
2099 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2100}
2101
2102void PeerConnection::OnVideoChannelCreated() {
2103 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2104 session_->video_channel(), senders_, receivers_,
2105 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002106}
2107
2108void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002109 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2110 cricket::VideoChannel>(
2111 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002112}
2113
2114void PeerConnection::OnDataChannelCreated() {
2115 for (const auto& channel : sctp_data_channels_) {
2116 channel->OnTransportChannelCreated();
2117 }
2118}
2119
2120void PeerConnection::OnDataChannelDestroyed() {
2121 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2122 // DataChannel may callback to us and try to modify the list.
2123 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2124 temp_rtp_dcs.swap(rtp_data_channels_);
2125 for (const auto& kv : temp_rtp_dcs) {
2126 kv.second->OnTransportChannelDestroyed();
2127 }
2128
2129 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2130 temp_sctp_dcs.swap(sctp_data_channels_);
2131 for (const auto& channel : temp_sctp_dcs) {
2132 channel->OnTransportChannelDestroyed();
2133 }
2134}
2135
2136void PeerConnection::OnDataChannelOpenMessage(
2137 const std::string& label,
2138 const InternalDataChannelInit& config) {
2139 rtc::scoped_refptr<DataChannel> channel(
2140 InternalCreateDataChannel(label, &config));
2141 if (!channel.get()) {
2142 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2143 return;
2144 }
2145
deadbeefa601f5c2016-06-06 14:27:39 -07002146 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2147 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002148 // Call both the raw pointer and scoped_refptr versions of the method
2149 // for compatibility.
2150 observer_->OnDataChannel(proxy_channel.get());
2151 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002152}
2153
deadbeefa601f5c2016-06-06 14:27:39 -07002154RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2155 auto it = std::find_if(
2156 senders_.begin(), senders_.end(),
2157 [id](const rtc::scoped_refptr<
2158 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2159 return sender->id() == id;
2160 });
2161 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002162}
2163
deadbeefa601f5c2016-06-06 14:27:39 -07002164std::vector<
2165 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002166PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2167 return std::find_if(
2168 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002169 [track](const rtc::scoped_refptr<
2170 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002171 return sender->track() == track;
2172 });
2173}
2174
deadbeefa601f5c2016-06-06 14:27:39 -07002175std::vector<rtc::scoped_refptr<
2176 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002177PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002178 return std::find_if(
2179 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002180 [track_id](const rtc::scoped_refptr<
2181 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002182 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002183 });
2184}
2185
deadbeefab9b2d12015-10-14 11:33:11 -07002186PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2187 cricket::MediaType media_type) {
2188 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2189 media_type == cricket::MEDIA_TYPE_VIDEO);
2190 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2191 : &remote_video_tracks_;
2192}
2193
2194PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2195 cricket::MediaType media_type) {
2196 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2197 media_type == cricket::MEDIA_TYPE_VIDEO);
2198 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2199 : &local_video_tracks_;
2200}
2201
2202const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2203 const PeerConnection::TrackInfos& infos,
2204 const std::string& stream_label,
2205 const std::string track_id) const {
2206 for (const TrackInfo& track_info : infos) {
2207 if (track_info.stream_label == stream_label &&
2208 track_info.track_id == track_id) {
2209 return &track_info;
2210 }
2211 }
2212 return nullptr;
2213}
2214
2215DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2216 for (const auto& channel : sctp_data_channels_) {
2217 if (channel->id() == sid) {
2218 return channel;
2219 }
2220 }
2221 return nullptr;
2222}
2223
deadbeef91dd5672016-05-18 16:55:30 -07002224bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002225 const RTCConfiguration& configuration) {
2226 cricket::ServerAddresses stun_servers;
2227 std::vector<cricket::RelayServerConfig> turn_servers;
2228 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2229 return false;
2230 }
2231
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002232 port_allocator_->Initialize();
2233
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002234 // To handle both internal and externally created port allocator, we will
2235 // enable BUNDLE here.
2236 int portallocator_flags = port_allocator_->flags();
2237 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2238 cricket::PORTALLOCATOR_ENABLE_IPV6;
2239 // If the disable-IPv6 flag was specified, we'll not override it
2240 // by experiment.
2241 if (configuration.disable_ipv6) {
2242 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2243 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2244 "Disabled") {
2245 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2246 }
2247
2248 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2249 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2250 LOG(LS_INFO) << "TCP candidates are disabled.";
2251 }
2252
honghaiz60347052016-05-31 18:29:12 -07002253 if (configuration.candidate_network_policy ==
2254 kCandidateNetworkPolicyLowCost) {
2255 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2256 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2257 }
2258
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002259 port_allocator_->set_flags(portallocator_flags);
2260 // No step delay is used while allocating ports.
2261 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2262 port_allocator_->set_candidate_filter(
2263 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2264
2265 // Call this last since it may create pooled allocator sessions using the
2266 // properties set above.
2267 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002268 configuration.ice_candidate_pool_size,
2269 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002270 return true;
2271}
2272
deadbeef91dd5672016-05-18 16:55:30 -07002273bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002274 const RTCConfiguration& configuration) {
2275 cricket::ServerAddresses stun_servers;
2276 std::vector<cricket::RelayServerConfig> turn_servers;
2277 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2278 return false;
2279 }
2280 port_allocator_->set_candidate_filter(
2281 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2282 // Call this last since it may create pooled allocator sessions using the
2283 // candidate filter set above.
2284 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002285 configuration.ice_candidate_pool_size,
2286 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002287 return true;
2288}
2289
ivoc14d5dbe2016-07-04 07:06:55 -07002290bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2291 int64_t max_size_bytes) {
2292 return media_controller_->call_w()->StartEventLog(file, max_size_bytes);
2293}
2294
2295void PeerConnection::StopRtcEventLog_w() {
2296 media_controller_->call_w()->StopEventLog();
2297}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002298} // namespace webrtc