blob: 692ca2e2535bf3e0bedd6b0cbabb68d0ab71fa9c [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;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800288 turn_transport_type = cricket::PROTO_TCP;
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: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200309 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800310 turn_servers->push_back(
311 cricket::RelayServerConfig(address, port, username, server.password,
312 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200313 break;
314 }
315 case INVALID:
316 default:
317 LOG(WARNING) << "Configuration not supported: " << url;
318 return false;
319 }
320 return true;
321}
322
deadbeefab9b2d12015-10-14 11:33:11 -0700323// Check if we can send |new_stream| on a PeerConnection.
324bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
325 webrtc::MediaStreamInterface* new_stream) {
326 if (!new_stream || !current_streams) {
327 return false;
328 }
329 if (current_streams->find(new_stream->label()) != nullptr) {
330 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
331 << " is already added.";
332 return false;
333 }
334 return true;
335}
336
337bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
338 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
339}
340
deadbeef5e97fb52015-10-15 12:49:08 -0700341// If the direction is "recvonly" or "inactive", treat the description
342// as containing no streams.
343// See: https://code.google.com/p/webrtc/issues/detail?id=5054
344std::vector<cricket::StreamParams> GetActiveStreams(
345 const cricket::MediaContentDescription* desc) {
346 return MediaContentDirectionHasSend(desc->direction())
347 ? desc->streams()
348 : std::vector<cricket::StreamParams>();
349}
350
deadbeefab9b2d12015-10-14 11:33:11 -0700351bool IsValidOfferToReceiveMedia(int value) {
352 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
353 return (value >= Options::kUndefined) &&
354 (value <= Options::kMaxOfferToReceiveMedia);
355}
356
357// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800358void AddSendStreams(
359 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700360 const std::vector<rtc::scoped_refptr<
361 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800362 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
363 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700364 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800365 for (const auto& sender : senders) {
366 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700367 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700368 }
369
370 // Check for data channels.
371 for (const auto& kv : rtp_data_channels) {
372 const DataChannel* channel = kv.second;
373 if (channel->state() == DataChannel::kConnecting ||
374 channel->state() == DataChannel::kOpen) {
375 // |streamid| and |sync_label| are both set to the DataChannel label
376 // here so they can be signaled the same way as MediaStreams and Tracks.
377 // For MediaStreams, the sync_label is the MediaStream label and the
378 // track label is the same as |streamid|.
379 const std::string& streamid = channel->label();
380 const std::string& sync_label = channel->label();
381 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
382 sync_label);
383 }
384 }
385}
386
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700387uint32_t ConvertIceTransportTypeToCandidateFilter(
388 PeerConnectionInterface::IceTransportsType type) {
389 switch (type) {
390 case PeerConnectionInterface::kNone:
391 return cricket::CF_NONE;
392 case PeerConnectionInterface::kRelay:
393 return cricket::CF_RELAY;
394 case PeerConnectionInterface::kNoHost:
395 return (cricket::CF_ALL & ~cricket::CF_HOST);
396 case PeerConnectionInterface::kAll:
397 return cricket::CF_ALL;
398 default:
399 ASSERT(false);
400 }
401 return cricket::CF_NONE;
402}
403
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700404// Helper method to set a voice/video channel on all applicable senders
405// and receivers when one is created/destroyed by WebRtcSession.
406//
407// Used by On(Voice|Video)Channel(Created|Destroyed)
408template <class SENDER,
409 class RECEIVER,
410 class CHANNEL,
411 class SENDERS,
412 class RECEIVERS>
413void SetChannelOnSendersAndReceivers(CHANNEL* channel,
414 SENDERS& senders,
415 RECEIVERS& receivers,
416 cricket::MediaType media_type) {
417 for (auto& sender : senders) {
418 if (sender->media_type() == media_type) {
419 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
420 }
421 }
422 for (auto& receiver : receivers) {
423 if (receiver->media_type() == media_type) {
424 if (!channel) {
425 receiver->internal()->Stop();
426 }
427 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
428 }
429 }
430}
431
deadbeef0a6c4ca2015-10-06 11:38:28 -0700432} // namespace
433
434namespace webrtc {
435
deadbeef3edec7c2016-12-10 11:44:26 -0800436static const char* const kRtcErrorNames[] = {
437 "NONE",
438 "UNSUPPORTED_PARAMETER",
439 "INVALID_PARAMETER",
440 "INVALID_RANGE",
441 "SYNTAX_ERROR",
442 "INVALID_STATE",
443 "INVALID_MODIFICATION",
444 "NETWORK_ERROR",
445 "INTERNAL_ERROR",
446};
447
448std::ostream& operator<<(std::ostream& stream, RtcError error) {
449 int index = static_cast<int>(error);
450 RTC_CHECK(index < static_cast<int>(sizeof(kRtcErrorNames) /
451 sizeof(kRtcErrorNames[0])));
452 return stream << kRtcErrorNames[index];
453}
454
zhihuang8f65cdf2016-05-06 18:40:30 -0700455// Generate a RTCP CNAME when a PeerConnection is created.
456std::string GenerateRtcpCname() {
457 std::string cname;
458 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
459 LOG(LS_ERROR) << "Failed to generate CNAME.";
460 RTC_DCHECK(false);
461 }
462 return cname;
463}
464
htaa2a49d92016-03-04 02:51:39 -0800465bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700466 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800467 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700468 cricket::MediaSessionOptions* session_options) {
469 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
470 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
471 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
472 return false;
473 }
474
htaaac2dea2016-03-10 13:35:55 -0800475 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700476 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700477 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800478 } else {
479 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700480 }
htaaac2dea2016-03-10 13:35:55 -0800481 // For offers, we only offer video if we have it or it's forced by options.
482 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700483 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700484 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800485 } else if (is_offer) {
486 session_options->recv_video = false;
487 } else {
488 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700489 }
490
491 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700492 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800493 for (auto& kv : session_options->transport_options) {
494 kv.second.ice_restart = rtc_options.ice_restart;
495 }
deadbeefab9b2d12015-10-14 11:33:11 -0700496
497 return true;
498}
499
500bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
501 cricket::MediaSessionOptions* session_options) {
502 bool value = false;
503 size_t mandatory_constraints_satisfied = 0;
504
505 // kOfferToReceiveAudio defaults to true according to spec.
506 if (!FindConstraint(constraints,
507 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
508 &mandatory_constraints_satisfied) ||
509 value) {
510 session_options->recv_audio = true;
511 }
512
513 // kOfferToReceiveVideo defaults to false according to spec. But
514 // if it is an answer and video is offered, we should still accept video
515 // per default.
516 value = false;
517 if (!FindConstraint(constraints,
518 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
519 &mandatory_constraints_satisfied) ||
520 value) {
521 session_options->recv_video = true;
522 }
523
524 if (FindConstraint(constraints,
525 MediaConstraintsInterface::kVoiceActivityDetection, &value,
526 &mandatory_constraints_satisfied)) {
527 session_options->vad_enabled = value;
528 }
529
530 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
531 &mandatory_constraints_satisfied)) {
532 session_options->bundle_enabled = value;
533 } else {
534 // kUseRtpMux defaults to true according to spec.
535 session_options->bundle_enabled = true;
536 }
deadbeefab9b2d12015-10-14 11:33:11 -0700537
deadbeef0ed85b22016-02-23 17:24:52 -0800538 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700539 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
540 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700541 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800542 ice_restart = true;
543 }
544 for (auto& kv : session_options->transport_options) {
545 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700546 }
547
548 if (!constraints) {
549 return true;
550 }
551 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
552}
553
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200554bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800555 cricket::ServerAddresses* stun_servers,
556 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200557 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
558 if (!server.urls.empty()) {
559 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200560 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700561 LOG(LS_ERROR) << "Empty uri.";
562 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200563 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800564 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200565 return false;
566 }
567 }
568 } else if (!server.uri.empty()) {
569 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800570 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000571 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200572 }
573 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700574 LOG(LS_ERROR) << "Empty uri.";
575 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576 }
577 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800578 // Candidates must have unique priorities, so that connectivity checks
579 // are performed in a well-defined order.
580 int priority = static_cast<int>(turn_servers->size() - 1);
581 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
582 // First in the list gets highest priority.
583 turn_server.priority = priority--;
584 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585 return true;
586}
587
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000588PeerConnection::PeerConnection(PeerConnectionFactory* factory)
589 : factory_(factory),
590 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000591 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700594 ice_gathering_state_(kIceGatheringNew),
skvlad11a9cbf2016-10-07 11:53:05 -0700595 event_log_(RtcEventLog::Create(webrtc::Clock::GetRealTimeClock())),
zhihuang8f65cdf2016-05-06 18:40:30 -0700596 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700597 local_streams_(StreamCollection::Create()),
598 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599
600PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100601 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700602 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700603 // Need to detach RTP senders/receivers from WebRtcSession,
604 // since it's about to be destroyed.
605 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700606 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700607 }
608 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700609 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700610 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700611 // Destroy stats_ because it depends on session_.
612 stats_.reset(nullptr);
613 // Now destroy session_ before destroying other members,
614 // because its destruction fires signals (such as VoiceChannelDestroyed)
615 // which will trigger some final actions in PeerConnection...
616 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700617 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700618 network_thread()->Invoke<void>(RTC_FROM_HERE,
619 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000620}
621
622bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000623 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700624 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200625 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800626 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100627 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800628 RTC_DCHECK(observer != nullptr);
629 if (!observer) {
630 return false;
631 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000632 observer_ = observer;
633
kwiberg0eb15ed2015-12-17 03:04:15 -0800634 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800635
deadbeef91dd5672016-05-18 16:55:30 -0700636 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700637 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700638 if (!network_thread()->Invoke<bool>(
639 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
640 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 return false;
642 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643
skvlad11a9cbf2016-10-07 11:53:05 -0700644 media_controller_.reset(factory_->CreateMediaController(
645 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000646
zhihuang29ff8442016-07-27 11:07:25 -0700647 session_.reset(new WebRtcSession(
648 media_controller_.get(), factory_->network_thread(),
649 factory_->worker_thread(), factory_->signaling_thread(),
650 port_allocator_.get(),
651 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700652 factory_->CreateTransportController(
653 port_allocator_.get(),
654 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700655
deadbeefab9b2d12015-10-14 11:33:11 -0700656 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700657 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658
659 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200660 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800661 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700663 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000665 // Register PeerConnection as receiver of local ice candidates.
666 // All the callbacks will be posted to the application from PeerConnection.
667 session_->RegisterIceObserver(this);
668 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700669 session_->SignalVoiceChannelCreated.connect(
670 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700671 session_->SignalVoiceChannelDestroyed.connect(
672 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700673 session_->SignalVideoChannelCreated.connect(
674 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700675 session_->SignalVideoChannelDestroyed.connect(
676 this, &PeerConnection::OnVideoChannelDestroyed);
677 session_->SignalDataChannelCreated.connect(
678 this, &PeerConnection::OnDataChannelCreated);
679 session_->SignalDataChannelDestroyed.connect(
680 this, &PeerConnection::OnDataChannelDestroyed);
681 session_->SignalDataChannelOpenMessage.connect(
682 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800683
684 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 return true;
686}
687
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000688rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700690 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691}
692
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000693rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000694PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700695 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696}
697
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000698bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100699 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 if (IsClosed()) {
701 return false;
702 }
deadbeefab9b2d12015-10-14 11:33:11 -0700703 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 return false;
705 }
deadbeefab9b2d12015-10-14 11:33:11 -0700706
707 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800708 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
709 observer->SignalAudioTrackAdded.connect(this,
710 &PeerConnection::OnAudioTrackAdded);
711 observer->SignalAudioTrackRemoved.connect(
712 this, &PeerConnection::OnAudioTrackRemoved);
713 observer->SignalVideoTrackAdded.connect(this,
714 &PeerConnection::OnVideoTrackAdded);
715 observer->SignalVideoTrackRemoved.connect(
716 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700717 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700718
deadbeefab9b2d12015-10-14 11:33:11 -0700719 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800720 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700721 }
722 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800723 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700724 }
725
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000726 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 observer_->OnRenegotiationNeeded();
728 return true;
729}
730
731void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100732 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700733 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800734 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700735 }
736 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800737 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700738 }
739
740 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800741 stream_observers_.erase(
742 std::remove_if(
743 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700744 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800745 return observer->stream()->label().compare(local_stream->label()) ==
746 0;
747 }),
748 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700749
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750 if (IsClosed()) {
751 return;
752 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753 observer_->OnRenegotiationNeeded();
754}
755
deadbeefe1f9d832016-01-14 15:35:42 -0800756rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
757 MediaStreamTrackInterface* track,
758 std::vector<MediaStreamInterface*> streams) {
759 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
760 if (IsClosed()) {
761 return nullptr;
762 }
763 if (streams.size() >= 2) {
764 LOG(LS_ERROR)
765 << "Adding a track with two streams is not currently supported.";
766 return nullptr;
767 }
768 // TODO(deadbeef): Support adding a track to two different senders.
769 if (FindSenderForTrack(track) != senders_.end()) {
770 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
771 return nullptr;
772 }
773
774 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700775 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800776 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700777 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800778 signaling_thread(),
779 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700780 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800781 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700782 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800783 }
784 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700785 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800786 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700787 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800788 }
789 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700790 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800791 signaling_thread(),
792 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700793 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800794 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700795 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800796 }
797 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700798 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800799 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700800 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800801 }
802 } else {
803 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
804 return rtc::scoped_refptr<RtpSenderInterface>();
805 }
806
807 senders_.push_back(new_sender);
808 observer_->OnRenegotiationNeeded();
809 return new_sender;
810}
811
812bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
813 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
814 if (IsClosed()) {
815 return false;
816 }
817
818 auto it = std::find(senders_.begin(), senders_.end(), sender);
819 if (it == senders_.end()) {
820 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
821 return false;
822 }
deadbeefa601f5c2016-06-06 14:27:39 -0700823 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800824 senders_.erase(it);
825
826 observer_->OnRenegotiationNeeded();
827 return true;
828}
829
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000830rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100832 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700833 if (IsClosed()) {
834 return nullptr;
835 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000836 if (!track) {
837 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
838 return NULL;
839 }
deadbeefab9b2d12015-10-14 11:33:11 -0700840 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
842 return NULL;
843 }
844
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000845 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 DtmfSender::Create(track, signaling_thread(), session_.get()));
847 if (!sender.get()) {
848 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
849 return NULL;
850 }
851 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
852}
853
deadbeeffac06552015-11-25 11:26:01 -0800854rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800855 const std::string& kind,
856 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100857 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700858 if (IsClosed()) {
859 return nullptr;
860 }
deadbeefa601f5c2016-06-06 14:27:39 -0700861 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800862 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700863 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700864 signaling_thread(),
865 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800866 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700867 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700868 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800869 } else {
870 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800871 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800872 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800873 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700874 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800875 }
deadbeeffac06552015-11-25 11:26:01 -0800876 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800877 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800878}
879
deadbeef70ab1a12015-09-28 16:53:55 -0700880std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
881 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700882 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
883 for (const auto& sender : senders_) {
884 ret.push_back(sender.get());
885 }
886 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700887}
888
889std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
890PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700891 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
892 for (const auto& receiver : receivers_) {
893 ret.push_back(receiver.get());
894 }
895 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700896}
897
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000899 MediaStreamTrackInterface* track,
900 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100901 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700902 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000903 if (!VERIFY(observer != NULL)) {
904 LOG(LS_ERROR) << "GetStats - observer is NULL.";
905 return false;
906 }
907
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000908 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700909 // The StatsCollector is used to tell if a track is valid because it may
910 // remember tracks that the PeerConnection previously removed.
911 if (track && !stats_->IsValidTrack(track->id())) {
912 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
913 << track->id();
914 return false;
915 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700916 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000917 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 return true;
919}
920
hbos74e1a4f2016-09-15 23:33:01 -0700921void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
922 RTC_DCHECK(stats_collector_);
923 stats_collector_->GetStatsReport(callback);
924}
925
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
927 return signaling_state_;
928}
929
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930PeerConnectionInterface::IceConnectionState
931PeerConnection::ice_connection_state() {
932 return ice_connection_state_;
933}
934
935PeerConnectionInterface::IceGatheringState
936PeerConnection::ice_gathering_state() {
937 return ice_gathering_state_;
938}
939
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000940rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941PeerConnection::CreateDataChannel(
942 const std::string& label,
943 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100944 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700945#ifdef HAVE_QUIC
946 if (session_->data_channel_type() == cricket::DCT_QUIC) {
947 // TODO(zhihuang): Handle case when config is NULL.
948 if (!config) {
949 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
950 return nullptr;
951 }
952 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
953 if (!config->reliable || config->ordered) {
954 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
955 "ordered delivery.";
956 return nullptr;
957 }
958 return session_->quic_data_transport()->CreateDataChannel(label, config);
959 }
960#endif // HAVE_QUIC
961
deadbeefab9b2d12015-10-14 11:33:11 -0700962 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000963
kwibergd1fe2812016-04-27 06:47:29 -0700964 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000965 if (config) {
966 internal_config.reset(new InternalDataChannelInit(*config));
967 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000968 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700969 InternalCreateDataChannel(label, internal_config.get()));
970 if (!channel.get()) {
971 return nullptr;
972 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000973
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000974 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
975 // the first SCTP DataChannel.
976 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
977 observer_->OnRenegotiationNeeded();
978 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000979
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980 return DataChannelProxy::Create(signaling_thread(), channel.get());
981}
982
983void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
984 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100985 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700986 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
988 return;
989 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000990 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000991
992 bool value;
993 size_t mandatory_constraints = 0;
994
995 if (FindConstraint(constraints,
996 MediaConstraintsInterface::kOfferToReceiveAudio,
997 &value,
998 &mandatory_constraints)) {
999 options.offer_to_receive_audio =
1000 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1001 }
1002
1003 if (FindConstraint(constraints,
1004 MediaConstraintsInterface::kOfferToReceiveVideo,
1005 &value,
1006 &mandatory_constraints)) {
1007 options.offer_to_receive_video =
1008 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1009 }
1010
1011 if (FindConstraint(constraints,
1012 MediaConstraintsInterface::kVoiceActivityDetection,
1013 &value,
1014 &mandatory_constraints)) {
1015 options.voice_activity_detection = value;
1016 }
1017
1018 if (FindConstraint(constraints,
1019 MediaConstraintsInterface::kIceRestart,
1020 &value,
1021 &mandatory_constraints)) {
1022 options.ice_restart = value;
1023 }
1024
1025 if (FindConstraint(constraints,
1026 MediaConstraintsInterface::kUseRtpMux,
1027 &value,
1028 &mandatory_constraints)) {
1029 options.use_rtp_mux = value;
1030 }
1031
1032 CreateOffer(observer, options);
1033}
1034
1035void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1036 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001037 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001038 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001039 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1040 return;
1041 }
deadbeefab9b2d12015-10-14 11:33:11 -07001042
1043 cricket::MediaSessionOptions session_options;
1044 if (!GetOptionsForOffer(options, &session_options)) {
1045 std::string error = "CreateOffer called with invalid options.";
1046 LOG(LS_ERROR) << error;
1047 PostCreateSessionDescriptionFailure(observer, error);
1048 return;
1049 }
1050
1051 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052}
1053
1054void PeerConnection::CreateAnswer(
1055 CreateSessionDescriptionObserver* observer,
1056 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001057 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001058 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1060 return;
1061 }
deadbeefab9b2d12015-10-14 11:33:11 -07001062
1063 cricket::MediaSessionOptions session_options;
1064 if (!GetOptionsForAnswer(constraints, &session_options)) {
1065 std::string error = "CreateAnswer called with invalid constraints.";
1066 LOG(LS_ERROR) << error;
1067 PostCreateSessionDescriptionFailure(observer, error);
1068 return;
1069 }
1070
htaa2a49d92016-03-04 02:51:39 -08001071 session_->CreateAnswer(observer, session_options);
1072}
1073
1074void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1075 const RTCOfferAnswerOptions& options) {
1076 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1077 if (!VERIFY(observer != nullptr)) {
1078 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1079 return;
1080 }
1081
1082 cricket::MediaSessionOptions session_options;
1083 if (!GetOptionsForAnswer(options, &session_options)) {
1084 std::string error = "CreateAnswer called with invalid options.";
1085 LOG(LS_ERROR) << error;
1086 PostCreateSessionDescriptionFailure(observer, error);
1087 return;
1088 }
1089
1090 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091}
1092
1093void PeerConnection::SetLocalDescription(
1094 SetSessionDescriptionObserver* observer,
1095 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001096 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001097 if (IsClosed()) {
1098 return;
1099 }
deadbeefab9b2d12015-10-14 11:33:11 -07001100 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1102 return;
1103 }
1104 if (!desc) {
1105 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1106 return;
1107 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108 // Update stats here so that we have the most recent stats for tracks and
1109 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001110 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001111 std::string error;
1112 if (!session_->SetLocalDescription(desc, &error)) {
1113 PostSetSessionDescriptionFailure(observer, error);
1114 return;
1115 }
deadbeefab9b2d12015-10-14 11:33:11 -07001116
1117 // If setting the description decided our SSL role, allocate any necessary
1118 // SCTP sids.
1119 rtc::SSLRole role;
1120 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001121 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001122 AllocateSctpSids(role);
1123 }
1124
1125 // Update state and SSRC of local MediaStreams and DataChannels based on the
1126 // local session description.
1127 const cricket::ContentInfo* audio_content =
1128 GetFirstAudioContent(desc->description());
1129 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001130 if (audio_content->rejected) {
1131 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1132 } else {
1133 const cricket::AudioContentDescription* audio_desc =
1134 static_cast<const cricket::AudioContentDescription*>(
1135 audio_content->description);
1136 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1137 }
deadbeefab9b2d12015-10-14 11:33:11 -07001138 }
1139
1140 const cricket::ContentInfo* video_content =
1141 GetFirstVideoContent(desc->description());
1142 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001143 if (video_content->rejected) {
1144 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1145 } else {
1146 const cricket::VideoContentDescription* video_desc =
1147 static_cast<const cricket::VideoContentDescription*>(
1148 video_content->description);
1149 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1150 }
deadbeefab9b2d12015-10-14 11:33:11 -07001151 }
1152
1153 const cricket::ContentInfo* data_content =
1154 GetFirstDataContent(desc->description());
1155 if (data_content) {
1156 const cricket::DataContentDescription* data_desc =
1157 static_cast<const cricket::DataContentDescription*>(
1158 data_content->description);
1159 if (rtc::starts_with(data_desc->protocol().data(),
1160 cricket::kMediaProtocolRtpPrefix)) {
1161 UpdateLocalRtpDataChannels(data_desc->streams());
1162 }
1163 }
1164
1165 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001166 signaling_thread()->Post(RTC_FROM_HERE, this,
1167 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001168
deadbeefcbecd352015-09-23 11:50:27 -07001169 // MaybeStartGathering needs to be called after posting
1170 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1171 // before signaling that SetLocalDescription completed.
1172 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173}
1174
1175void PeerConnection::SetRemoteDescription(
1176 SetSessionDescriptionObserver* observer,
1177 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001178 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001179 if (IsClosed()) {
1180 return;
1181 }
deadbeefab9b2d12015-10-14 11:33:11 -07001182 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1184 return;
1185 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186 if (!desc) {
1187 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1188 return;
1189 }
1190 // Update stats here so that we have the most recent stats for tracks and
1191 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001192 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193 std::string error;
1194 if (!session_->SetRemoteDescription(desc, &error)) {
1195 PostSetSessionDescriptionFailure(observer, error);
1196 return;
1197 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001198
deadbeefab9b2d12015-10-14 11:33:11 -07001199 // If setting the description decided our SSL role, allocate any necessary
1200 // SCTP sids.
1201 rtc::SSLRole role;
1202 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001203 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001204 AllocateSctpSids(role);
1205 }
1206
1207 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001208 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1209 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1210 const cricket::AudioContentDescription* audio_desc =
1211 GetFirstAudioContentDescription(remote_desc);
1212 const cricket::VideoContentDescription* video_desc =
1213 GetFirstVideoContentDescription(remote_desc);
1214 const cricket::DataContentDescription* data_desc =
1215 GetFirstDataContentDescription(remote_desc);
1216
1217 // Check if the descriptions include streams, just in case the peer supports
1218 // MSID, but doesn't indicate so with "a=msid-semantic".
1219 if (remote_desc->msid_supported() ||
1220 (audio_desc && !audio_desc->streams().empty()) ||
1221 (video_desc && !video_desc->streams().empty())) {
1222 remote_peer_supports_msid_ = true;
1223 }
deadbeefab9b2d12015-10-14 11:33:11 -07001224
1225 // We wait to signal new streams until we finish processing the description,
1226 // since only at that point will new streams have all their tracks.
1227 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1228
1229 // Find all audio rtp streams and create corresponding remote AudioTracks
1230 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001231 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001232 if (audio_content->rejected) {
1233 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1234 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001235 bool default_audio_track_needed =
1236 !remote_peer_supports_msid_ &&
1237 MediaContentDirectionHasSend(audio_desc->direction());
1238 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1239 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001240 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001241 }
deadbeefab9b2d12015-10-14 11:33:11 -07001242 }
1243
1244 // Find all video rtp streams and create corresponding remote VideoTracks
1245 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001246 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001247 if (video_content->rejected) {
1248 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1249 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001250 bool default_video_track_needed =
1251 !remote_peer_supports_msid_ &&
1252 MediaContentDirectionHasSend(video_desc->direction());
1253 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1254 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001255 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001256 }
deadbeefab9b2d12015-10-14 11:33:11 -07001257 }
1258
1259 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001260 if (data_desc) {
1261 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001262 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001263 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001264 }
1265 }
1266
1267 // Iterate new_streams and notify the observer about new MediaStreams.
1268 for (size_t i = 0; i < new_streams->count(); ++i) {
1269 MediaStreamInterface* new_stream = new_streams->at(i);
1270 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001271 // Call both the raw pointer and scoped_refptr versions of the method
1272 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001273 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001274 observer_->OnAddStream(
1275 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001276 }
1277
deadbeefbda7e0b2015-12-08 17:13:40 -08001278 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001279
1280 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001281 signaling_thread()->Post(RTC_FROM_HERE, this,
1282 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001283}
1284
deadbeef46c73892016-11-16 19:42:04 -08001285PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1286 return configuration_;
1287}
1288
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001289bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001290 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef46c73892016-11-16 19:42:04 -08001291 // TODO(deadbeef): Return false and log an error if there are any unsupported
1292 // modifications.
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001293 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001294 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001295 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001296 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001297 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001298 return false;
1299 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001300 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001301
deadbeefd1a38b52016-12-10 13:15:33 -08001302 // TODO(deadbeef): Shouldn't have to hop to the network thread twice...
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001303 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001304
deadbeefd1a38b52016-12-10 13:15:33 -08001305 // As described in JSEP, calling setConfiguration with new ICE servers or
1306 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1307 // triggers an ICE restart which will pick up the changes.
1308 if (configuration.servers != configuration_.servers ||
1309 configuration.type != configuration_.type) {
1310 session_->SetNeedsIceRestartFlag();
1311 }
deadbeef46c73892016-11-16 19:42:04 -08001312 configuration_ = configuration;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001313 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001314}
1315
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316bool PeerConnection::AddIceCandidate(
1317 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001318 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001319 if (IsClosed()) {
1320 return false;
1321 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 return session_->ProcessIceMessage(ice_candidate);
1323}
1324
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001325bool PeerConnection::RemoveIceCandidates(
1326 const std::vector<cricket::Candidate>& candidates) {
1327 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1328 return session_->RemoveRemoteIceCandidates(candidates);
1329}
1330
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001331void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001332 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001333 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001334
1335 if (session_) {
1336 session_->set_metrics_observer(uma_observer_);
1337 }
1338
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001339 // Send information about IPv4/IPv6 status.
1340 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001341 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001342 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001343 uma_observer_->IncrementEnumCounter(
1344 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1345 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001346 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001347 uma_observer_->IncrementEnumCounter(
1348 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1349 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001350 }
1351 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001352}
1353
ivoc14d5dbe2016-07-04 07:06:55 -07001354bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1355 int64_t max_size_bytes) {
1356 return factory_->worker_thread()->Invoke<bool>(
1357 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1358 max_size_bytes));
1359}
1360
1361void PeerConnection::StopRtcEventLog() {
1362 factory_->worker_thread()->Invoke<void>(
1363 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1364}
1365
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366const SessionDescriptionInterface* PeerConnection::local_description() const {
1367 return session_->local_description();
1368}
1369
1370const SessionDescriptionInterface* PeerConnection::remote_description() const {
1371 return session_->remote_description();
1372}
1373
1374void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001375 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376 // Update stats here so that we have the most recent stats for tracks and
1377 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001378 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379
deadbeefd59daf82015-10-14 15:02:44 -07001380 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381}
1382
deadbeefd59daf82015-10-14 15:02:44 -07001383void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1384 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001386 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001388 break;
deadbeefd59daf82015-10-14 15:02:44 -07001389 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1391 break;
deadbeefd59daf82015-10-14 15:02:44 -07001392 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1394 break;
deadbeefd59daf82015-10-14 15:02:44 -07001395 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1397 break;
deadbeefd59daf82015-10-14 15:02:44 -07001398 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001399 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1400 break;
deadbeefd59daf82015-10-14 15:02:44 -07001401 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402 ChangeSignalingState(PeerConnectionInterface::kStable);
1403 break;
deadbeefd59daf82015-10-14 15:02:44 -07001404 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405 ChangeSignalingState(PeerConnectionInterface::kClosed);
1406 break;
1407 default:
1408 break;
1409 }
1410}
1411
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001412void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1415 SetSessionDescriptionMsg* param =
1416 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1417 param->observer->OnSuccess();
1418 delete param;
1419 break;
1420 }
1421 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1422 SetSessionDescriptionMsg* param =
1423 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1424 param->observer->OnFailure(param->error);
1425 delete param;
1426 break;
1427 }
deadbeefab9b2d12015-10-14 11:33:11 -07001428 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1429 CreateSessionDescriptionMsg* param =
1430 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1431 param->observer->OnFailure(param->error);
1432 delete param;
1433 break;
1434 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435 case MSG_GETSTATS: {
1436 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001437 StatsReports reports;
1438 stats_->GetStats(param->track, &reports);
1439 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 delete param;
1441 break;
1442 }
deadbeefbd292462015-12-14 18:15:29 -08001443 case MSG_FREE_DATACHANNELS: {
1444 sctp_data_channels_to_free_.clear();
1445 break;
1446 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001448 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449 break;
1450 }
1451}
1452
deadbeefab9b2d12015-10-14 11:33:11 -07001453void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001454 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001455 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001456 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1457 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001458 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001459 session_->voice_channel()));
1460
1461 receivers_.push_back(receiver);
1462 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1463 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1464 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465}
1466
deadbeefab9b2d12015-10-14 11:33:11 -07001467void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001468 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001469 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001470 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1471 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001472 signaling_thread(),
1473 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001474 ssrc, session_->video_channel()));
1475 receivers_.push_back(receiver);
1476 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1477 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1478 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479}
1480
deadbeef70ab1a12015-09-28 16:53:55 -07001481// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1482// description.
perkjd61bf802016-03-24 03:16:19 -07001483void PeerConnection::DestroyReceiver(const std::string& track_id) {
1484 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001485 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001486 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001487 << " doesn't exist.";
1488 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001489 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001490 receivers_.erase(it);
1491 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001492}
1493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494void PeerConnection::OnIceConnectionChange(
1495 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001496 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001497 // After transitioning to "closed", ignore any additional states from
1498 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001499 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001500 return;
1501 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001502 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001503 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001504}
1505
1506void PeerConnection::OnIceGatheringChange(
1507 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001508 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 if (IsClosed()) {
1510 return;
1511 }
1512 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001513 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514}
1515
1516void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001517 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001518 if (IsClosed()) {
1519 return;
1520 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001521 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522}
1523
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001524void PeerConnection::OnIceCandidatesRemoved(
1525 const std::vector<cricket::Candidate>& candidates) {
1526 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001527 if (IsClosed()) {
1528 return;
1529 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001530 observer_->OnIceCandidatesRemoved(candidates);
1531}
1532
Peter Thatcher54360512015-07-08 11:08:35 -07001533void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001534 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001535 if (IsClosed()) {
1536 return;
1537 }
Peter Thatcher54360512015-07-08 11:08:35 -07001538 observer_->OnIceConnectionReceivingChange(receiving);
1539}
1540
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001541void PeerConnection::ChangeSignalingState(
1542 PeerConnectionInterface::SignalingState signaling_state) {
1543 signaling_state_ = signaling_state;
1544 if (signaling_state == kClosed) {
1545 ice_connection_state_ = kIceConnectionClosed;
1546 observer_->OnIceConnectionChange(ice_connection_state_);
1547 if (ice_gathering_state_ != kIceGatheringComplete) {
1548 ice_gathering_state_ = kIceGatheringComplete;
1549 observer_->OnIceGatheringChange(ice_gathering_state_);
1550 }
1551 }
1552 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001553}
1554
deadbeefeb459812015-12-15 19:24:43 -08001555void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1556 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001557 if (IsClosed()) {
1558 return;
1559 }
deadbeefeb459812015-12-15 19:24:43 -08001560 auto sender = FindSenderForTrack(track);
1561 if (sender != senders_.end()) {
1562 // We already have a sender for this track, so just change the stream_id
1563 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001564 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001565 return;
1566 }
1567
1568 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001569 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1570 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001571 signaling_thread(),
1572 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1573 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001574 senders_.push_back(new_sender);
1575 // If the sender has already been configured in SDP, we call SetSsrc,
1576 // which will connect the sender to the underlying transport. This can
1577 // occur if a local session description that contains the ID of the sender
1578 // is set before AddStream is called. It can also occur if the local
1579 // session description is not changed and RemoveStream is called, and
1580 // later AddStream is called again with the same stream.
1581 const TrackInfo* track_info =
1582 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1583 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001584 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001585 }
1586}
1587
1588// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1589// indefinitely, when we have unified plan SDP.
1590void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1591 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001592 if (IsClosed()) {
1593 return;
1594 }
deadbeefeb459812015-12-15 19:24:43 -08001595 auto sender = FindSenderForTrack(track);
1596 if (sender == senders_.end()) {
1597 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1598 << " doesn't exist.";
1599 return;
1600 }
deadbeefa601f5c2016-06-06 14:27:39 -07001601 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001602 senders_.erase(sender);
1603}
1604
1605void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1606 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001607 if (IsClosed()) {
1608 return;
1609 }
deadbeefeb459812015-12-15 19:24:43 -08001610 auto sender = FindSenderForTrack(track);
1611 if (sender != senders_.end()) {
1612 // We already have a sender for this track, so just change the stream_id
1613 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001614 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001615 return;
1616 }
1617
1618 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001619 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1620 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001621 signaling_thread(), new VideoRtpSender(track, stream->label(),
1622 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001623 senders_.push_back(new_sender);
1624 const TrackInfo* track_info =
1625 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1626 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001627 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001628 }
1629}
1630
1631void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1632 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001633 if (IsClosed()) {
1634 return;
1635 }
deadbeefeb459812015-12-15 19:24:43 -08001636 auto sender = FindSenderForTrack(track);
1637 if (sender == senders_.end()) {
1638 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1639 << " doesn't exist.";
1640 return;
1641 }
deadbeefa601f5c2016-06-06 14:27:39 -07001642 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001643 senders_.erase(sender);
1644}
1645
deadbeefab9b2d12015-10-14 11:33:11 -07001646void PeerConnection::PostSetSessionDescriptionFailure(
1647 SetSessionDescriptionObserver* observer,
1648 const std::string& error) {
1649 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1650 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001651 signaling_thread()->Post(RTC_FROM_HERE, this,
1652 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001653}
1654
1655void PeerConnection::PostCreateSessionDescriptionFailure(
1656 CreateSessionDescriptionObserver* observer,
1657 const std::string& error) {
1658 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1659 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001660 signaling_thread()->Post(RTC_FROM_HERE, this,
1661 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001662}
1663
1664bool PeerConnection::GetOptionsForOffer(
1665 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1666 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001667 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1668 // ContentInfos.
1669 if (session_->local_description()) {
1670 for (const cricket::ContentInfo& content :
1671 session_->local_description()->description()->contents()) {
1672 session_options->transport_options[content.name] =
1673 cricket::TransportOptions();
1674 }
1675 }
deadbeef46c73892016-11-16 19:42:04 -08001676 session_options->enable_ice_renomination =
1677 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001678
htaaac2dea2016-03-10 13:35:55 -08001679 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001680 return false;
1681 }
1682
deadbeeffac06552015-11-25 11:26:01 -08001683 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001684 // Offer to receive audio/video if the constraint is not set and there are
1685 // send streams, or we're currently receiving.
1686 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1687 session_options->recv_audio =
1688 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1689 !remote_audio_tracks_.empty();
1690 }
1691 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1692 session_options->recv_video =
1693 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1694 !remote_video_tracks_.empty();
1695 }
deadbeefc80741f2015-10-22 13:14:45 -07001696
zhihuang9763d562016-08-05 11:14:50 -07001697 // Intentionally unset the data channel type for RTP data channel with the
1698 // second condition. Otherwise the RTP data channels would be successfully
1699 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1700 // when building with chromium. We want to leave RTP data channels broken, so
1701 // people won't try to use them.
1702 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1703 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001704 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001705
zhihuangaf388472016-11-02 16:49:48 -07001706 session_options->bundle_enabled =
1707 session_options->bundle_enabled &&
1708 (session_options->has_audio() || session_options->has_video() ||
1709 session_options->has_data());
1710
zhihuang8f65cdf2016-05-06 18:40:30 -07001711 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001712 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001713 return true;
1714}
1715
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001716void PeerConnection::InitializeOptionsForAnswer(
1717 cricket::MediaSessionOptions* session_options) {
1718 session_options->recv_audio = false;
1719 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001720 session_options->enable_ice_renomination =
1721 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001722}
1723
htaa2a49d92016-03-04 02:51:39 -08001724void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001725 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001726 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1727 // ContentInfos.
1728 if (session_->remote_description()) {
1729 // Initialize the transport_options map.
1730 for (const cricket::ContentInfo& content :
1731 session_->remote_description()->description()->contents()) {
1732 session_options->transport_options[content.name] =
1733 cricket::TransportOptions();
1734 }
1735 }
deadbeeffac06552015-11-25 11:26:01 -08001736 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001737 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1738 // are not signaled in the SDP so does not go through that path and must be
1739 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001740 // Intentionally unset the data channel type for RTP data channel. Otherwise
1741 // the RTP data channels would be successfully negotiated by default and the
1742 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1743 // We want to leave RTP data channels broken, so people won't try to use them.
1744 if (session_->data_channel_type() != cricket::DCT_RTP) {
1745 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001746 }
zhihuangaf388472016-11-02 16:49:48 -07001747 session_options->bundle_enabled =
1748 session_options->bundle_enabled &&
1749 (session_options->has_audio() || session_options->has_video() ||
1750 session_options->has_data());
1751
jbauchcb560652016-08-04 05:20:32 -07001752 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001753}
1754
1755bool PeerConnection::GetOptionsForAnswer(
1756 const MediaConstraintsInterface* constraints,
1757 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001758 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001759 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1760 return false;
1761 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001762 session_options->rtcp_cname = rtcp_cname_;
1763
htaa2a49d92016-03-04 02:51:39 -08001764 FinishOptionsForAnswer(session_options);
1765 return true;
1766}
1767
1768bool PeerConnection::GetOptionsForAnswer(
1769 const RTCOfferAnswerOptions& options,
1770 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001771 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001772 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001773 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);
deadbeefab9b2d12015-10-14 11:33:11 -07001778 return true;
1779}
1780
deadbeeffaac4972015-11-12 15:33:07 -08001781void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1782 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001783 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1784 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001785}
1786
deadbeefab9b2d12015-10-14 11:33:11 -07001787void PeerConnection::UpdateRemoteStreamsList(
1788 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001789 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001790 cricket::MediaType media_type,
1791 StreamCollection* new_streams) {
1792 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1793
1794 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001795 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001796 auto track_it = current_tracks->begin();
1797 while (track_it != current_tracks->end()) {
1798 const TrackInfo& info = *track_it;
1799 const cricket::StreamParams* params =
1800 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001801 bool track_exists = params && params->id == info.track_id;
1802 // If this is a default track, and we still need it, don't remove it.
1803 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1804 track_exists) {
1805 ++track_it;
1806 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001807 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1808 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001809 }
1810 }
1811
1812 // Find new and active tracks.
1813 for (const cricket::StreamParams& params : streams) {
1814 // The sync_label is the MediaStream label and the |stream.id| is the
1815 // track id.
1816 const std::string& stream_label = params.sync_label;
1817 const std::string& track_id = params.id;
1818 uint32_t ssrc = params.first_ssrc();
1819
1820 rtc::scoped_refptr<MediaStreamInterface> stream =
1821 remote_streams_->find(stream_label);
1822 if (!stream) {
1823 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001824 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1825 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001826 remote_streams_->AddStream(stream);
1827 new_streams->AddStream(stream);
1828 }
1829
1830 const TrackInfo* track_info =
1831 FindTrackInfo(*current_tracks, stream_label, track_id);
1832 if (!track_info) {
1833 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1834 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1835 }
1836 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001837
1838 // Add default track if necessary.
1839 if (default_track_needed) {
1840 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1841 remote_streams_->find(kDefaultStreamLabel);
1842 if (!default_stream) {
1843 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001844 default_stream = MediaStreamProxy::Create(
1845 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001846 remote_streams_->AddStream(default_stream);
1847 new_streams->AddStream(default_stream);
1848 }
1849 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1850 ? kDefaultAudioTrackLabel
1851 : kDefaultVideoTrackLabel;
1852 const TrackInfo* default_track_info =
1853 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1854 if (!default_track_info) {
1855 current_tracks->push_back(
1856 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1857 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1858 }
1859 }
deadbeefab9b2d12015-10-14 11:33:11 -07001860}
1861
1862void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1863 const std::string& track_id,
1864 uint32_t ssrc,
1865 cricket::MediaType media_type) {
1866 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1867
1868 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001869 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001870 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001871 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001872 } else {
1873 RTC_DCHECK(false && "Invalid media type");
1874 }
1875}
1876
1877void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1878 const std::string& track_id,
1879 cricket::MediaType media_type) {
1880 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1881
1882 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001883 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1884 // will be notified which will end the AudioRtpReceiver::track().
1885 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001886 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1887 stream->FindAudioTrack(track_id);
1888 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001889 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001890 }
1891 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001892 // Stopping or destroying a VideoRtpReceiver will end the
1893 // VideoRtpReceiver::track().
1894 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001895 rtc::scoped_refptr<VideoTrackInterface> video_track =
1896 stream->FindVideoTrack(track_id);
1897 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001898 // There's no guarantee the track is still available, e.g. the track may
1899 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001900 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001901 }
1902 } else {
1903 ASSERT(false && "Invalid media type");
1904 }
1905}
1906
1907void PeerConnection::UpdateEndedRemoteMediaStreams() {
1908 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1909 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1910 MediaStreamInterface* stream = remote_streams_->at(i);
1911 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1912 streams_to_remove.push_back(stream);
1913 }
1914 }
1915
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001916 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001917 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001918 // Call both the raw pointer and scoped_refptr versions of the method
1919 // for compatibility.
1920 observer_->OnRemoveStream(stream.get());
1921 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001922 }
1923}
1924
deadbeefab9b2d12015-10-14 11:33:11 -07001925void PeerConnection::UpdateLocalTracks(
1926 const std::vector<cricket::StreamParams>& streams,
1927 cricket::MediaType media_type) {
1928 TrackInfos* current_tracks = GetLocalTracks(media_type);
1929
1930 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1931 // don't match the new StreamParam.
1932 TrackInfos::iterator track_it = current_tracks->begin();
1933 while (track_it != current_tracks->end()) {
1934 const TrackInfo& info = *track_it;
1935 const cricket::StreamParams* params =
1936 cricket::GetStreamBySsrc(streams, info.ssrc);
1937 if (!params || params->id != info.track_id ||
1938 params->sync_label != info.stream_label) {
1939 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1940 media_type);
1941 track_it = current_tracks->erase(track_it);
1942 } else {
1943 ++track_it;
1944 }
1945 }
1946
1947 // Find new and active tracks.
1948 for (const cricket::StreamParams& params : streams) {
1949 // The sync_label is the MediaStream label and the |stream.id| is the
1950 // track id.
1951 const std::string& stream_label = params.sync_label;
1952 const std::string& track_id = params.id;
1953 uint32_t ssrc = params.first_ssrc();
1954 const TrackInfo* track_info =
1955 FindTrackInfo(*current_tracks, stream_label, track_id);
1956 if (!track_info) {
1957 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1958 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1959 }
1960 }
1961}
1962
1963void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1964 const std::string& track_id,
1965 uint32_t ssrc,
1966 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001967 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001968 if (!sender) {
1969 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1970 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001971 return;
1972 }
1973
deadbeeffac06552015-11-25 11:26:01 -08001974 if (sender->media_type() != media_type) {
1975 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1976 << " description with an unexpected media type.";
1977 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001978 }
deadbeeffac06552015-11-25 11:26:01 -08001979
1980 sender->set_stream_id(stream_label);
1981 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001982}
1983
1984void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1985 const std::string& track_id,
1986 uint32_t ssrc,
1987 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001988 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001989 if (!sender) {
1990 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001991 // SessionDescriptions has been renegotiated.
1992 return;
1993 }
deadbeeffac06552015-11-25 11:26:01 -08001994
1995 // A sender has been removed from the SessionDescription but it's still
1996 // associated with the PeerConnection. This only occurs if the SDP doesn't
1997 // match with the calls to CreateSender, AddStream and RemoveStream.
1998 if (sender->media_type() != media_type) {
1999 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2000 << " description with an unexpected media type.";
2001 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002002 }
deadbeeffac06552015-11-25 11:26:01 -08002003
2004 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002005}
2006
2007void PeerConnection::UpdateLocalRtpDataChannels(
2008 const cricket::StreamParamsVec& streams) {
2009 std::vector<std::string> existing_channels;
2010
2011 // Find new and active data channels.
2012 for (const cricket::StreamParams& params : streams) {
2013 // |it->sync_label| is actually the data channel label. The reason is that
2014 // we use the same naming of data channels as we do for
2015 // MediaStreams and Tracks.
2016 // For MediaStreams, the sync_label is the MediaStream label and the
2017 // track label is the same as |streamid|.
2018 const std::string& channel_label = params.sync_label;
2019 auto data_channel_it = rtp_data_channels_.find(channel_label);
2020 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
2021 continue;
2022 }
2023 // Set the SSRC the data channel should use for sending.
2024 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2025 existing_channels.push_back(data_channel_it->first);
2026 }
2027
2028 UpdateClosingRtpDataChannels(existing_channels, true);
2029}
2030
2031void PeerConnection::UpdateRemoteRtpDataChannels(
2032 const cricket::StreamParamsVec& streams) {
2033 std::vector<std::string> existing_channels;
2034
2035 // Find new and active data channels.
2036 for (const cricket::StreamParams& params : streams) {
2037 // The data channel label is either the mslabel or the SSRC if the mslabel
2038 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2039 std::string label = params.sync_label.empty()
2040 ? rtc::ToString(params.first_ssrc())
2041 : params.sync_label;
2042 auto data_channel_it = rtp_data_channels_.find(label);
2043 if (data_channel_it == rtp_data_channels_.end()) {
2044 // This is a new data channel.
2045 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2046 } else {
2047 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2048 }
2049 existing_channels.push_back(label);
2050 }
2051
2052 UpdateClosingRtpDataChannels(existing_channels, false);
2053}
2054
2055void PeerConnection::UpdateClosingRtpDataChannels(
2056 const std::vector<std::string>& active_channels,
2057 bool is_local_update) {
2058 auto it = rtp_data_channels_.begin();
2059 while (it != rtp_data_channels_.end()) {
2060 DataChannel* data_channel = it->second;
2061 if (std::find(active_channels.begin(), active_channels.end(),
2062 data_channel->label()) != active_channels.end()) {
2063 ++it;
2064 continue;
2065 }
2066
2067 if (is_local_update) {
2068 data_channel->SetSendSsrc(0);
2069 } else {
2070 data_channel->RemotePeerRequestClose();
2071 }
2072
2073 if (data_channel->state() == DataChannel::kClosed) {
2074 rtp_data_channels_.erase(it);
2075 it = rtp_data_channels_.begin();
2076 } else {
2077 ++it;
2078 }
2079 }
2080}
2081
2082void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2083 uint32_t remote_ssrc) {
2084 rtc::scoped_refptr<DataChannel> channel(
2085 InternalCreateDataChannel(label, nullptr));
2086 if (!channel.get()) {
2087 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2088 << "CreateDataChannel failed.";
2089 return;
2090 }
2091 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002092 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2093 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002094 // Call both the raw pointer and scoped_refptr versions of the method
2095 // for compatibility.
2096 observer_->OnDataChannel(proxy_channel.get());
2097 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002098}
2099
2100rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2101 const std::string& label,
2102 const InternalDataChannelInit* config) {
2103 if (IsClosed()) {
2104 return nullptr;
2105 }
2106 if (session_->data_channel_type() == cricket::DCT_NONE) {
2107 LOG(LS_ERROR)
2108 << "InternalCreateDataChannel: Data is not supported in this call.";
2109 return nullptr;
2110 }
2111 InternalDataChannelInit new_config =
2112 config ? (*config) : InternalDataChannelInit();
2113 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2114 if (new_config.id < 0) {
2115 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002116 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002117 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2118 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2119 return nullptr;
2120 }
2121 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2122 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2123 << "because the id is already in use or out of range.";
2124 return nullptr;
2125 }
2126 }
2127
2128 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2129 session_.get(), session_->data_channel_type(), label, new_config));
2130 if (!channel) {
2131 sid_allocator_.ReleaseSid(new_config.id);
2132 return nullptr;
2133 }
2134
2135 if (channel->data_channel_type() == cricket::DCT_RTP) {
2136 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2137 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2138 << " already exists.";
2139 return nullptr;
2140 }
2141 rtp_data_channels_[channel->label()] = channel;
2142 } else {
2143 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2144 sctp_data_channels_.push_back(channel);
2145 channel->SignalClosed.connect(this,
2146 &PeerConnection::OnSctpDataChannelClosed);
2147 }
2148
hbos82ebe022016-11-14 01:41:09 -08002149 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002150 return channel;
2151}
2152
2153bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002154#ifdef HAVE_QUIC
2155 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2156 (session_->quic_data_transport() &&
2157 session_->quic_data_transport()->HasDataChannels());
2158#else
deadbeefab9b2d12015-10-14 11:33:11 -07002159 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002160#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002161}
2162
2163void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2164 for (const auto& channel : sctp_data_channels_) {
2165 if (channel->id() < 0) {
2166 int sid;
2167 if (!sid_allocator_.AllocateSid(role, &sid)) {
2168 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2169 continue;
2170 }
2171 channel->SetSctpSid(sid);
2172 }
2173 }
2174}
2175
2176void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002177 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002178 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2179 ++it) {
2180 if (it->get() == channel) {
2181 if (channel->id() >= 0) {
2182 sid_allocator_.ReleaseSid(channel->id());
2183 }
deadbeefbd292462015-12-14 18:15:29 -08002184 // Since this method is triggered by a signal from the DataChannel,
2185 // we can't free it directly here; we need to free it asynchronously.
2186 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002187 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002188 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2189 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002190 return;
2191 }
2192 }
2193}
2194
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002195void PeerConnection::OnVoiceChannelCreated() {
2196 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2197 session_->voice_channel(), senders_, receivers_,
2198 cricket::MEDIA_TYPE_AUDIO);
2199}
2200
deadbeefab9b2d12015-10-14 11:33:11 -07002201void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002202 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2203 cricket::VoiceChannel>(
2204 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2205}
2206
2207void PeerConnection::OnVideoChannelCreated() {
2208 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2209 session_->video_channel(), senders_, receivers_,
2210 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002211}
2212
2213void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002214 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2215 cricket::VideoChannel>(
2216 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002217}
2218
2219void PeerConnection::OnDataChannelCreated() {
2220 for (const auto& channel : sctp_data_channels_) {
2221 channel->OnTransportChannelCreated();
2222 }
2223}
2224
2225void PeerConnection::OnDataChannelDestroyed() {
2226 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2227 // DataChannel may callback to us and try to modify the list.
2228 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2229 temp_rtp_dcs.swap(rtp_data_channels_);
2230 for (const auto& kv : temp_rtp_dcs) {
2231 kv.second->OnTransportChannelDestroyed();
2232 }
2233
2234 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2235 temp_sctp_dcs.swap(sctp_data_channels_);
2236 for (const auto& channel : temp_sctp_dcs) {
2237 channel->OnTransportChannelDestroyed();
2238 }
2239}
2240
2241void PeerConnection::OnDataChannelOpenMessage(
2242 const std::string& label,
2243 const InternalDataChannelInit& config) {
2244 rtc::scoped_refptr<DataChannel> channel(
2245 InternalCreateDataChannel(label, &config));
2246 if (!channel.get()) {
2247 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2248 return;
2249 }
2250
deadbeefa601f5c2016-06-06 14:27:39 -07002251 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2252 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002253 // Call both the raw pointer and scoped_refptr versions of the method
2254 // for compatibility.
2255 observer_->OnDataChannel(proxy_channel.get());
2256 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002257}
2258
deadbeefa601f5c2016-06-06 14:27:39 -07002259RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2260 auto it = std::find_if(
2261 senders_.begin(), senders_.end(),
2262 [id](const rtc::scoped_refptr<
2263 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2264 return sender->id() == id;
2265 });
2266 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002267}
2268
deadbeefa601f5c2016-06-06 14:27:39 -07002269std::vector<
2270 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002271PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2272 return std::find_if(
2273 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002274 [track](const rtc::scoped_refptr<
2275 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002276 return sender->track() == track;
2277 });
2278}
2279
deadbeefa601f5c2016-06-06 14:27:39 -07002280std::vector<rtc::scoped_refptr<
2281 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002282PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002283 return std::find_if(
2284 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002285 [track_id](const rtc::scoped_refptr<
2286 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002287 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002288 });
2289}
2290
deadbeefab9b2d12015-10-14 11:33:11 -07002291PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2292 cricket::MediaType media_type) {
2293 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2294 media_type == cricket::MEDIA_TYPE_VIDEO);
2295 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2296 : &remote_video_tracks_;
2297}
2298
2299PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2300 cricket::MediaType media_type) {
2301 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2302 media_type == cricket::MEDIA_TYPE_VIDEO);
2303 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2304 : &local_video_tracks_;
2305}
2306
2307const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2308 const PeerConnection::TrackInfos& infos,
2309 const std::string& stream_label,
2310 const std::string track_id) const {
2311 for (const TrackInfo& track_info : infos) {
2312 if (track_info.stream_label == stream_label &&
2313 track_info.track_id == track_id) {
2314 return &track_info;
2315 }
2316 }
2317 return nullptr;
2318}
2319
2320DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2321 for (const auto& channel : sctp_data_channels_) {
2322 if (channel->id() == sid) {
2323 return channel;
2324 }
2325 }
2326 return nullptr;
2327}
2328
deadbeef91dd5672016-05-18 16:55:30 -07002329bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002330 const RTCConfiguration& configuration) {
2331 cricket::ServerAddresses stun_servers;
2332 std::vector<cricket::RelayServerConfig> turn_servers;
2333 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2334 return false;
2335 }
2336
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002337 port_allocator_->Initialize();
2338
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002339 // To handle both internal and externally created port allocator, we will
2340 // enable BUNDLE here.
2341 int portallocator_flags = port_allocator_->flags();
2342 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2343 cricket::PORTALLOCATOR_ENABLE_IPV6;
2344 // If the disable-IPv6 flag was specified, we'll not override it
2345 // by experiment.
2346 if (configuration.disable_ipv6) {
2347 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2348 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2349 "Disabled") {
2350 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2351 }
2352
2353 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2354 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2355 LOG(LS_INFO) << "TCP candidates are disabled.";
2356 }
2357
honghaiz60347052016-05-31 18:29:12 -07002358 if (configuration.candidate_network_policy ==
2359 kCandidateNetworkPolicyLowCost) {
2360 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2361 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2362 }
2363
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002364 port_allocator_->set_flags(portallocator_flags);
2365 // No step delay is used while allocating ports.
2366 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2367 port_allocator_->set_candidate_filter(
2368 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2369
2370 // Call this last since it may create pooled allocator sessions using the
2371 // properties set above.
2372 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002373 configuration.ice_candidate_pool_size,
2374 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002375 return true;
2376}
2377
deadbeef91dd5672016-05-18 16:55:30 -07002378bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002379 const RTCConfiguration& configuration) {
2380 cricket::ServerAddresses stun_servers;
2381 std::vector<cricket::RelayServerConfig> turn_servers;
2382 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2383 return false;
2384 }
2385 port_allocator_->set_candidate_filter(
2386 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2387 // Call this last since it may create pooled allocator sessions using the
2388 // candidate filter set above.
2389 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002390 configuration.ice_candidate_pool_size,
2391 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002392 return true;
2393}
2394
ivoc14d5dbe2016-07-04 07:06:55 -07002395bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2396 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002397 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002398}
2399
2400void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002401 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002402}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002403} // namespace webrtc