blob: 80c8a11a39572bc4a29a53d35ef742678b5255d8 [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"
ossuf515ab82016-12-07 04:52:58 -080039#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070040#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kjellandera96e2d72016-02-04 23:52:28 -080041#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010042#include "webrtc/pc/channelmanager.h"
skvlad11a9cbf2016-10-07 11:53:05 -070043#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010044#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045
46namespace {
47
deadbeefab9b2d12015-10-14 11:33:11 -070048using webrtc::DataChannel;
49using webrtc::MediaConstraintsInterface;
50using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070052using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080053using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070054using webrtc::RtpSenderProxy;
55using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070056using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
deadbeefab9b2d12015-10-14 11:33:11 -070058static const char kDefaultStreamLabel[] = "default";
59static const char kDefaultAudioTrackLabel[] = "defaulta0";
60static const char kDefaultVideoTrackLabel[] = "defaultv0";
61
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062// The min number of tokens must present in Turn host uri.
63// e.g. user@turn.example.org
64static const size_t kTurnHostTokensNum = 2;
65// Number of tokens must be preset when TURN uri has transport param.
66static const size_t kTurnTransportTokensNum = 2;
67// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000068static const int kDefaultStunPort = 3478;
69static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071
72// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070073static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
zhihuang8f65cdf2016-05-06 18:40:30 -070075// The length of RTCP CNAMEs.
76static const int kRtcpCnameLength = 16;
77
deadbeef0a6c4ca2015-10-06 11:38:28 -070078// NOTE: A loop below assumes that the first value of this enum is 0 and all
79// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070081 STUN = 0, // Indicates a STUN server.
82 STUNS, // Indicates a STUN server used with a TLS session.
83 TURN, // Indicates a TURN server
84 TURNS, // Indicates a TURN server used with a TLS session.
85 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086};
tfarina5237aaf2015-11-10 23:44:30 -080087static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070088 "kValidIceServiceTypes must have as many strings as ServiceType "
89 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
91enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000092 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070094 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080096 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097};
98
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000099struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 explicit SetSessionDescriptionMsg(
101 webrtc::SetSessionDescriptionObserver* observer)
102 : observer(observer) {
103 }
104
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000105 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 std::string error;
107};
108
deadbeefab9b2d12015-10-14 11:33:11 -0700109struct CreateSessionDescriptionMsg : public rtc::MessageData {
110 explicit CreateSessionDescriptionMsg(
111 webrtc::CreateSessionDescriptionObserver* observer)
112 : observer(observer) {}
113
114 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
115 std::string error;
116};
117
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000118struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000119 GetStatsMsg(webrtc::StatsObserver* observer,
120 webrtc::MediaStreamTrackInterface* track)
121 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000123 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000124 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125};
126
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000127// |in_str| should be of format
128// stunURI = scheme ":" stun-host [ ":" stun-port ]
129// scheme = "stun" / "stuns"
130// stun-host = IP-literal / IPv4address / reg-name
131// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700132//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000133// draft-petithuguenin-behave-turn-uris-01
134// turnURI = scheme ":" turn-host [ ":" turn-port ]
135// turn-host = username@IP-literal / IPv4address / reg-name
136bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
137 ServiceType* service_type,
138 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200139 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700140 if (colonpos == std::string::npos) {
141 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000142 return false;
143 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700144 if ((colonpos + 1) == in_str.length()) {
145 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
146 return false;
147 }
148 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800149 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700150 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000151 *service_type = static_cast<ServiceType>(i);
152 break;
153 }
154 }
155 if (*service_type == INVALID) {
156 return false;
157 }
158 *hostname = in_str.substr(colonpos + 1, std::string::npos);
159 return true;
160}
161
deadbeef0a6c4ca2015-10-06 11:38:28 -0700162bool ParsePort(const std::string& in_str, int* port) {
163 // Make sure port only contains digits. FromString doesn't check this.
164 for (const char& c : in_str) {
165 if (!std::isdigit(c)) {
166 return false;
167 }
168 }
169 return rtc::FromString(in_str, port);
170}
171
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000172// This method parses IPv6 and IPv4 literal strings, along with hostnames in
173// standard hostname:port format.
174// Consider following formats as correct.
175// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700176// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000177bool ParseHostnameAndPortFromString(const std::string& in_str,
178 std::string* host,
179 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700180 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000181 if (in_str.at(0) == '[') {
182 std::string::size_type closebracket = in_str.rfind(']');
183 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 std::string::size_type colonpos = in_str.find(':', closebracket);
185 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700186 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
187 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000188 return false;
189 }
190 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700191 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000192 } else {
193 return false;
194 }
195 } else {
196 std::string::size_type colonpos = in_str.find(':');
197 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700198 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000199 return false;
200 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 } else {
203 *host = in_str;
204 }
205 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700206 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000207}
208
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800209// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700210// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200211bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
212 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800213 cricket::ServerAddresses* stun_servers,
214 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 // draft-nandakumar-rtcweb-stun-uri-01
216 // stunURI = scheme ":" stun-host [ ":" stun-port ]
217 // scheme = "stun" / "stuns"
218 // stun-host = IP-literal / IPv4address / reg-name
219 // stun-port = *DIGIT
220
221 // draft-petithuguenin-behave-turn-uris-01
222 // turnURI = scheme ":" turn-host [ ":" turn-port ]
223 // [ "?transport=" transport ]
224 // scheme = "turn" / "turns"
225 // transport = "udp" / "tcp" / transport-ext
226 // transport-ext = 1*unreserved
227 // turn-host = IP-literal / IPv4address / reg-name
228 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800229 RTC_DCHECK(stun_servers != nullptr);
230 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200231 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800232 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700233 RTC_DCHECK(!url.empty());
hnslbd44bb02016-12-12 03:14:30 -0800234 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200235 std::string uri_without_transport = tokens[0];
236 // Let's look into transport= param, if it exists.
237 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
238 std::string uri_transport_param = tokens[1];
hnslbd44bb02016-12-12 03:14:30 -0800239 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
240 if (tokens[0] != kTransport) {
241 LOG(LS_WARNING) << "Invalid transport parameter key.";
242 return false;
243 }
244 if (tokens.size() < 2 ||
245 !cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
246 (turn_transport_type != cricket::PROTO_UDP &&
247 turn_transport_type != cricket::PROTO_TCP)) {
248 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
249 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200251 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000252
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200253 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700254 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200255 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
256 &service_type,
257 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700258 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
259 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000261
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
263 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200264
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200265 // Let's break hostname.
266 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700267 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
268
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200269 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270 if (tokens.size() > kTurnHostTokensNum) {
271 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
272 return false;
273 }
274 if (tokens.size() == kTurnHostTokensNum) {
275 if (tokens[0].empty() || tokens[1].empty()) {
276 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
277 return false;
278 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200279 username.assign(rtc::s_url_decode(tokens[0]));
280 hoststring = tokens[1];
281 } else {
282 hoststring = tokens[0];
283 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000284
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200285 int port = kDefaultStunPort;
286 if (service_type == TURNS) {
287 port = kDefaultStunTlsPort;
hnsl277b2502016-12-13 05:17:23 -0800288 turn_transport_type = cricket::PROTO_TLS;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200289 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000290
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200291 std::string address;
292 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700293 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
294 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200295 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000296
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 if (port <= 0 || port > 0xffff) {
298 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700299 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200300 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000301
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200302 switch (service_type) {
303 case STUN:
304 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800305 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200306 break;
307 case TURN:
308 case TURNS: {
hnslb0f04fd2016-12-19 04:10:30 -0800309 cricket::RelayServerConfig config = cricket::RelayServerConfig(
310 address, port, username, server.password, turn_transport_type);
311 if (server.tls_cert_policy ==
312 PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
313 config.tls_cert_policy =
314 cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
315 }
316 turn_servers->push_back(config);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200317 break;
318 }
319 case INVALID:
320 default:
321 LOG(WARNING) << "Configuration not supported: " << url;
322 return false;
323 }
324 return true;
325}
326
deadbeefab9b2d12015-10-14 11:33:11 -0700327// Check if we can send |new_stream| on a PeerConnection.
328bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
329 webrtc::MediaStreamInterface* new_stream) {
330 if (!new_stream || !current_streams) {
331 return false;
332 }
333 if (current_streams->find(new_stream->label()) != nullptr) {
334 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
335 << " is already added.";
336 return false;
337 }
338 return true;
339}
340
341bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
342 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
343}
344
deadbeef5e97fb52015-10-15 12:49:08 -0700345// If the direction is "recvonly" or "inactive", treat the description
346// as containing no streams.
347// See: https://code.google.com/p/webrtc/issues/detail?id=5054
348std::vector<cricket::StreamParams> GetActiveStreams(
349 const cricket::MediaContentDescription* desc) {
350 return MediaContentDirectionHasSend(desc->direction())
351 ? desc->streams()
352 : std::vector<cricket::StreamParams>();
353}
354
deadbeefab9b2d12015-10-14 11:33:11 -0700355bool IsValidOfferToReceiveMedia(int value) {
356 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
357 return (value >= Options::kUndefined) &&
358 (value <= Options::kMaxOfferToReceiveMedia);
359}
360
361// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800362void AddSendStreams(
363 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700364 const std::vector<rtc::scoped_refptr<
365 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800366 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
367 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700368 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800369 for (const auto& sender : senders) {
370 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700371 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700372 }
373
374 // Check for data channels.
375 for (const auto& kv : rtp_data_channels) {
376 const DataChannel* channel = kv.second;
377 if (channel->state() == DataChannel::kConnecting ||
378 channel->state() == DataChannel::kOpen) {
379 // |streamid| and |sync_label| are both set to the DataChannel label
380 // here so they can be signaled the same way as MediaStreams and Tracks.
381 // For MediaStreams, the sync_label is the MediaStream label and the
382 // track label is the same as |streamid|.
383 const std::string& streamid = channel->label();
384 const std::string& sync_label = channel->label();
385 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
386 sync_label);
387 }
388 }
389}
390
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700391uint32_t ConvertIceTransportTypeToCandidateFilter(
392 PeerConnectionInterface::IceTransportsType type) {
393 switch (type) {
394 case PeerConnectionInterface::kNone:
395 return cricket::CF_NONE;
396 case PeerConnectionInterface::kRelay:
397 return cricket::CF_RELAY;
398 case PeerConnectionInterface::kNoHost:
399 return (cricket::CF_ALL & ~cricket::CF_HOST);
400 case PeerConnectionInterface::kAll:
401 return cricket::CF_ALL;
402 default:
403 ASSERT(false);
404 }
405 return cricket::CF_NONE;
406}
407
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700408// Helper method to set a voice/video channel on all applicable senders
409// and receivers when one is created/destroyed by WebRtcSession.
410//
411// Used by On(Voice|Video)Channel(Created|Destroyed)
412template <class SENDER,
413 class RECEIVER,
414 class CHANNEL,
415 class SENDERS,
416 class RECEIVERS>
417void SetChannelOnSendersAndReceivers(CHANNEL* channel,
418 SENDERS& senders,
419 RECEIVERS& receivers,
420 cricket::MediaType media_type) {
421 for (auto& sender : senders) {
422 if (sender->media_type() == media_type) {
423 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
424 }
425 }
426 for (auto& receiver : receivers) {
427 if (receiver->media_type() == media_type) {
428 if (!channel) {
429 receiver->internal()->Stop();
430 }
431 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
432 }
433 }
434}
435
deadbeef0a6c4ca2015-10-06 11:38:28 -0700436} // namespace
437
438namespace webrtc {
439
deadbeef3edec7c2016-12-10 11:44:26 -0800440static const char* const kRtcErrorNames[] = {
441 "NONE",
442 "UNSUPPORTED_PARAMETER",
443 "INVALID_PARAMETER",
444 "INVALID_RANGE",
445 "SYNTAX_ERROR",
446 "INVALID_STATE",
447 "INVALID_MODIFICATION",
448 "NETWORK_ERROR",
449 "INTERNAL_ERROR",
450};
451
452std::ostream& operator<<(std::ostream& stream, RtcError error) {
453 int index = static_cast<int>(error);
454 RTC_CHECK(index < static_cast<int>(sizeof(kRtcErrorNames) /
455 sizeof(kRtcErrorNames[0])));
456 return stream << kRtcErrorNames[index];
457}
458
zhihuang8f65cdf2016-05-06 18:40:30 -0700459// Generate a RTCP CNAME when a PeerConnection is created.
460std::string GenerateRtcpCname() {
461 std::string cname;
462 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
463 LOG(LS_ERROR) << "Failed to generate CNAME.";
464 RTC_DCHECK(false);
465 }
466 return cname;
467}
468
htaa2a49d92016-03-04 02:51:39 -0800469bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700470 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800471 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700472 cricket::MediaSessionOptions* session_options) {
473 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
474 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
475 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
476 return false;
477 }
478
htaaac2dea2016-03-10 13:35:55 -0800479 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700480 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700481 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800482 } else {
483 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700484 }
htaaac2dea2016-03-10 13:35:55 -0800485 // For offers, we only offer video if we have it or it's forced by options.
486 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700487 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700488 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800489 } else if (is_offer) {
490 session_options->recv_video = false;
491 } else {
492 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700493 }
494
495 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700496 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800497 for (auto& kv : session_options->transport_options) {
498 kv.second.ice_restart = rtc_options.ice_restart;
499 }
deadbeefab9b2d12015-10-14 11:33:11 -0700500
501 return true;
502}
503
504bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
505 cricket::MediaSessionOptions* session_options) {
506 bool value = false;
507 size_t mandatory_constraints_satisfied = 0;
508
509 // kOfferToReceiveAudio defaults to true according to spec.
510 if (!FindConstraint(constraints,
511 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
512 &mandatory_constraints_satisfied) ||
513 value) {
514 session_options->recv_audio = true;
515 }
516
517 // kOfferToReceiveVideo defaults to false according to spec. But
518 // if it is an answer and video is offered, we should still accept video
519 // per default.
520 value = false;
521 if (!FindConstraint(constraints,
522 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
523 &mandatory_constraints_satisfied) ||
524 value) {
525 session_options->recv_video = true;
526 }
527
528 if (FindConstraint(constraints,
529 MediaConstraintsInterface::kVoiceActivityDetection, &value,
530 &mandatory_constraints_satisfied)) {
531 session_options->vad_enabled = value;
532 }
533
534 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
535 &mandatory_constraints_satisfied)) {
536 session_options->bundle_enabled = value;
537 } else {
538 // kUseRtpMux defaults to true according to spec.
539 session_options->bundle_enabled = true;
540 }
deadbeefab9b2d12015-10-14 11:33:11 -0700541
deadbeef0ed85b22016-02-23 17:24:52 -0800542 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700543 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
544 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700545 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800546 ice_restart = true;
547 }
548 for (auto& kv : session_options->transport_options) {
549 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700550 }
551
552 if (!constraints) {
553 return true;
554 }
555 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
556}
557
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200558bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800559 cricket::ServerAddresses* stun_servers,
560 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200561 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
562 if (!server.urls.empty()) {
563 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200564 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700565 LOG(LS_ERROR) << "Empty uri.";
566 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200567 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800568 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200569 return false;
570 }
571 }
572 } else if (!server.uri.empty()) {
573 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800574 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200576 }
577 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700578 LOG(LS_ERROR) << "Empty uri.";
579 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000580 }
581 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800582 // Candidates must have unique priorities, so that connectivity checks
583 // are performed in a well-defined order.
584 int priority = static_cast<int>(turn_servers->size() - 1);
585 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
586 // First in the list gets highest priority.
587 turn_server.priority = priority--;
588 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 return true;
590}
591
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592PeerConnection::PeerConnection(PeerConnectionFactory* factory)
593 : factory_(factory),
594 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000595 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000596 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700598 ice_gathering_state_(kIceGatheringNew),
skvlad11a9cbf2016-10-07 11:53:05 -0700599 event_log_(RtcEventLog::Create(webrtc::Clock::GetRealTimeClock())),
zhihuang8f65cdf2016-05-06 18:40:30 -0700600 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700601 local_streams_(StreamCollection::Create()),
602 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603
604PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100605 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700606 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700607 // Need to detach RTP senders/receivers from WebRtcSession,
608 // since it's about to be destroyed.
609 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700610 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700611 }
612 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700613 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700614 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700615 // Destroy stats_ because it depends on session_.
616 stats_.reset(nullptr);
617 // Now destroy session_ before destroying other members,
618 // because its destruction fires signals (such as VoiceChannelDestroyed)
619 // which will trigger some final actions in PeerConnection...
620 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700621 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700622 network_thread()->Invoke<void>(RTC_FROM_HERE,
623 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624}
625
626bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000627 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700628 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200629 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800630 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100631 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800632 RTC_DCHECK(observer != nullptr);
633 if (!observer) {
634 return false;
635 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000636 observer_ = observer;
637
kwiberg0eb15ed2015-12-17 03:04:15 -0800638 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800639
deadbeef91dd5672016-05-18 16:55:30 -0700640 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700641 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700642 if (!network_thread()->Invoke<bool>(
643 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
644 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645 return false;
646 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000647
skvlad11a9cbf2016-10-07 11:53:05 -0700648 media_controller_.reset(factory_->CreateMediaController(
649 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000650
zhihuang29ff8442016-07-27 11:07:25 -0700651 session_.reset(new WebRtcSession(
652 media_controller_.get(), factory_->network_thread(),
653 factory_->worker_thread(), factory_->signaling_thread(),
654 port_allocator_.get(),
655 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700656 factory_->CreateTransportController(
657 port_allocator_.get(),
658 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700659
deadbeefab9b2d12015-10-14 11:33:11 -0700660 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700661 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662
663 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200664 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800665 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700667 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669 // Register PeerConnection as receiver of local ice candidates.
670 // All the callbacks will be posted to the application from PeerConnection.
671 session_->RegisterIceObserver(this);
672 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700673 session_->SignalVoiceChannelCreated.connect(
674 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700675 session_->SignalVoiceChannelDestroyed.connect(
676 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700677 session_->SignalVideoChannelCreated.connect(
678 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700679 session_->SignalVideoChannelDestroyed.connect(
680 this, &PeerConnection::OnVideoChannelDestroyed);
681 session_->SignalDataChannelCreated.connect(
682 this, &PeerConnection::OnDataChannelCreated);
683 session_->SignalDataChannelDestroyed.connect(
684 this, &PeerConnection::OnDataChannelDestroyed);
685 session_->SignalDataChannelOpenMessage.connect(
686 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800687
688 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 return true;
690}
691
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000692rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700694 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695}
696
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000697rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700699 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700}
701
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000702bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100703 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 if (IsClosed()) {
705 return false;
706 }
deadbeefab9b2d12015-10-14 11:33:11 -0700707 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708 return false;
709 }
deadbeefab9b2d12015-10-14 11:33:11 -0700710
711 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800712 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
713 observer->SignalAudioTrackAdded.connect(this,
714 &PeerConnection::OnAudioTrackAdded);
715 observer->SignalAudioTrackRemoved.connect(
716 this, &PeerConnection::OnAudioTrackRemoved);
717 observer->SignalVideoTrackAdded.connect(this,
718 &PeerConnection::OnVideoTrackAdded);
719 observer->SignalVideoTrackRemoved.connect(
720 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700721 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700722
deadbeefab9b2d12015-10-14 11:33:11 -0700723 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800724 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700725 }
726 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800727 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700728 }
729
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000730 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 observer_->OnRenegotiationNeeded();
732 return true;
733}
734
735void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100736 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700737 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800738 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700739 }
740 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800741 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700742 }
743
744 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800745 stream_observers_.erase(
746 std::remove_if(
747 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700748 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800749 return observer->stream()->label().compare(local_stream->label()) ==
750 0;
751 }),
752 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700753
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754 if (IsClosed()) {
755 return;
756 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000757 observer_->OnRenegotiationNeeded();
758}
759
deadbeefe1f9d832016-01-14 15:35:42 -0800760rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
761 MediaStreamTrackInterface* track,
762 std::vector<MediaStreamInterface*> streams) {
763 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
764 if (IsClosed()) {
765 return nullptr;
766 }
767 if (streams.size() >= 2) {
768 LOG(LS_ERROR)
769 << "Adding a track with two streams is not currently supported.";
770 return nullptr;
771 }
772 // TODO(deadbeef): Support adding a track to two different senders.
773 if (FindSenderForTrack(track) != senders_.end()) {
774 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
775 return nullptr;
776 }
777
778 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700779 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800780 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700781 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800782 signaling_thread(),
783 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700784 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800785 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700786 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800787 }
788 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700789 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800790 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700791 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800792 }
793 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700794 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800795 signaling_thread(),
796 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700797 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800798 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700799 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800800 }
801 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700802 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800803 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700804 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800805 }
806 } else {
807 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
808 return rtc::scoped_refptr<RtpSenderInterface>();
809 }
810
811 senders_.push_back(new_sender);
812 observer_->OnRenegotiationNeeded();
813 return new_sender;
814}
815
816bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
817 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
818 if (IsClosed()) {
819 return false;
820 }
821
822 auto it = std::find(senders_.begin(), senders_.end(), sender);
823 if (it == senders_.end()) {
824 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
825 return false;
826 }
deadbeefa601f5c2016-06-06 14:27:39 -0700827 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800828 senders_.erase(it);
829
830 observer_->OnRenegotiationNeeded();
831 return true;
832}
833
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000834rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100836 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700837 if (IsClosed()) {
838 return nullptr;
839 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 if (!track) {
841 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
842 return NULL;
843 }
deadbeefab9b2d12015-10-14 11:33:11 -0700844 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000845 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
846 return NULL;
847 }
848
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000849 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 DtmfSender::Create(track, signaling_thread(), session_.get()));
851 if (!sender.get()) {
852 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
853 return NULL;
854 }
855 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
856}
857
deadbeeffac06552015-11-25 11:26:01 -0800858rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800859 const std::string& kind,
860 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100861 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700862 if (IsClosed()) {
863 return nullptr;
864 }
deadbeefa601f5c2016-06-06 14:27:39 -0700865 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800866 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700867 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700868 signaling_thread(),
869 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800870 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700871 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700872 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800873 } else {
874 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800875 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800876 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800877 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700878 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800879 }
deadbeeffac06552015-11-25 11:26:01 -0800880 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800881 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800882}
883
deadbeef70ab1a12015-09-28 16:53:55 -0700884std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
885 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700886 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
887 for (const auto& sender : senders_) {
888 ret.push_back(sender.get());
889 }
890 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700891}
892
893std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
894PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700895 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
896 for (const auto& receiver : receivers_) {
897 ret.push_back(receiver.get());
898 }
899 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700900}
901
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000902bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000903 MediaStreamTrackInterface* track,
904 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100905 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700906 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907 if (!VERIFY(observer != NULL)) {
908 LOG(LS_ERROR) << "GetStats - observer is NULL.";
909 return false;
910 }
911
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000912 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700913 // The StatsCollector is used to tell if a track is valid because it may
914 // remember tracks that the PeerConnection previously removed.
915 if (track && !stats_->IsValidTrack(track->id())) {
916 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
917 << track->id();
918 return false;
919 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700920 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000921 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922 return true;
923}
924
hbos74e1a4f2016-09-15 23:33:01 -0700925void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
926 RTC_DCHECK(stats_collector_);
927 stats_collector_->GetStatsReport(callback);
928}
929
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
931 return signaling_state_;
932}
933
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934PeerConnectionInterface::IceConnectionState
935PeerConnection::ice_connection_state() {
936 return ice_connection_state_;
937}
938
939PeerConnectionInterface::IceGatheringState
940PeerConnection::ice_gathering_state() {
941 return ice_gathering_state_;
942}
943
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000944rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945PeerConnection::CreateDataChannel(
946 const std::string& label,
947 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100948 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700949#ifdef HAVE_QUIC
950 if (session_->data_channel_type() == cricket::DCT_QUIC) {
951 // TODO(zhihuang): Handle case when config is NULL.
952 if (!config) {
953 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
954 return nullptr;
955 }
956 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
957 if (!config->reliable || config->ordered) {
958 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
959 "ordered delivery.";
960 return nullptr;
961 }
962 return session_->quic_data_transport()->CreateDataChannel(label, config);
963 }
964#endif // HAVE_QUIC
965
deadbeefab9b2d12015-10-14 11:33:11 -0700966 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000967
kwibergd1fe2812016-04-27 06:47:29 -0700968 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000969 if (config) {
970 internal_config.reset(new InternalDataChannelInit(*config));
971 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000972 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700973 InternalCreateDataChannel(label, internal_config.get()));
974 if (!channel.get()) {
975 return nullptr;
976 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000978 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
979 // the first SCTP DataChannel.
980 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
981 observer_->OnRenegotiationNeeded();
982 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000983
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 return DataChannelProxy::Create(signaling_thread(), channel.get());
985}
986
987void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
988 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100989 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700990 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
992 return;
993 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000994 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000995
996 bool value;
997 size_t mandatory_constraints = 0;
998
999 if (FindConstraint(constraints,
1000 MediaConstraintsInterface::kOfferToReceiveAudio,
1001 &value,
1002 &mandatory_constraints)) {
1003 options.offer_to_receive_audio =
1004 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1005 }
1006
1007 if (FindConstraint(constraints,
1008 MediaConstraintsInterface::kOfferToReceiveVideo,
1009 &value,
1010 &mandatory_constraints)) {
1011 options.offer_to_receive_video =
1012 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1013 }
1014
1015 if (FindConstraint(constraints,
1016 MediaConstraintsInterface::kVoiceActivityDetection,
1017 &value,
1018 &mandatory_constraints)) {
1019 options.voice_activity_detection = value;
1020 }
1021
1022 if (FindConstraint(constraints,
1023 MediaConstraintsInterface::kIceRestart,
1024 &value,
1025 &mandatory_constraints)) {
1026 options.ice_restart = value;
1027 }
1028
1029 if (FindConstraint(constraints,
1030 MediaConstraintsInterface::kUseRtpMux,
1031 &value,
1032 &mandatory_constraints)) {
1033 options.use_rtp_mux = value;
1034 }
1035
1036 CreateOffer(observer, options);
1037}
1038
1039void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1040 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001041 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001042 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001043 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1044 return;
1045 }
deadbeefab9b2d12015-10-14 11:33:11 -07001046
1047 cricket::MediaSessionOptions session_options;
1048 if (!GetOptionsForOffer(options, &session_options)) {
1049 std::string error = "CreateOffer called with invalid options.";
1050 LOG(LS_ERROR) << error;
1051 PostCreateSessionDescriptionFailure(observer, error);
1052 return;
1053 }
1054
1055 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056}
1057
1058void PeerConnection::CreateAnswer(
1059 CreateSessionDescriptionObserver* observer,
1060 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001061 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001062 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1064 return;
1065 }
deadbeefab9b2d12015-10-14 11:33:11 -07001066
1067 cricket::MediaSessionOptions session_options;
1068 if (!GetOptionsForAnswer(constraints, &session_options)) {
1069 std::string error = "CreateAnswer called with invalid constraints.";
1070 LOG(LS_ERROR) << error;
1071 PostCreateSessionDescriptionFailure(observer, error);
1072 return;
1073 }
1074
htaa2a49d92016-03-04 02:51:39 -08001075 session_->CreateAnswer(observer, session_options);
1076}
1077
1078void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1079 const RTCOfferAnswerOptions& options) {
1080 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1081 if (!VERIFY(observer != nullptr)) {
1082 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1083 return;
1084 }
1085
1086 cricket::MediaSessionOptions session_options;
1087 if (!GetOptionsForAnswer(options, &session_options)) {
1088 std::string error = "CreateAnswer called with invalid options.";
1089 LOG(LS_ERROR) << error;
1090 PostCreateSessionDescriptionFailure(observer, error);
1091 return;
1092 }
1093
1094 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095}
1096
1097void PeerConnection::SetLocalDescription(
1098 SetSessionDescriptionObserver* observer,
1099 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001100 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001101 if (IsClosed()) {
1102 return;
1103 }
deadbeefab9b2d12015-10-14 11:33:11 -07001104 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1106 return;
1107 }
1108 if (!desc) {
1109 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1110 return;
1111 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 // Update stats here so that we have the most recent stats for tracks and
1113 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001114 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115 std::string error;
1116 if (!session_->SetLocalDescription(desc, &error)) {
1117 PostSetSessionDescriptionFailure(observer, error);
1118 return;
1119 }
deadbeefab9b2d12015-10-14 11:33:11 -07001120
1121 // If setting the description decided our SSL role, allocate any necessary
1122 // SCTP sids.
1123 rtc::SSLRole role;
1124 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001125 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001126 AllocateSctpSids(role);
1127 }
1128
1129 // Update state and SSRC of local MediaStreams and DataChannels based on the
1130 // local session description.
1131 const cricket::ContentInfo* audio_content =
1132 GetFirstAudioContent(desc->description());
1133 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001134 if (audio_content->rejected) {
1135 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1136 } else {
1137 const cricket::AudioContentDescription* audio_desc =
1138 static_cast<const cricket::AudioContentDescription*>(
1139 audio_content->description);
1140 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1141 }
deadbeefab9b2d12015-10-14 11:33:11 -07001142 }
1143
1144 const cricket::ContentInfo* video_content =
1145 GetFirstVideoContent(desc->description());
1146 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001147 if (video_content->rejected) {
1148 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1149 } else {
1150 const cricket::VideoContentDescription* video_desc =
1151 static_cast<const cricket::VideoContentDescription*>(
1152 video_content->description);
1153 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1154 }
deadbeefab9b2d12015-10-14 11:33:11 -07001155 }
1156
1157 const cricket::ContentInfo* data_content =
1158 GetFirstDataContent(desc->description());
1159 if (data_content) {
1160 const cricket::DataContentDescription* data_desc =
1161 static_cast<const cricket::DataContentDescription*>(
1162 data_content->description);
1163 if (rtc::starts_with(data_desc->protocol().data(),
1164 cricket::kMediaProtocolRtpPrefix)) {
1165 UpdateLocalRtpDataChannels(data_desc->streams());
1166 }
1167 }
1168
1169 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001170 signaling_thread()->Post(RTC_FROM_HERE, this,
1171 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001172
deadbeefcbecd352015-09-23 11:50:27 -07001173 // MaybeStartGathering needs to be called after posting
1174 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1175 // before signaling that SetLocalDescription completed.
1176 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001177}
1178
1179void PeerConnection::SetRemoteDescription(
1180 SetSessionDescriptionObserver* observer,
1181 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001182 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001183 if (IsClosed()) {
1184 return;
1185 }
deadbeefab9b2d12015-10-14 11:33:11 -07001186 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1188 return;
1189 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190 if (!desc) {
1191 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1192 return;
1193 }
1194 // Update stats here so that we have the most recent stats for tracks and
1195 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001196 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 std::string error;
1198 if (!session_->SetRemoteDescription(desc, &error)) {
1199 PostSetSessionDescriptionFailure(observer, error);
1200 return;
1201 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202
deadbeefab9b2d12015-10-14 11:33:11 -07001203 // If setting the description decided our SSL role, allocate any necessary
1204 // SCTP sids.
1205 rtc::SSLRole role;
1206 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001207 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001208 AllocateSctpSids(role);
1209 }
1210
1211 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001212 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1213 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1214 const cricket::AudioContentDescription* audio_desc =
1215 GetFirstAudioContentDescription(remote_desc);
1216 const cricket::VideoContentDescription* video_desc =
1217 GetFirstVideoContentDescription(remote_desc);
1218 const cricket::DataContentDescription* data_desc =
1219 GetFirstDataContentDescription(remote_desc);
1220
1221 // Check if the descriptions include streams, just in case the peer supports
1222 // MSID, but doesn't indicate so with "a=msid-semantic".
1223 if (remote_desc->msid_supported() ||
1224 (audio_desc && !audio_desc->streams().empty()) ||
1225 (video_desc && !video_desc->streams().empty())) {
1226 remote_peer_supports_msid_ = true;
1227 }
deadbeefab9b2d12015-10-14 11:33:11 -07001228
1229 // We wait to signal new streams until we finish processing the description,
1230 // since only at that point will new streams have all their tracks.
1231 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1232
1233 // Find all audio rtp streams and create corresponding remote AudioTracks
1234 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001235 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001236 if (audio_content->rejected) {
1237 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1238 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001239 bool default_audio_track_needed =
1240 !remote_peer_supports_msid_ &&
1241 MediaContentDirectionHasSend(audio_desc->direction());
1242 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1243 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001244 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001245 }
deadbeefab9b2d12015-10-14 11:33:11 -07001246 }
1247
1248 // Find all video rtp streams and create corresponding remote VideoTracks
1249 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001250 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001251 if (video_content->rejected) {
1252 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1253 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001254 bool default_video_track_needed =
1255 !remote_peer_supports_msid_ &&
1256 MediaContentDirectionHasSend(video_desc->direction());
1257 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1258 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001259 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001260 }
deadbeefab9b2d12015-10-14 11:33:11 -07001261 }
1262
1263 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001264 if (data_desc) {
1265 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001266 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001267 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001268 }
1269 }
1270
1271 // Iterate new_streams and notify the observer about new MediaStreams.
1272 for (size_t i = 0; i < new_streams->count(); ++i) {
1273 MediaStreamInterface* new_stream = new_streams->at(i);
1274 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001275 // Call both the raw pointer and scoped_refptr versions of the method
1276 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001277 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001278 observer_->OnAddStream(
1279 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001280 }
1281
deadbeefbda7e0b2015-12-08 17:13:40 -08001282 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001283
1284 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001285 signaling_thread()->Post(RTC_FROM_HERE, this,
1286 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001287}
1288
deadbeef46c73892016-11-16 19:42:04 -08001289PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1290 return configuration_;
1291}
1292
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001293bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001294 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001295
1296 if (session_->local_description() &&
1297 configuration.ice_candidate_pool_size !=
1298 configuration_.ice_candidate_pool_size) {
1299 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1300 "SetLocalDescription.";
1301 return false;
1302 }
deadbeef46c73892016-11-16 19:42:04 -08001303 // TODO(deadbeef): Return false and log an error if there are any unsupported
1304 // modifications.
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001305 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001306 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001307 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001308 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001309 configuration))) {
deadbeef6de92f92016-12-12 18:49:32 -08001310 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001311 return false;
1312 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001313 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001314
deadbeefd1a38b52016-12-10 13:15:33 -08001315 // TODO(deadbeef): Shouldn't have to hop to the network thread twice...
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001316 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001317
deadbeefd1a38b52016-12-10 13:15:33 -08001318 // As described in JSEP, calling setConfiguration with new ICE servers or
1319 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1320 // triggers an ICE restart which will pick up the changes.
1321 if (configuration.servers != configuration_.servers ||
1322 configuration.type != configuration_.type) {
1323 session_->SetNeedsIceRestartFlag();
1324 }
deadbeef46c73892016-11-16 19:42:04 -08001325 configuration_ = configuration;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001326 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001327}
1328
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329bool PeerConnection::AddIceCandidate(
1330 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001331 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001332 if (IsClosed()) {
1333 return false;
1334 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335 return session_->ProcessIceMessage(ice_candidate);
1336}
1337
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001338bool PeerConnection::RemoveIceCandidates(
1339 const std::vector<cricket::Candidate>& candidates) {
1340 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1341 return session_->RemoveRemoteIceCandidates(candidates);
1342}
1343
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001344void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001345 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001346 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001347
1348 if (session_) {
1349 session_->set_metrics_observer(uma_observer_);
1350 }
1351
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001352 // Send information about IPv4/IPv6 status.
1353 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001354 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001355 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001356 uma_observer_->IncrementEnumCounter(
1357 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1358 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001359 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001360 uma_observer_->IncrementEnumCounter(
1361 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1362 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001363 }
1364 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001365}
1366
ivoc14d5dbe2016-07-04 07:06:55 -07001367bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1368 int64_t max_size_bytes) {
1369 return factory_->worker_thread()->Invoke<bool>(
1370 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1371 max_size_bytes));
1372}
1373
1374void PeerConnection::StopRtcEventLog() {
1375 factory_->worker_thread()->Invoke<void>(
1376 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1377}
1378
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379const SessionDescriptionInterface* PeerConnection::local_description() const {
1380 return session_->local_description();
1381}
1382
1383const SessionDescriptionInterface* PeerConnection::remote_description() const {
1384 return session_->remote_description();
1385}
1386
1387void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001388 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 // Update stats here so that we have the most recent stats for tracks and
1390 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001391 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392
deadbeefd59daf82015-10-14 15:02:44 -07001393 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394}
1395
deadbeefd59daf82015-10-14 15:02:44 -07001396void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1397 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001399 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001401 break;
deadbeefd59daf82015-10-14 15:02:44 -07001402 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1404 break;
deadbeefd59daf82015-10-14 15:02:44 -07001405 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1407 break;
deadbeefd59daf82015-10-14 15:02:44 -07001408 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1410 break;
deadbeefd59daf82015-10-14 15:02:44 -07001411 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1413 break;
deadbeefd59daf82015-10-14 15:02:44 -07001414 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 ChangeSignalingState(PeerConnectionInterface::kStable);
1416 break;
deadbeefd59daf82015-10-14 15:02:44 -07001417 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001418 ChangeSignalingState(PeerConnectionInterface::kClosed);
1419 break;
1420 default:
1421 break;
1422 }
1423}
1424
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001425void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1428 SetSessionDescriptionMsg* param =
1429 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1430 param->observer->OnSuccess();
1431 delete param;
1432 break;
1433 }
1434 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1435 SetSessionDescriptionMsg* param =
1436 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1437 param->observer->OnFailure(param->error);
1438 delete param;
1439 break;
1440 }
deadbeefab9b2d12015-10-14 11:33:11 -07001441 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1442 CreateSessionDescriptionMsg* param =
1443 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1444 param->observer->OnFailure(param->error);
1445 delete param;
1446 break;
1447 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001448 case MSG_GETSTATS: {
1449 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001450 StatsReports reports;
1451 stats_->GetStats(param->track, &reports);
1452 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 delete param;
1454 break;
1455 }
deadbeefbd292462015-12-14 18:15:29 -08001456 case MSG_FREE_DATACHANNELS: {
1457 sctp_data_channels_to_free_.clear();
1458 break;
1459 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001461 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 break;
1463 }
1464}
1465
deadbeefab9b2d12015-10-14 11:33:11 -07001466void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001467 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001468 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001469 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1470 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001471 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001472 session_->voice_channel()));
1473
1474 receivers_.push_back(receiver);
1475 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1476 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1477 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478}
1479
deadbeefab9b2d12015-10-14 11:33:11 -07001480void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001481 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001482 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001483 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1484 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001485 signaling_thread(),
1486 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001487 ssrc, session_->video_channel()));
1488 receivers_.push_back(receiver);
1489 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1490 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1491 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001492}
1493
deadbeef70ab1a12015-09-28 16:53:55 -07001494// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1495// description.
perkjd61bf802016-03-24 03:16:19 -07001496void PeerConnection::DestroyReceiver(const std::string& track_id) {
1497 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001498 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001499 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001500 << " doesn't exist.";
1501 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001502 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001503 receivers_.erase(it);
1504 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505}
1506
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507void PeerConnection::OnIceConnectionChange(
1508 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001509 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001510 // After transitioning to "closed", ignore any additional states from
1511 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001512 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001513 return;
1514 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001515 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001516 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001517}
1518
1519void PeerConnection::OnIceGatheringChange(
1520 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001521 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522 if (IsClosed()) {
1523 return;
1524 }
1525 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001526 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001527}
1528
1529void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001530 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001531 if (IsClosed()) {
1532 return;
1533 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001534 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535}
1536
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001537void PeerConnection::OnIceCandidatesRemoved(
1538 const std::vector<cricket::Candidate>& candidates) {
1539 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001540 if (IsClosed()) {
1541 return;
1542 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001543 observer_->OnIceCandidatesRemoved(candidates);
1544}
1545
Peter Thatcher54360512015-07-08 11:08:35 -07001546void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001547 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001548 if (IsClosed()) {
1549 return;
1550 }
Peter Thatcher54360512015-07-08 11:08:35 -07001551 observer_->OnIceConnectionReceivingChange(receiving);
1552}
1553
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554void PeerConnection::ChangeSignalingState(
1555 PeerConnectionInterface::SignalingState signaling_state) {
1556 signaling_state_ = signaling_state;
1557 if (signaling_state == kClosed) {
1558 ice_connection_state_ = kIceConnectionClosed;
1559 observer_->OnIceConnectionChange(ice_connection_state_);
1560 if (ice_gathering_state_ != kIceGatheringComplete) {
1561 ice_gathering_state_ = kIceGatheringComplete;
1562 observer_->OnIceGatheringChange(ice_gathering_state_);
1563 }
1564 }
1565 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566}
1567
deadbeefeb459812015-12-15 19:24:43 -08001568void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1569 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001570 if (IsClosed()) {
1571 return;
1572 }
deadbeefeb459812015-12-15 19:24:43 -08001573 auto sender = FindSenderForTrack(track);
1574 if (sender != senders_.end()) {
1575 // We already have a sender for this track, so just change the stream_id
1576 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001577 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001578 return;
1579 }
1580
1581 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001582 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1583 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001584 signaling_thread(),
1585 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1586 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001587 senders_.push_back(new_sender);
1588 // If the sender has already been configured in SDP, we call SetSsrc,
1589 // which will connect the sender to the underlying transport. This can
1590 // occur if a local session description that contains the ID of the sender
1591 // is set before AddStream is called. It can also occur if the local
1592 // session description is not changed and RemoveStream is called, and
1593 // later AddStream is called again with the same stream.
1594 const TrackInfo* track_info =
1595 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1596 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001597 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001598 }
1599}
1600
1601// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1602// indefinitely, when we have unified plan SDP.
1603void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1604 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001605 if (IsClosed()) {
1606 return;
1607 }
deadbeefeb459812015-12-15 19:24:43 -08001608 auto sender = FindSenderForTrack(track);
1609 if (sender == senders_.end()) {
1610 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1611 << " doesn't exist.";
1612 return;
1613 }
deadbeefa601f5c2016-06-06 14:27:39 -07001614 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001615 senders_.erase(sender);
1616}
1617
1618void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1619 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001620 if (IsClosed()) {
1621 return;
1622 }
deadbeefeb459812015-12-15 19:24:43 -08001623 auto sender = FindSenderForTrack(track);
1624 if (sender != senders_.end()) {
1625 // We already have a sender for this track, so just change the stream_id
1626 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001627 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001628 return;
1629 }
1630
1631 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001632 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1633 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001634 signaling_thread(), new VideoRtpSender(track, stream->label(),
1635 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001636 senders_.push_back(new_sender);
1637 const TrackInfo* track_info =
1638 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1639 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001640 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001641 }
1642}
1643
1644void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1645 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001646 if (IsClosed()) {
1647 return;
1648 }
deadbeefeb459812015-12-15 19:24:43 -08001649 auto sender = FindSenderForTrack(track);
1650 if (sender == senders_.end()) {
1651 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1652 << " doesn't exist.";
1653 return;
1654 }
deadbeefa601f5c2016-06-06 14:27:39 -07001655 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001656 senders_.erase(sender);
1657}
1658
deadbeefab9b2d12015-10-14 11:33:11 -07001659void PeerConnection::PostSetSessionDescriptionFailure(
1660 SetSessionDescriptionObserver* observer,
1661 const std::string& error) {
1662 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1663 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001664 signaling_thread()->Post(RTC_FROM_HERE, this,
1665 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001666}
1667
1668void PeerConnection::PostCreateSessionDescriptionFailure(
1669 CreateSessionDescriptionObserver* observer,
1670 const std::string& error) {
1671 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1672 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001673 signaling_thread()->Post(RTC_FROM_HERE, this,
1674 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001675}
1676
1677bool PeerConnection::GetOptionsForOffer(
1678 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1679 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001680 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1681 // ContentInfos.
1682 if (session_->local_description()) {
1683 for (const cricket::ContentInfo& content :
1684 session_->local_description()->description()->contents()) {
1685 session_options->transport_options[content.name] =
1686 cricket::TransportOptions();
1687 }
1688 }
deadbeef46c73892016-11-16 19:42:04 -08001689 session_options->enable_ice_renomination =
1690 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001691
htaaac2dea2016-03-10 13:35:55 -08001692 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001693 return false;
1694 }
1695
deadbeeffac06552015-11-25 11:26:01 -08001696 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001697 // Offer to receive audio/video if the constraint is not set and there are
1698 // send streams, or we're currently receiving.
1699 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1700 session_options->recv_audio =
1701 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1702 !remote_audio_tracks_.empty();
1703 }
1704 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1705 session_options->recv_video =
1706 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1707 !remote_video_tracks_.empty();
1708 }
deadbeefc80741f2015-10-22 13:14:45 -07001709
zhihuang9763d562016-08-05 11:14:50 -07001710 // Intentionally unset the data channel type for RTP data channel with the
1711 // second condition. Otherwise the RTP data channels would be successfully
1712 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1713 // when building with chromium. We want to leave RTP data channels broken, so
1714 // people won't try to use them.
1715 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1716 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001717 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001718
zhihuangaf388472016-11-02 16:49:48 -07001719 session_options->bundle_enabled =
1720 session_options->bundle_enabled &&
1721 (session_options->has_audio() || session_options->has_video() ||
1722 session_options->has_data());
1723
zhihuang8f65cdf2016-05-06 18:40:30 -07001724 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001725 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001726 return true;
1727}
1728
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001729void PeerConnection::InitializeOptionsForAnswer(
1730 cricket::MediaSessionOptions* session_options) {
1731 session_options->recv_audio = false;
1732 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001733 session_options->enable_ice_renomination =
1734 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001735}
1736
htaa2a49d92016-03-04 02:51:39 -08001737void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001738 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001739 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1740 // ContentInfos.
1741 if (session_->remote_description()) {
1742 // Initialize the transport_options map.
1743 for (const cricket::ContentInfo& content :
1744 session_->remote_description()->description()->contents()) {
1745 session_options->transport_options[content.name] =
1746 cricket::TransportOptions();
1747 }
1748 }
deadbeeffac06552015-11-25 11:26:01 -08001749 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001750 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1751 // are not signaled in the SDP so does not go through that path and must be
1752 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001753 // Intentionally unset the data channel type for RTP data channel. Otherwise
1754 // the RTP data channels would be successfully negotiated by default and the
1755 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1756 // We want to leave RTP data channels broken, so people won't try to use them.
1757 if (session_->data_channel_type() != cricket::DCT_RTP) {
1758 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001759 }
zhihuangaf388472016-11-02 16:49:48 -07001760 session_options->bundle_enabled =
1761 session_options->bundle_enabled &&
1762 (session_options->has_audio() || session_options->has_video() ||
1763 session_options->has_data());
1764
jbauchcb560652016-08-04 05:20:32 -07001765 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001766}
1767
1768bool PeerConnection::GetOptionsForAnswer(
1769 const MediaConstraintsInterface* constraints,
1770 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001771 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001772 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1773 return false;
1774 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001775 session_options->rtcp_cname = rtcp_cname_;
1776
htaa2a49d92016-03-04 02:51:39 -08001777 FinishOptionsForAnswer(session_options);
1778 return true;
1779}
1780
1781bool PeerConnection::GetOptionsForAnswer(
1782 const RTCOfferAnswerOptions& options,
1783 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001784 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001785 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001786 return false;
1787 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001788 session_options->rtcp_cname = rtcp_cname_;
1789
htaa2a49d92016-03-04 02:51:39 -08001790 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001791 return true;
1792}
1793
deadbeeffaac4972015-11-12 15:33:07 -08001794void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1795 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001796 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1797 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001798}
1799
deadbeefab9b2d12015-10-14 11:33:11 -07001800void PeerConnection::UpdateRemoteStreamsList(
1801 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001802 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001803 cricket::MediaType media_type,
1804 StreamCollection* new_streams) {
1805 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1806
1807 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001808 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001809 auto track_it = current_tracks->begin();
1810 while (track_it != current_tracks->end()) {
1811 const TrackInfo& info = *track_it;
1812 const cricket::StreamParams* params =
1813 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001814 bool track_exists = params && params->id == info.track_id;
1815 // If this is a default track, and we still need it, don't remove it.
1816 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1817 track_exists) {
1818 ++track_it;
1819 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001820 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1821 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001822 }
1823 }
1824
1825 // Find new and active tracks.
1826 for (const cricket::StreamParams& params : streams) {
1827 // The sync_label is the MediaStream label and the |stream.id| is the
1828 // track id.
1829 const std::string& stream_label = params.sync_label;
1830 const std::string& track_id = params.id;
1831 uint32_t ssrc = params.first_ssrc();
1832
1833 rtc::scoped_refptr<MediaStreamInterface> stream =
1834 remote_streams_->find(stream_label);
1835 if (!stream) {
1836 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001837 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1838 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001839 remote_streams_->AddStream(stream);
1840 new_streams->AddStream(stream);
1841 }
1842
1843 const TrackInfo* track_info =
1844 FindTrackInfo(*current_tracks, stream_label, track_id);
1845 if (!track_info) {
1846 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1847 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1848 }
1849 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001850
1851 // Add default track if necessary.
1852 if (default_track_needed) {
1853 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1854 remote_streams_->find(kDefaultStreamLabel);
1855 if (!default_stream) {
1856 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001857 default_stream = MediaStreamProxy::Create(
1858 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001859 remote_streams_->AddStream(default_stream);
1860 new_streams->AddStream(default_stream);
1861 }
1862 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1863 ? kDefaultAudioTrackLabel
1864 : kDefaultVideoTrackLabel;
1865 const TrackInfo* default_track_info =
1866 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1867 if (!default_track_info) {
1868 current_tracks->push_back(
1869 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1870 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1871 }
1872 }
deadbeefab9b2d12015-10-14 11:33:11 -07001873}
1874
1875void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1876 const std::string& track_id,
1877 uint32_t ssrc,
1878 cricket::MediaType media_type) {
1879 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1880
1881 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001882 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001883 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001884 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001885 } else {
1886 RTC_DCHECK(false && "Invalid media type");
1887 }
1888}
1889
1890void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1891 const std::string& track_id,
1892 cricket::MediaType media_type) {
1893 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1894
1895 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001896 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1897 // will be notified which will end the AudioRtpReceiver::track().
1898 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001899 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1900 stream->FindAudioTrack(track_id);
1901 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001902 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001903 }
1904 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001905 // Stopping or destroying a VideoRtpReceiver will end the
1906 // VideoRtpReceiver::track().
1907 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001908 rtc::scoped_refptr<VideoTrackInterface> video_track =
1909 stream->FindVideoTrack(track_id);
1910 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001911 // There's no guarantee the track is still available, e.g. the track may
1912 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001913 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001914 }
1915 } else {
1916 ASSERT(false && "Invalid media type");
1917 }
1918}
1919
1920void PeerConnection::UpdateEndedRemoteMediaStreams() {
1921 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1922 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1923 MediaStreamInterface* stream = remote_streams_->at(i);
1924 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1925 streams_to_remove.push_back(stream);
1926 }
1927 }
1928
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001929 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001930 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001931 // Call both the raw pointer and scoped_refptr versions of the method
1932 // for compatibility.
1933 observer_->OnRemoveStream(stream.get());
1934 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001935 }
1936}
1937
deadbeefab9b2d12015-10-14 11:33:11 -07001938void PeerConnection::UpdateLocalTracks(
1939 const std::vector<cricket::StreamParams>& streams,
1940 cricket::MediaType media_type) {
1941 TrackInfos* current_tracks = GetLocalTracks(media_type);
1942
1943 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1944 // don't match the new StreamParam.
1945 TrackInfos::iterator track_it = current_tracks->begin();
1946 while (track_it != current_tracks->end()) {
1947 const TrackInfo& info = *track_it;
1948 const cricket::StreamParams* params =
1949 cricket::GetStreamBySsrc(streams, info.ssrc);
1950 if (!params || params->id != info.track_id ||
1951 params->sync_label != info.stream_label) {
1952 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1953 media_type);
1954 track_it = current_tracks->erase(track_it);
1955 } else {
1956 ++track_it;
1957 }
1958 }
1959
1960 // Find new and active tracks.
1961 for (const cricket::StreamParams& params : streams) {
1962 // The sync_label is the MediaStream label and the |stream.id| is the
1963 // track id.
1964 const std::string& stream_label = params.sync_label;
1965 const std::string& track_id = params.id;
1966 uint32_t ssrc = params.first_ssrc();
1967 const TrackInfo* track_info =
1968 FindTrackInfo(*current_tracks, stream_label, track_id);
1969 if (!track_info) {
1970 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1971 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1972 }
1973 }
1974}
1975
1976void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1977 const std::string& track_id,
1978 uint32_t ssrc,
1979 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001980 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001981 if (!sender) {
1982 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1983 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001984 return;
1985 }
1986
deadbeeffac06552015-11-25 11:26:01 -08001987 if (sender->media_type() != media_type) {
1988 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1989 << " description with an unexpected media type.";
1990 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001991 }
deadbeeffac06552015-11-25 11:26:01 -08001992
1993 sender->set_stream_id(stream_label);
1994 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001995}
1996
1997void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1998 const std::string& track_id,
1999 uint32_t ssrc,
2000 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002001 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002002 if (!sender) {
2003 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002004 // SessionDescriptions has been renegotiated.
2005 return;
2006 }
deadbeeffac06552015-11-25 11:26:01 -08002007
2008 // A sender has been removed from the SessionDescription but it's still
2009 // associated with the PeerConnection. This only occurs if the SDP doesn't
2010 // match with the calls to CreateSender, AddStream and RemoveStream.
2011 if (sender->media_type() != media_type) {
2012 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2013 << " description with an unexpected media type.";
2014 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002015 }
deadbeeffac06552015-11-25 11:26:01 -08002016
2017 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002018}
2019
2020void PeerConnection::UpdateLocalRtpDataChannels(
2021 const cricket::StreamParamsVec& streams) {
2022 std::vector<std::string> existing_channels;
2023
2024 // Find new and active data channels.
2025 for (const cricket::StreamParams& params : streams) {
2026 // |it->sync_label| is actually the data channel label. The reason is that
2027 // we use the same naming of data channels as we do for
2028 // MediaStreams and Tracks.
2029 // For MediaStreams, the sync_label is the MediaStream label and the
2030 // track label is the same as |streamid|.
2031 const std::string& channel_label = params.sync_label;
2032 auto data_channel_it = rtp_data_channels_.find(channel_label);
2033 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
2034 continue;
2035 }
2036 // Set the SSRC the data channel should use for sending.
2037 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2038 existing_channels.push_back(data_channel_it->first);
2039 }
2040
2041 UpdateClosingRtpDataChannels(existing_channels, true);
2042}
2043
2044void PeerConnection::UpdateRemoteRtpDataChannels(
2045 const cricket::StreamParamsVec& streams) {
2046 std::vector<std::string> existing_channels;
2047
2048 // Find new and active data channels.
2049 for (const cricket::StreamParams& params : streams) {
2050 // The data channel label is either the mslabel or the SSRC if the mslabel
2051 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2052 std::string label = params.sync_label.empty()
2053 ? rtc::ToString(params.first_ssrc())
2054 : params.sync_label;
2055 auto data_channel_it = rtp_data_channels_.find(label);
2056 if (data_channel_it == rtp_data_channels_.end()) {
2057 // This is a new data channel.
2058 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2059 } else {
2060 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2061 }
2062 existing_channels.push_back(label);
2063 }
2064
2065 UpdateClosingRtpDataChannels(existing_channels, false);
2066}
2067
2068void PeerConnection::UpdateClosingRtpDataChannels(
2069 const std::vector<std::string>& active_channels,
2070 bool is_local_update) {
2071 auto it = rtp_data_channels_.begin();
2072 while (it != rtp_data_channels_.end()) {
2073 DataChannel* data_channel = it->second;
2074 if (std::find(active_channels.begin(), active_channels.end(),
2075 data_channel->label()) != active_channels.end()) {
2076 ++it;
2077 continue;
2078 }
2079
2080 if (is_local_update) {
2081 data_channel->SetSendSsrc(0);
2082 } else {
2083 data_channel->RemotePeerRequestClose();
2084 }
2085
2086 if (data_channel->state() == DataChannel::kClosed) {
2087 rtp_data_channels_.erase(it);
2088 it = rtp_data_channels_.begin();
2089 } else {
2090 ++it;
2091 }
2092 }
2093}
2094
2095void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2096 uint32_t remote_ssrc) {
2097 rtc::scoped_refptr<DataChannel> channel(
2098 InternalCreateDataChannel(label, nullptr));
2099 if (!channel.get()) {
2100 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2101 << "CreateDataChannel failed.";
2102 return;
2103 }
2104 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002105 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2106 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002107 // Call both the raw pointer and scoped_refptr versions of the method
2108 // for compatibility.
2109 observer_->OnDataChannel(proxy_channel.get());
2110 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002111}
2112
2113rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2114 const std::string& label,
2115 const InternalDataChannelInit* config) {
2116 if (IsClosed()) {
2117 return nullptr;
2118 }
2119 if (session_->data_channel_type() == cricket::DCT_NONE) {
2120 LOG(LS_ERROR)
2121 << "InternalCreateDataChannel: Data is not supported in this call.";
2122 return nullptr;
2123 }
2124 InternalDataChannelInit new_config =
2125 config ? (*config) : InternalDataChannelInit();
2126 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2127 if (new_config.id < 0) {
2128 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002129 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002130 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2131 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2132 return nullptr;
2133 }
2134 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2135 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2136 << "because the id is already in use or out of range.";
2137 return nullptr;
2138 }
2139 }
2140
2141 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2142 session_.get(), session_->data_channel_type(), label, new_config));
2143 if (!channel) {
2144 sid_allocator_.ReleaseSid(new_config.id);
2145 return nullptr;
2146 }
2147
2148 if (channel->data_channel_type() == cricket::DCT_RTP) {
2149 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2150 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2151 << " already exists.";
2152 return nullptr;
2153 }
2154 rtp_data_channels_[channel->label()] = channel;
2155 } else {
2156 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2157 sctp_data_channels_.push_back(channel);
2158 channel->SignalClosed.connect(this,
2159 &PeerConnection::OnSctpDataChannelClosed);
2160 }
2161
hbos82ebe022016-11-14 01:41:09 -08002162 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002163 return channel;
2164}
2165
2166bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002167#ifdef HAVE_QUIC
2168 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2169 (session_->quic_data_transport() &&
2170 session_->quic_data_transport()->HasDataChannels());
2171#else
deadbeefab9b2d12015-10-14 11:33:11 -07002172 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002173#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002174}
2175
2176void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2177 for (const auto& channel : sctp_data_channels_) {
2178 if (channel->id() < 0) {
2179 int sid;
2180 if (!sid_allocator_.AllocateSid(role, &sid)) {
2181 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2182 continue;
2183 }
2184 channel->SetSctpSid(sid);
2185 }
2186 }
2187}
2188
2189void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002190 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002191 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2192 ++it) {
2193 if (it->get() == channel) {
2194 if (channel->id() >= 0) {
2195 sid_allocator_.ReleaseSid(channel->id());
2196 }
deadbeefbd292462015-12-14 18:15:29 -08002197 // Since this method is triggered by a signal from the DataChannel,
2198 // we can't free it directly here; we need to free it asynchronously.
2199 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002200 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002201 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2202 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002203 return;
2204 }
2205 }
2206}
2207
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002208void PeerConnection::OnVoiceChannelCreated() {
2209 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2210 session_->voice_channel(), senders_, receivers_,
2211 cricket::MEDIA_TYPE_AUDIO);
2212}
2213
deadbeefab9b2d12015-10-14 11:33:11 -07002214void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002215 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2216 cricket::VoiceChannel>(
2217 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2218}
2219
2220void PeerConnection::OnVideoChannelCreated() {
2221 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2222 session_->video_channel(), senders_, receivers_,
2223 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002224}
2225
2226void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002227 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2228 cricket::VideoChannel>(
2229 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002230}
2231
2232void PeerConnection::OnDataChannelCreated() {
2233 for (const auto& channel : sctp_data_channels_) {
2234 channel->OnTransportChannelCreated();
2235 }
2236}
2237
2238void PeerConnection::OnDataChannelDestroyed() {
2239 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2240 // DataChannel may callback to us and try to modify the list.
2241 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2242 temp_rtp_dcs.swap(rtp_data_channels_);
2243 for (const auto& kv : temp_rtp_dcs) {
2244 kv.second->OnTransportChannelDestroyed();
2245 }
2246
2247 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2248 temp_sctp_dcs.swap(sctp_data_channels_);
2249 for (const auto& channel : temp_sctp_dcs) {
2250 channel->OnTransportChannelDestroyed();
2251 }
2252}
2253
2254void PeerConnection::OnDataChannelOpenMessage(
2255 const std::string& label,
2256 const InternalDataChannelInit& config) {
2257 rtc::scoped_refptr<DataChannel> channel(
2258 InternalCreateDataChannel(label, &config));
2259 if (!channel.get()) {
2260 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2261 return;
2262 }
2263
deadbeefa601f5c2016-06-06 14:27:39 -07002264 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2265 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002266 // Call both the raw pointer and scoped_refptr versions of the method
2267 // for compatibility.
2268 observer_->OnDataChannel(proxy_channel.get());
2269 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002270}
2271
deadbeefa601f5c2016-06-06 14:27:39 -07002272RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2273 auto it = std::find_if(
2274 senders_.begin(), senders_.end(),
2275 [id](const rtc::scoped_refptr<
2276 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2277 return sender->id() == id;
2278 });
2279 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002280}
2281
deadbeefa601f5c2016-06-06 14:27:39 -07002282std::vector<
2283 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002284PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2285 return std::find_if(
2286 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002287 [track](const rtc::scoped_refptr<
2288 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002289 return sender->track() == track;
2290 });
2291}
2292
deadbeefa601f5c2016-06-06 14:27:39 -07002293std::vector<rtc::scoped_refptr<
2294 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002295PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002296 return std::find_if(
2297 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002298 [track_id](const rtc::scoped_refptr<
2299 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002300 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002301 });
2302}
2303
deadbeefab9b2d12015-10-14 11:33:11 -07002304PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2305 cricket::MediaType media_type) {
2306 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2307 media_type == cricket::MEDIA_TYPE_VIDEO);
2308 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2309 : &remote_video_tracks_;
2310}
2311
2312PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2313 cricket::MediaType media_type) {
2314 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2315 media_type == cricket::MEDIA_TYPE_VIDEO);
2316 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2317 : &local_video_tracks_;
2318}
2319
2320const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2321 const PeerConnection::TrackInfos& infos,
2322 const std::string& stream_label,
2323 const std::string track_id) const {
2324 for (const TrackInfo& track_info : infos) {
2325 if (track_info.stream_label == stream_label &&
2326 track_info.track_id == track_id) {
2327 return &track_info;
2328 }
2329 }
2330 return nullptr;
2331}
2332
2333DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2334 for (const auto& channel : sctp_data_channels_) {
2335 if (channel->id() == sid) {
2336 return channel;
2337 }
2338 }
2339 return nullptr;
2340}
2341
deadbeef91dd5672016-05-18 16:55:30 -07002342bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002343 const RTCConfiguration& configuration) {
2344 cricket::ServerAddresses stun_servers;
2345 std::vector<cricket::RelayServerConfig> turn_servers;
2346 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2347 return false;
2348 }
2349
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002350 port_allocator_->Initialize();
2351
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002352 // To handle both internal and externally created port allocator, we will
2353 // enable BUNDLE here.
2354 int portallocator_flags = port_allocator_->flags();
2355 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2356 cricket::PORTALLOCATOR_ENABLE_IPV6;
2357 // If the disable-IPv6 flag was specified, we'll not override it
2358 // by experiment.
2359 if (configuration.disable_ipv6) {
2360 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2361 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2362 "Disabled") {
2363 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2364 }
2365
2366 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2367 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2368 LOG(LS_INFO) << "TCP candidates are disabled.";
2369 }
2370
honghaiz60347052016-05-31 18:29:12 -07002371 if (configuration.candidate_network_policy ==
2372 kCandidateNetworkPolicyLowCost) {
2373 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2374 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2375 }
2376
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002377 port_allocator_->set_flags(portallocator_flags);
2378 // No step delay is used while allocating ports.
2379 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2380 port_allocator_->set_candidate_filter(
2381 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2382
2383 // Call this last since it may create pooled allocator sessions using the
2384 // properties set above.
2385 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002386 configuration.ice_candidate_pool_size,
2387 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002388 return true;
2389}
2390
deadbeef91dd5672016-05-18 16:55:30 -07002391bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002392 const RTCConfiguration& configuration) {
2393 cricket::ServerAddresses stun_servers;
2394 std::vector<cricket::RelayServerConfig> turn_servers;
2395 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2396 return false;
2397 }
2398 port_allocator_->set_candidate_filter(
2399 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2400 // Call this last since it may create pooled allocator sessions using the
2401 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002402 return port_allocator_->SetConfiguration(
2403 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
2404 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002405}
2406
ivoc14d5dbe2016-07-04 07:06:55 -07002407bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2408 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002409 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002410}
2411
2412void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002413 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002414}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415} // namespace webrtc