blob: a1ce6ab05c02df6eabae0da39d1e7dac0de21a75 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070037#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010038#include "webrtc/base/trace_event.h"
ivoc14d5dbe2016-07-04 07:06:55 -070039#include "webrtc/call.h"
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());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200234 rtc::tokenize(url, '?', &tokens);
235 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];
239 rtc::tokenize(uri_transport_param, '=', &tokens);
240 if (tokens[0] == kTransport) {
241 // As per above grammar transport param will be consist of lower case
242 // letters.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800243 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
244 (turn_transport_type != cricket::PROTO_UDP &&
245 turn_transport_type != cricket::PROTO_TCP)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200246 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700247 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000248 }
249 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200250 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200252 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700253 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200254 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
255 &service_type,
256 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700257 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
258 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200259 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000260
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
262 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200263
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200264 // Let's break hostname.
265 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700266 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
267
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200268 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269 if (tokens.size() > kTurnHostTokensNum) {
270 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
271 return false;
272 }
273 if (tokens.size() == kTurnHostTokensNum) {
274 if (tokens[0].empty() || tokens[1].empty()) {
275 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
276 return false;
277 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200278 username.assign(rtc::s_url_decode(tokens[0]));
279 hoststring = tokens[1];
280 } else {
281 hoststring = tokens[0];
282 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000283
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200284 int port = kDefaultStunPort;
285 if (service_type == TURNS) {
286 port = kDefaultStunTlsPort;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800287 turn_transport_type = cricket::PROTO_TCP;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200288 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000289
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200290 std::string address;
291 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700292 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
293 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200294 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000295
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200296 if (port <= 0 || port > 0xffff) {
297 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700298 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000300
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200301 switch (service_type) {
302 case STUN:
303 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800304 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200305 break;
306 case TURN:
307 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200308 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800309 turn_servers->push_back(
310 cricket::RelayServerConfig(address, port, username, server.password,
311 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200312 break;
313 }
314 case INVALID:
315 default:
316 LOG(WARNING) << "Configuration not supported: " << url;
317 return false;
318 }
319 return true;
320}
321
deadbeefab9b2d12015-10-14 11:33:11 -0700322// Check if we can send |new_stream| on a PeerConnection.
323bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
324 webrtc::MediaStreamInterface* new_stream) {
325 if (!new_stream || !current_streams) {
326 return false;
327 }
328 if (current_streams->find(new_stream->label()) != nullptr) {
329 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
330 << " is already added.";
331 return false;
332 }
333 return true;
334}
335
336bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
337 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
338}
339
deadbeef5e97fb52015-10-15 12:49:08 -0700340// If the direction is "recvonly" or "inactive", treat the description
341// as containing no streams.
342// See: https://code.google.com/p/webrtc/issues/detail?id=5054
343std::vector<cricket::StreamParams> GetActiveStreams(
344 const cricket::MediaContentDescription* desc) {
345 return MediaContentDirectionHasSend(desc->direction())
346 ? desc->streams()
347 : std::vector<cricket::StreamParams>();
348}
349
deadbeefab9b2d12015-10-14 11:33:11 -0700350bool IsValidOfferToReceiveMedia(int value) {
351 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
352 return (value >= Options::kUndefined) &&
353 (value <= Options::kMaxOfferToReceiveMedia);
354}
355
356// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800357void AddSendStreams(
358 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700359 const std::vector<rtc::scoped_refptr<
360 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800361 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
362 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700363 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800364 for (const auto& sender : senders) {
365 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700366 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700367 }
368
369 // Check for data channels.
370 for (const auto& kv : rtp_data_channels) {
371 const DataChannel* channel = kv.second;
372 if (channel->state() == DataChannel::kConnecting ||
373 channel->state() == DataChannel::kOpen) {
374 // |streamid| and |sync_label| are both set to the DataChannel label
375 // here so they can be signaled the same way as MediaStreams and Tracks.
376 // For MediaStreams, the sync_label is the MediaStream label and the
377 // track label is the same as |streamid|.
378 const std::string& streamid = channel->label();
379 const std::string& sync_label = channel->label();
380 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
381 sync_label);
382 }
383 }
384}
385
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700386uint32_t ConvertIceTransportTypeToCandidateFilter(
387 PeerConnectionInterface::IceTransportsType type) {
388 switch (type) {
389 case PeerConnectionInterface::kNone:
390 return cricket::CF_NONE;
391 case PeerConnectionInterface::kRelay:
392 return cricket::CF_RELAY;
393 case PeerConnectionInterface::kNoHost:
394 return (cricket::CF_ALL & ~cricket::CF_HOST);
395 case PeerConnectionInterface::kAll:
396 return cricket::CF_ALL;
397 default:
398 ASSERT(false);
399 }
400 return cricket::CF_NONE;
401}
402
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700403// Helper method to set a voice/video channel on all applicable senders
404// and receivers when one is created/destroyed by WebRtcSession.
405//
406// Used by On(Voice|Video)Channel(Created|Destroyed)
407template <class SENDER,
408 class RECEIVER,
409 class CHANNEL,
410 class SENDERS,
411 class RECEIVERS>
412void SetChannelOnSendersAndReceivers(CHANNEL* channel,
413 SENDERS& senders,
414 RECEIVERS& receivers,
415 cricket::MediaType media_type) {
416 for (auto& sender : senders) {
417 if (sender->media_type() == media_type) {
418 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
419 }
420 }
421 for (auto& receiver : receivers) {
422 if (receiver->media_type() == media_type) {
423 if (!channel) {
424 receiver->internal()->Stop();
425 }
426 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
427 }
428 }
429}
430
deadbeef0a6c4ca2015-10-06 11:38:28 -0700431} // namespace
432
433namespace webrtc {
434
zhihuang8f65cdf2016-05-06 18:40:30 -0700435// Generate a RTCP CNAME when a PeerConnection is created.
436std::string GenerateRtcpCname() {
437 std::string cname;
438 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
439 LOG(LS_ERROR) << "Failed to generate CNAME.";
440 RTC_DCHECK(false);
441 }
442 return cname;
443}
444
htaa2a49d92016-03-04 02:51:39 -0800445bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700446 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800447 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700448 cricket::MediaSessionOptions* session_options) {
449 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
450 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
451 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
452 return false;
453 }
454
htaaac2dea2016-03-10 13:35:55 -0800455 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700456 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700457 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800458 } else {
459 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700460 }
htaaac2dea2016-03-10 13:35:55 -0800461 // For offers, we only offer video if we have it or it's forced by options.
462 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700463 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700464 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800465 } else if (is_offer) {
466 session_options->recv_video = false;
467 } else {
468 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700469 }
470
471 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700472 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800473 for (auto& kv : session_options->transport_options) {
474 kv.second.ice_restart = rtc_options.ice_restart;
475 }
deadbeefab9b2d12015-10-14 11:33:11 -0700476
477 return true;
478}
479
480bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
481 cricket::MediaSessionOptions* session_options) {
482 bool value = false;
483 size_t mandatory_constraints_satisfied = 0;
484
485 // kOfferToReceiveAudio defaults to true according to spec.
486 if (!FindConstraint(constraints,
487 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
488 &mandatory_constraints_satisfied) ||
489 value) {
490 session_options->recv_audio = true;
491 }
492
493 // kOfferToReceiveVideo defaults to false according to spec. But
494 // if it is an answer and video is offered, we should still accept video
495 // per default.
496 value = false;
497 if (!FindConstraint(constraints,
498 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
499 &mandatory_constraints_satisfied) ||
500 value) {
501 session_options->recv_video = true;
502 }
503
504 if (FindConstraint(constraints,
505 MediaConstraintsInterface::kVoiceActivityDetection, &value,
506 &mandatory_constraints_satisfied)) {
507 session_options->vad_enabled = value;
508 }
509
510 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
511 &mandatory_constraints_satisfied)) {
512 session_options->bundle_enabled = value;
513 } else {
514 // kUseRtpMux defaults to true according to spec.
515 session_options->bundle_enabled = true;
516 }
deadbeefab9b2d12015-10-14 11:33:11 -0700517
deadbeef0ed85b22016-02-23 17:24:52 -0800518 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700519 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
520 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700521 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800522 ice_restart = true;
523 }
524 for (auto& kv : session_options->transport_options) {
525 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700526 }
527
528 if (!constraints) {
529 return true;
530 }
531 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
532}
533
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200534bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800535 cricket::ServerAddresses* stun_servers,
536 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200537 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
538 if (!server.urls.empty()) {
539 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200540 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700541 LOG(LS_ERROR) << "Empty uri.";
542 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200543 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800544 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200545 return false;
546 }
547 }
548 } else if (!server.uri.empty()) {
549 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800550 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000551 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200552 }
553 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700554 LOG(LS_ERROR) << "Empty uri.";
555 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000556 }
557 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800558 // Candidates must have unique priorities, so that connectivity checks
559 // are performed in a well-defined order.
560 int priority = static_cast<int>(turn_servers->size() - 1);
561 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
562 // First in the list gets highest priority.
563 turn_server.priority = priority--;
564 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000565 return true;
566}
567
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568PeerConnection::PeerConnection(PeerConnectionFactory* factory)
569 : factory_(factory),
570 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000571 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000572 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700574 ice_gathering_state_(kIceGatheringNew),
skvlad11a9cbf2016-10-07 11:53:05 -0700575 event_log_(RtcEventLog::Create(webrtc::Clock::GetRealTimeClock())),
zhihuang8f65cdf2016-05-06 18:40:30 -0700576 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700577 local_streams_(StreamCollection::Create()),
578 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579
580PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100581 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700582 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700583 // Need to detach RTP senders/receivers from WebRtcSession,
584 // since it's about to be destroyed.
585 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700586 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700587 }
588 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700589 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700590 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700591 // Destroy stats_ because it depends on session_.
592 stats_.reset(nullptr);
593 // Now destroy session_ before destroying other members,
594 // because its destruction fires signals (such as VoiceChannelDestroyed)
595 // which will trigger some final actions in PeerConnection...
596 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700597 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700598 network_thread()->Invoke<void>(RTC_FROM_HERE,
599 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000600}
601
602bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000603 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700604 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200605 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800606 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100607 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800608 RTC_DCHECK(observer != nullptr);
609 if (!observer) {
610 return false;
611 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000612 observer_ = observer;
613
kwiberg0eb15ed2015-12-17 03:04:15 -0800614 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800615
deadbeef91dd5672016-05-18 16:55:30 -0700616 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700617 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700618 if (!network_thread()->Invoke<bool>(
619 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
620 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621 return false;
622 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000623
skvlad11a9cbf2016-10-07 11:53:05 -0700624 media_controller_.reset(factory_->CreateMediaController(
625 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626
zhihuang29ff8442016-07-27 11:07:25 -0700627 session_.reset(new WebRtcSession(
628 media_controller_.get(), factory_->network_thread(),
629 factory_->worker_thread(), factory_->signaling_thread(),
630 port_allocator_.get(),
631 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700632 factory_->CreateTransportController(
633 port_allocator_.get(),
634 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700635
deadbeefab9b2d12015-10-14 11:33:11 -0700636 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700637 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638
639 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200640 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800641 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000642 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645 // Register PeerConnection as receiver of local ice candidates.
646 // All the callbacks will be posted to the application from PeerConnection.
647 session_->RegisterIceObserver(this);
648 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700649 session_->SignalVoiceChannelCreated.connect(
650 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700651 session_->SignalVoiceChannelDestroyed.connect(
652 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700653 session_->SignalVideoChannelCreated.connect(
654 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700655 session_->SignalVideoChannelDestroyed.connect(
656 this, &PeerConnection::OnVideoChannelDestroyed);
657 session_->SignalDataChannelCreated.connect(
658 this, &PeerConnection::OnDataChannelCreated);
659 session_->SignalDataChannelDestroyed.connect(
660 this, &PeerConnection::OnDataChannelDestroyed);
661 session_->SignalDataChannelOpenMessage.connect(
662 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800663
664 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000665 return true;
666}
667
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000668rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700670 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671}
672
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000673rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700675 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676}
677
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000678bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100679 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 if (IsClosed()) {
681 return false;
682 }
deadbeefab9b2d12015-10-14 11:33:11 -0700683 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 return false;
685 }
deadbeefab9b2d12015-10-14 11:33:11 -0700686
687 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800688 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
689 observer->SignalAudioTrackAdded.connect(this,
690 &PeerConnection::OnAudioTrackAdded);
691 observer->SignalAudioTrackRemoved.connect(
692 this, &PeerConnection::OnAudioTrackRemoved);
693 observer->SignalVideoTrackAdded.connect(this,
694 &PeerConnection::OnVideoTrackAdded);
695 observer->SignalVideoTrackRemoved.connect(
696 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700697 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700698
deadbeefab9b2d12015-10-14 11:33:11 -0700699 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800700 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700701 }
702 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800703 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700704 }
705
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000706 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707 observer_->OnRenegotiationNeeded();
708 return true;
709}
710
711void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100712 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700713 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800714 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700715 }
716 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800717 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700718 }
719
720 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800721 stream_observers_.erase(
722 std::remove_if(
723 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700724 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800725 return observer->stream()->label().compare(local_stream->label()) ==
726 0;
727 }),
728 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700729
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730 if (IsClosed()) {
731 return;
732 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 observer_->OnRenegotiationNeeded();
734}
735
deadbeefe1f9d832016-01-14 15:35:42 -0800736rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
737 MediaStreamTrackInterface* track,
738 std::vector<MediaStreamInterface*> streams) {
739 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
740 if (IsClosed()) {
741 return nullptr;
742 }
743 if (streams.size() >= 2) {
744 LOG(LS_ERROR)
745 << "Adding a track with two streams is not currently supported.";
746 return nullptr;
747 }
748 // TODO(deadbeef): Support adding a track to two different senders.
749 if (FindSenderForTrack(track) != senders_.end()) {
750 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
751 return nullptr;
752 }
753
754 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700755 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800756 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700757 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800758 signaling_thread(),
759 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700760 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800761 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700762 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800763 }
764 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700765 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800766 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700767 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800768 }
769 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700770 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800771 signaling_thread(),
772 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700773 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800774 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700775 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800776 }
777 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700778 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800779 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700780 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800781 }
782 } else {
783 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
784 return rtc::scoped_refptr<RtpSenderInterface>();
785 }
786
787 senders_.push_back(new_sender);
788 observer_->OnRenegotiationNeeded();
789 return new_sender;
790}
791
792bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
793 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
794 if (IsClosed()) {
795 return false;
796 }
797
798 auto it = std::find(senders_.begin(), senders_.end(), sender);
799 if (it == senders_.end()) {
800 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
801 return false;
802 }
deadbeefa601f5c2016-06-06 14:27:39 -0700803 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800804 senders_.erase(it);
805
806 observer_->OnRenegotiationNeeded();
807 return true;
808}
809
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000810rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100812 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700813 if (IsClosed()) {
814 return nullptr;
815 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000816 if (!track) {
817 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
818 return NULL;
819 }
deadbeefab9b2d12015-10-14 11:33:11 -0700820 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
822 return NULL;
823 }
824
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000825 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 DtmfSender::Create(track, signaling_thread(), session_.get()));
827 if (!sender.get()) {
828 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
829 return NULL;
830 }
831 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
832}
833
deadbeeffac06552015-11-25 11:26:01 -0800834rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800835 const std::string& kind,
836 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100837 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700838 if (IsClosed()) {
839 return nullptr;
840 }
deadbeefa601f5c2016-06-06 14:27:39 -0700841 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800842 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700843 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700844 signaling_thread(),
845 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800846 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700847 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700848 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800849 } else {
850 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800851 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800852 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800853 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700854 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800855 }
deadbeeffac06552015-11-25 11:26:01 -0800856 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800857 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800858}
859
deadbeef70ab1a12015-09-28 16:53:55 -0700860std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
861 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700862 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
863 for (const auto& sender : senders_) {
864 ret.push_back(sender.get());
865 }
866 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700867}
868
869std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
870PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700871 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
872 for (const auto& receiver : receivers_) {
873 ret.push_back(receiver.get());
874 }
875 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700876}
877
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000879 MediaStreamTrackInterface* track,
880 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100881 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700882 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 if (!VERIFY(observer != NULL)) {
884 LOG(LS_ERROR) << "GetStats - observer is NULL.";
885 return false;
886 }
887
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000888 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700889 // The StatsCollector is used to tell if a track is valid because it may
890 // remember tracks that the PeerConnection previously removed.
891 if (track && !stats_->IsValidTrack(track->id())) {
892 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
893 << track->id();
894 return false;
895 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700896 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000897 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898 return true;
899}
900
hbos74e1a4f2016-09-15 23:33:01 -0700901void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
902 RTC_DCHECK(stats_collector_);
903 stats_collector_->GetStatsReport(callback);
904}
905
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
907 return signaling_state_;
908}
909
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910PeerConnectionInterface::IceConnectionState
911PeerConnection::ice_connection_state() {
912 return ice_connection_state_;
913}
914
915PeerConnectionInterface::IceGatheringState
916PeerConnection::ice_gathering_state() {
917 return ice_gathering_state_;
918}
919
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000920rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921PeerConnection::CreateDataChannel(
922 const std::string& label,
923 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100924 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700925#ifdef HAVE_QUIC
926 if (session_->data_channel_type() == cricket::DCT_QUIC) {
927 // TODO(zhihuang): Handle case when config is NULL.
928 if (!config) {
929 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
930 return nullptr;
931 }
932 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
933 if (!config->reliable || config->ordered) {
934 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
935 "ordered delivery.";
936 return nullptr;
937 }
938 return session_->quic_data_transport()->CreateDataChannel(label, config);
939 }
940#endif // HAVE_QUIC
941
deadbeefab9b2d12015-10-14 11:33:11 -0700942 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000943
kwibergd1fe2812016-04-27 06:47:29 -0700944 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000945 if (config) {
946 internal_config.reset(new InternalDataChannelInit(*config));
947 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000948 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700949 InternalCreateDataChannel(label, internal_config.get()));
950 if (!channel.get()) {
951 return nullptr;
952 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000954 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
955 // the first SCTP DataChannel.
956 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
957 observer_->OnRenegotiationNeeded();
958 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000959
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 return DataChannelProxy::Create(signaling_thread(), channel.get());
961}
962
963void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
964 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100965 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700966 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
968 return;
969 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000970 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000971
972 bool value;
973 size_t mandatory_constraints = 0;
974
975 if (FindConstraint(constraints,
976 MediaConstraintsInterface::kOfferToReceiveAudio,
977 &value,
978 &mandatory_constraints)) {
979 options.offer_to_receive_audio =
980 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
981 }
982
983 if (FindConstraint(constraints,
984 MediaConstraintsInterface::kOfferToReceiveVideo,
985 &value,
986 &mandatory_constraints)) {
987 options.offer_to_receive_video =
988 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
989 }
990
991 if (FindConstraint(constraints,
992 MediaConstraintsInterface::kVoiceActivityDetection,
993 &value,
994 &mandatory_constraints)) {
995 options.voice_activity_detection = value;
996 }
997
998 if (FindConstraint(constraints,
999 MediaConstraintsInterface::kIceRestart,
1000 &value,
1001 &mandatory_constraints)) {
1002 options.ice_restart = value;
1003 }
1004
1005 if (FindConstraint(constraints,
1006 MediaConstraintsInterface::kUseRtpMux,
1007 &value,
1008 &mandatory_constraints)) {
1009 options.use_rtp_mux = value;
1010 }
1011
1012 CreateOffer(observer, options);
1013}
1014
1015void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1016 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001017 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001018 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001019 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1020 return;
1021 }
deadbeefab9b2d12015-10-14 11:33:11 -07001022
1023 cricket::MediaSessionOptions session_options;
1024 if (!GetOptionsForOffer(options, &session_options)) {
1025 std::string error = "CreateOffer called with invalid options.";
1026 LOG(LS_ERROR) << error;
1027 PostCreateSessionDescriptionFailure(observer, error);
1028 return;
1029 }
1030
1031 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032}
1033
1034void PeerConnection::CreateAnswer(
1035 CreateSessionDescriptionObserver* observer,
1036 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001037 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001038 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1040 return;
1041 }
deadbeefab9b2d12015-10-14 11:33:11 -07001042
1043 cricket::MediaSessionOptions session_options;
1044 if (!GetOptionsForAnswer(constraints, &session_options)) {
1045 std::string error = "CreateAnswer called with invalid constraints.";
1046 LOG(LS_ERROR) << error;
1047 PostCreateSessionDescriptionFailure(observer, error);
1048 return;
1049 }
1050
htaa2a49d92016-03-04 02:51:39 -08001051 session_->CreateAnswer(observer, session_options);
1052}
1053
1054void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1055 const RTCOfferAnswerOptions& options) {
1056 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1057 if (!VERIFY(observer != nullptr)) {
1058 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1059 return;
1060 }
1061
1062 cricket::MediaSessionOptions session_options;
1063 if (!GetOptionsForAnswer(options, &session_options)) {
1064 std::string error = "CreateAnswer called with invalid options.";
1065 LOG(LS_ERROR) << error;
1066 PostCreateSessionDescriptionFailure(observer, error);
1067 return;
1068 }
1069
1070 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071}
1072
1073void PeerConnection::SetLocalDescription(
1074 SetSessionDescriptionObserver* observer,
1075 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001076 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001077 if (IsClosed()) {
1078 return;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1082 return;
1083 }
1084 if (!desc) {
1085 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1086 return;
1087 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 // Update stats here so that we have the most recent stats for tracks and
1089 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001090 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 std::string error;
1092 if (!session_->SetLocalDescription(desc, &error)) {
1093 PostSetSessionDescriptionFailure(observer, error);
1094 return;
1095 }
deadbeefab9b2d12015-10-14 11:33:11 -07001096
1097 // If setting the description decided our SSL role, allocate any necessary
1098 // SCTP sids.
1099 rtc::SSLRole role;
1100 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001101 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001102 AllocateSctpSids(role);
1103 }
1104
1105 // Update state and SSRC of local MediaStreams and DataChannels based on the
1106 // local session description.
1107 const cricket::ContentInfo* audio_content =
1108 GetFirstAudioContent(desc->description());
1109 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001110 if (audio_content->rejected) {
1111 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1112 } else {
1113 const cricket::AudioContentDescription* audio_desc =
1114 static_cast<const cricket::AudioContentDescription*>(
1115 audio_content->description);
1116 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1117 }
deadbeefab9b2d12015-10-14 11:33:11 -07001118 }
1119
1120 const cricket::ContentInfo* video_content =
1121 GetFirstVideoContent(desc->description());
1122 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001123 if (video_content->rejected) {
1124 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1125 } else {
1126 const cricket::VideoContentDescription* video_desc =
1127 static_cast<const cricket::VideoContentDescription*>(
1128 video_content->description);
1129 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1130 }
deadbeefab9b2d12015-10-14 11:33:11 -07001131 }
1132
1133 const cricket::ContentInfo* data_content =
1134 GetFirstDataContent(desc->description());
1135 if (data_content) {
1136 const cricket::DataContentDescription* data_desc =
1137 static_cast<const cricket::DataContentDescription*>(
1138 data_content->description);
1139 if (rtc::starts_with(data_desc->protocol().data(),
1140 cricket::kMediaProtocolRtpPrefix)) {
1141 UpdateLocalRtpDataChannels(data_desc->streams());
1142 }
1143 }
1144
1145 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001146 signaling_thread()->Post(RTC_FROM_HERE, this,
1147 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001148
deadbeefcbecd352015-09-23 11:50:27 -07001149 // MaybeStartGathering needs to be called after posting
1150 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1151 // before signaling that SetLocalDescription completed.
1152 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001153}
1154
1155void PeerConnection::SetRemoteDescription(
1156 SetSessionDescriptionObserver* observer,
1157 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001158 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001159 if (IsClosed()) {
1160 return;
1161 }
deadbeefab9b2d12015-10-14 11:33:11 -07001162 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1164 return;
1165 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001166 if (!desc) {
1167 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1168 return;
1169 }
1170 // Update stats here so that we have the most recent stats for tracks and
1171 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001172 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 std::string error;
1174 if (!session_->SetRemoteDescription(desc, &error)) {
1175 PostSetSessionDescriptionFailure(observer, error);
1176 return;
1177 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178
deadbeefab9b2d12015-10-14 11:33:11 -07001179 // If setting the description decided our SSL role, allocate any necessary
1180 // SCTP sids.
1181 rtc::SSLRole role;
1182 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001183 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001184 AllocateSctpSids(role);
1185 }
1186
1187 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001188 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1189 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1190 const cricket::AudioContentDescription* audio_desc =
1191 GetFirstAudioContentDescription(remote_desc);
1192 const cricket::VideoContentDescription* video_desc =
1193 GetFirstVideoContentDescription(remote_desc);
1194 const cricket::DataContentDescription* data_desc =
1195 GetFirstDataContentDescription(remote_desc);
1196
1197 // Check if the descriptions include streams, just in case the peer supports
1198 // MSID, but doesn't indicate so with "a=msid-semantic".
1199 if (remote_desc->msid_supported() ||
1200 (audio_desc && !audio_desc->streams().empty()) ||
1201 (video_desc && !video_desc->streams().empty())) {
1202 remote_peer_supports_msid_ = true;
1203 }
deadbeefab9b2d12015-10-14 11:33:11 -07001204
1205 // We wait to signal new streams until we finish processing the description,
1206 // since only at that point will new streams have all their tracks.
1207 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1208
1209 // Find all audio rtp streams and create corresponding remote AudioTracks
1210 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001211 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001212 if (audio_content->rejected) {
1213 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1214 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001215 bool default_audio_track_needed =
1216 !remote_peer_supports_msid_ &&
1217 MediaContentDirectionHasSend(audio_desc->direction());
1218 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1219 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001220 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001221 }
deadbeefab9b2d12015-10-14 11:33:11 -07001222 }
1223
1224 // Find all video rtp streams and create corresponding remote VideoTracks
1225 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001226 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001227 if (video_content->rejected) {
1228 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1229 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001230 bool default_video_track_needed =
1231 !remote_peer_supports_msid_ &&
1232 MediaContentDirectionHasSend(video_desc->direction());
1233 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1234 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001235 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001236 }
deadbeefab9b2d12015-10-14 11:33:11 -07001237 }
1238
1239 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001240 if (data_desc) {
1241 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001242 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001243 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001244 }
1245 }
1246
1247 // Iterate new_streams and notify the observer about new MediaStreams.
1248 for (size_t i = 0; i < new_streams->count(); ++i) {
1249 MediaStreamInterface* new_stream = new_streams->at(i);
1250 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001251 // Call both the raw pointer and scoped_refptr versions of the method
1252 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001253 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001254 observer_->OnAddStream(
1255 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001256 }
1257
deadbeefbda7e0b2015-12-08 17:13:40 -08001258 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001259
1260 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001261 signaling_thread()->Post(RTC_FROM_HERE, this,
1262 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001263}
1264
deadbeef46c73892016-11-16 19:42:04 -08001265PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1266 return configuration_;
1267}
1268
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001269bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001270 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef46c73892016-11-16 19:42:04 -08001271 // TODO(deadbeef): Return false and log an error if there are any unsupported
1272 // modifications.
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001273 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001274 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001275 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001276 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001277 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001278 return false;
1279 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001280 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001281
1282 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1283 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001284
deadbeef46c73892016-11-16 19:42:04 -08001285 configuration_ = configuration;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001286 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001287}
1288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289bool PeerConnection::AddIceCandidate(
1290 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001291 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001292 if (IsClosed()) {
1293 return false;
1294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 return session_->ProcessIceMessage(ice_candidate);
1296}
1297
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001298bool PeerConnection::RemoveIceCandidates(
1299 const std::vector<cricket::Candidate>& candidates) {
1300 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1301 return session_->RemoveRemoteIceCandidates(candidates);
1302}
1303
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001304void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001305 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001306 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001307
1308 if (session_) {
1309 session_->set_metrics_observer(uma_observer_);
1310 }
1311
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001312 // Send information about IPv4/IPv6 status.
1313 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001314 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001315 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001316 uma_observer_->IncrementEnumCounter(
1317 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1318 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001319 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001320 uma_observer_->IncrementEnumCounter(
1321 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1322 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001323 }
1324 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001325}
1326
ivoc14d5dbe2016-07-04 07:06:55 -07001327bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1328 int64_t max_size_bytes) {
1329 return factory_->worker_thread()->Invoke<bool>(
1330 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1331 max_size_bytes));
1332}
1333
1334void PeerConnection::StopRtcEventLog() {
1335 factory_->worker_thread()->Invoke<void>(
1336 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1337}
1338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339const SessionDescriptionInterface* PeerConnection::local_description() const {
1340 return session_->local_description();
1341}
1342
1343const SessionDescriptionInterface* PeerConnection::remote_description() const {
1344 return session_->remote_description();
1345}
1346
1347void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001348 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 // Update stats here so that we have the most recent stats for tracks and
1350 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001351 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352
deadbeefd59daf82015-10-14 15:02:44 -07001353 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354}
1355
deadbeefd59daf82015-10-14 15:02:44 -07001356void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1357 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001359 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001361 break;
deadbeefd59daf82015-10-14 15:02:44 -07001362 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1364 break;
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1367 break;
deadbeefd59daf82015-10-14 15:02:44 -07001368 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1370 break;
deadbeefd59daf82015-10-14 15:02:44 -07001371 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1373 break;
deadbeefd59daf82015-10-14 15:02:44 -07001374 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 ChangeSignalingState(PeerConnectionInterface::kStable);
1376 break;
deadbeefd59daf82015-10-14 15:02:44 -07001377 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 ChangeSignalingState(PeerConnectionInterface::kClosed);
1379 break;
1380 default:
1381 break;
1382 }
1383}
1384
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001385void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1388 SetSessionDescriptionMsg* param =
1389 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1390 param->observer->OnSuccess();
1391 delete param;
1392 break;
1393 }
1394 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1395 SetSessionDescriptionMsg* param =
1396 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1397 param->observer->OnFailure(param->error);
1398 delete param;
1399 break;
1400 }
deadbeefab9b2d12015-10-14 11:33:11 -07001401 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1402 CreateSessionDescriptionMsg* param =
1403 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1404 param->observer->OnFailure(param->error);
1405 delete param;
1406 break;
1407 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 case MSG_GETSTATS: {
1409 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001410 StatsReports reports;
1411 stats_->GetStats(param->track, &reports);
1412 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 delete param;
1414 break;
1415 }
deadbeefbd292462015-12-14 18:15:29 -08001416 case MSG_FREE_DATACHANNELS: {
1417 sctp_data_channels_to_free_.clear();
1418 break;
1419 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001420 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001421 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 break;
1423 }
1424}
1425
deadbeefab9b2d12015-10-14 11:33:11 -07001426void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001427 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001428 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001429 receivers_.push_back(
1430 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001431 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
1432 session_->voice_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433}
1434
deadbeefab9b2d12015-10-14 11:33:11 -07001435void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001436 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001437 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001438 receivers_.push_back(
1439 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1440 signaling_thread(),
1441 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001442 ssrc, session_->video_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443}
1444
deadbeef70ab1a12015-09-28 16:53:55 -07001445// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1446// description.
perkjd61bf802016-03-24 03:16:19 -07001447void PeerConnection::DestroyReceiver(const std::string& track_id) {
1448 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001449 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001450 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001451 << " doesn't exist.";
1452 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001453 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001454 receivers_.erase(it);
1455 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456}
1457
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458void PeerConnection::OnIceConnectionChange(
1459 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001460 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001461 // After transitioning to "closed", ignore any additional states from
1462 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001463 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001464 return;
1465 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001467 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468}
1469
1470void PeerConnection::OnIceGatheringChange(
1471 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001472 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 if (IsClosed()) {
1474 return;
1475 }
1476 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001477 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478}
1479
1480void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001481 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001482 if (IsClosed()) {
1483 return;
1484 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001485 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486}
1487
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001488void PeerConnection::OnIceCandidatesRemoved(
1489 const std::vector<cricket::Candidate>& candidates) {
1490 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001491 if (IsClosed()) {
1492 return;
1493 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001494 observer_->OnIceCandidatesRemoved(candidates);
1495}
1496
Peter Thatcher54360512015-07-08 11:08:35 -07001497void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001498 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001499 if (IsClosed()) {
1500 return;
1501 }
Peter Thatcher54360512015-07-08 11:08:35 -07001502 observer_->OnIceConnectionReceivingChange(receiving);
1503}
1504
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505void PeerConnection::ChangeSignalingState(
1506 PeerConnectionInterface::SignalingState signaling_state) {
1507 signaling_state_ = signaling_state;
1508 if (signaling_state == kClosed) {
1509 ice_connection_state_ = kIceConnectionClosed;
1510 observer_->OnIceConnectionChange(ice_connection_state_);
1511 if (ice_gathering_state_ != kIceGatheringComplete) {
1512 ice_gathering_state_ = kIceGatheringComplete;
1513 observer_->OnIceGatheringChange(ice_gathering_state_);
1514 }
1515 }
1516 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001517}
1518
deadbeefeb459812015-12-15 19:24:43 -08001519void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1520 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001521 if (IsClosed()) {
1522 return;
1523 }
deadbeefeb459812015-12-15 19:24:43 -08001524 auto sender = FindSenderForTrack(track);
1525 if (sender != senders_.end()) {
1526 // We already have a sender for this track, so just change the stream_id
1527 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001528 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001529 return;
1530 }
1531
1532 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001533 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1534 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001535 signaling_thread(),
1536 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1537 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001538 senders_.push_back(new_sender);
1539 // If the sender has already been configured in SDP, we call SetSsrc,
1540 // which will connect the sender to the underlying transport. This can
1541 // occur if a local session description that contains the ID of the sender
1542 // is set before AddStream is called. It can also occur if the local
1543 // session description is not changed and RemoveStream is called, and
1544 // later AddStream is called again with the same stream.
1545 const TrackInfo* track_info =
1546 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1547 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001548 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001549 }
1550}
1551
1552// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1553// indefinitely, when we have unified plan SDP.
1554void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1555 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001556 if (IsClosed()) {
1557 return;
1558 }
deadbeefeb459812015-12-15 19:24:43 -08001559 auto sender = FindSenderForTrack(track);
1560 if (sender == senders_.end()) {
1561 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1562 << " doesn't exist.";
1563 return;
1564 }
deadbeefa601f5c2016-06-06 14:27:39 -07001565 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001566 senders_.erase(sender);
1567}
1568
1569void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1570 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001571 if (IsClosed()) {
1572 return;
1573 }
deadbeefeb459812015-12-15 19:24:43 -08001574 auto sender = FindSenderForTrack(track);
1575 if (sender != senders_.end()) {
1576 // We already have a sender for this track, so just change the stream_id
1577 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001578 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001579 return;
1580 }
1581
1582 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001583 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1584 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001585 signaling_thread(), new VideoRtpSender(track, stream->label(),
1586 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001587 senders_.push_back(new_sender);
1588 const TrackInfo* track_info =
1589 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1590 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001591 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001592 }
1593}
1594
1595void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1596 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001597 if (IsClosed()) {
1598 return;
1599 }
deadbeefeb459812015-12-15 19:24:43 -08001600 auto sender = FindSenderForTrack(track);
1601 if (sender == senders_.end()) {
1602 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1603 << " doesn't exist.";
1604 return;
1605 }
deadbeefa601f5c2016-06-06 14:27:39 -07001606 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001607 senders_.erase(sender);
1608}
1609
deadbeefab9b2d12015-10-14 11:33:11 -07001610void PeerConnection::PostSetSessionDescriptionFailure(
1611 SetSessionDescriptionObserver* observer,
1612 const std::string& error) {
1613 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1614 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001615 signaling_thread()->Post(RTC_FROM_HERE, this,
1616 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001617}
1618
1619void PeerConnection::PostCreateSessionDescriptionFailure(
1620 CreateSessionDescriptionObserver* observer,
1621 const std::string& error) {
1622 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1623 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001624 signaling_thread()->Post(RTC_FROM_HERE, this,
1625 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001626}
1627
1628bool PeerConnection::GetOptionsForOffer(
1629 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1630 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001631 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1632 // ContentInfos.
1633 if (session_->local_description()) {
1634 for (const cricket::ContentInfo& content :
1635 session_->local_description()->description()->contents()) {
1636 session_options->transport_options[content.name] =
1637 cricket::TransportOptions();
1638 }
1639 }
deadbeef46c73892016-11-16 19:42:04 -08001640 session_options->enable_ice_renomination =
1641 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001642
htaaac2dea2016-03-10 13:35:55 -08001643 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001644 return false;
1645 }
1646
deadbeeffac06552015-11-25 11:26:01 -08001647 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001648 // Offer to receive audio/video if the constraint is not set and there are
1649 // send streams, or we're currently receiving.
1650 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1651 session_options->recv_audio =
1652 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1653 !remote_audio_tracks_.empty();
1654 }
1655 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1656 session_options->recv_video =
1657 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1658 !remote_video_tracks_.empty();
1659 }
deadbeefc80741f2015-10-22 13:14:45 -07001660
zhihuang9763d562016-08-05 11:14:50 -07001661 // Intentionally unset the data channel type for RTP data channel with the
1662 // second condition. Otherwise the RTP data channels would be successfully
1663 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1664 // when building with chromium. We want to leave RTP data channels broken, so
1665 // people won't try to use them.
1666 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1667 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001668 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001669
zhihuangaf388472016-11-02 16:49:48 -07001670 session_options->bundle_enabled =
1671 session_options->bundle_enabled &&
1672 (session_options->has_audio() || session_options->has_video() ||
1673 session_options->has_data());
1674
zhihuang8f65cdf2016-05-06 18:40:30 -07001675 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001676 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001677 return true;
1678}
1679
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001680void PeerConnection::InitializeOptionsForAnswer(
1681 cricket::MediaSessionOptions* session_options) {
1682 session_options->recv_audio = false;
1683 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001684 session_options->enable_ice_renomination =
1685 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001686}
1687
htaa2a49d92016-03-04 02:51:39 -08001688void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001689 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001690 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1691 // ContentInfos.
1692 if (session_->remote_description()) {
1693 // Initialize the transport_options map.
1694 for (const cricket::ContentInfo& content :
1695 session_->remote_description()->description()->contents()) {
1696 session_options->transport_options[content.name] =
1697 cricket::TransportOptions();
1698 }
1699 }
deadbeeffac06552015-11-25 11:26:01 -08001700 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001701 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1702 // are not signaled in the SDP so does not go through that path and must be
1703 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001704 // Intentionally unset the data channel type for RTP data channel. Otherwise
1705 // the RTP data channels would be successfully negotiated by default and the
1706 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1707 // We want to leave RTP data channels broken, so people won't try to use them.
1708 if (session_->data_channel_type() != cricket::DCT_RTP) {
1709 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001710 }
zhihuangaf388472016-11-02 16:49:48 -07001711 session_options->bundle_enabled =
1712 session_options->bundle_enabled &&
1713 (session_options->has_audio() || session_options->has_video() ||
1714 session_options->has_data());
1715
jbauchcb560652016-08-04 05:20:32 -07001716 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001717}
1718
1719bool PeerConnection::GetOptionsForAnswer(
1720 const MediaConstraintsInterface* constraints,
1721 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001722 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001723 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1724 return false;
1725 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001726 session_options->rtcp_cname = rtcp_cname_;
1727
htaa2a49d92016-03-04 02:51:39 -08001728 FinishOptionsForAnswer(session_options);
1729 return true;
1730}
1731
1732bool PeerConnection::GetOptionsForAnswer(
1733 const RTCOfferAnswerOptions& options,
1734 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001735 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001736 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001737 return false;
1738 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001739 session_options->rtcp_cname = rtcp_cname_;
1740
htaa2a49d92016-03-04 02:51:39 -08001741 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001742 return true;
1743}
1744
deadbeeffaac4972015-11-12 15:33:07 -08001745void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1746 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001747 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1748 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001749}
1750
deadbeefab9b2d12015-10-14 11:33:11 -07001751void PeerConnection::UpdateRemoteStreamsList(
1752 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001753 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001754 cricket::MediaType media_type,
1755 StreamCollection* new_streams) {
1756 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1757
1758 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001759 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001760 auto track_it = current_tracks->begin();
1761 while (track_it != current_tracks->end()) {
1762 const TrackInfo& info = *track_it;
1763 const cricket::StreamParams* params =
1764 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001765 bool track_exists = params && params->id == info.track_id;
1766 // If this is a default track, and we still need it, don't remove it.
1767 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1768 track_exists) {
1769 ++track_it;
1770 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001771 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1772 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001773 }
1774 }
1775
1776 // Find new and active tracks.
1777 for (const cricket::StreamParams& params : streams) {
1778 // The sync_label is the MediaStream label and the |stream.id| is the
1779 // track id.
1780 const std::string& stream_label = params.sync_label;
1781 const std::string& track_id = params.id;
1782 uint32_t ssrc = params.first_ssrc();
1783
1784 rtc::scoped_refptr<MediaStreamInterface> stream =
1785 remote_streams_->find(stream_label);
1786 if (!stream) {
1787 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001788 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1789 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001790 remote_streams_->AddStream(stream);
1791 new_streams->AddStream(stream);
1792 }
1793
1794 const TrackInfo* track_info =
1795 FindTrackInfo(*current_tracks, stream_label, track_id);
1796 if (!track_info) {
1797 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1798 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1799 }
1800 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001801
1802 // Add default track if necessary.
1803 if (default_track_needed) {
1804 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1805 remote_streams_->find(kDefaultStreamLabel);
1806 if (!default_stream) {
1807 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001808 default_stream = MediaStreamProxy::Create(
1809 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001810 remote_streams_->AddStream(default_stream);
1811 new_streams->AddStream(default_stream);
1812 }
1813 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1814 ? kDefaultAudioTrackLabel
1815 : kDefaultVideoTrackLabel;
1816 const TrackInfo* default_track_info =
1817 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1818 if (!default_track_info) {
1819 current_tracks->push_back(
1820 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1821 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1822 }
1823 }
deadbeefab9b2d12015-10-14 11:33:11 -07001824}
1825
1826void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1827 const std::string& track_id,
1828 uint32_t ssrc,
1829 cricket::MediaType media_type) {
1830 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1831
1832 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001833 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001834 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001835 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001836 } else {
1837 RTC_DCHECK(false && "Invalid media type");
1838 }
1839}
1840
1841void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1842 const std::string& track_id,
1843 cricket::MediaType media_type) {
1844 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1845
1846 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001847 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1848 // will be notified which will end the AudioRtpReceiver::track().
1849 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001850 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1851 stream->FindAudioTrack(track_id);
1852 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001853 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001854 }
1855 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001856 // Stopping or destroying a VideoRtpReceiver will end the
1857 // VideoRtpReceiver::track().
1858 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001859 rtc::scoped_refptr<VideoTrackInterface> video_track =
1860 stream->FindVideoTrack(track_id);
1861 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001862 // There's no guarantee the track is still available, e.g. the track may
1863 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001864 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001865 }
1866 } else {
1867 ASSERT(false && "Invalid media type");
1868 }
1869}
1870
1871void PeerConnection::UpdateEndedRemoteMediaStreams() {
1872 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1873 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1874 MediaStreamInterface* stream = remote_streams_->at(i);
1875 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1876 streams_to_remove.push_back(stream);
1877 }
1878 }
1879
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001880 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001881 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001882 // Call both the raw pointer and scoped_refptr versions of the method
1883 // for compatibility.
1884 observer_->OnRemoveStream(stream.get());
1885 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001886 }
1887}
1888
deadbeefab9b2d12015-10-14 11:33:11 -07001889void PeerConnection::UpdateLocalTracks(
1890 const std::vector<cricket::StreamParams>& streams,
1891 cricket::MediaType media_type) {
1892 TrackInfos* current_tracks = GetLocalTracks(media_type);
1893
1894 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1895 // don't match the new StreamParam.
1896 TrackInfos::iterator track_it = current_tracks->begin();
1897 while (track_it != current_tracks->end()) {
1898 const TrackInfo& info = *track_it;
1899 const cricket::StreamParams* params =
1900 cricket::GetStreamBySsrc(streams, info.ssrc);
1901 if (!params || params->id != info.track_id ||
1902 params->sync_label != info.stream_label) {
1903 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1904 media_type);
1905 track_it = current_tracks->erase(track_it);
1906 } else {
1907 ++track_it;
1908 }
1909 }
1910
1911 // Find new and active tracks.
1912 for (const cricket::StreamParams& params : streams) {
1913 // The sync_label is the MediaStream label and the |stream.id| is the
1914 // track id.
1915 const std::string& stream_label = params.sync_label;
1916 const std::string& track_id = params.id;
1917 uint32_t ssrc = params.first_ssrc();
1918 const TrackInfo* track_info =
1919 FindTrackInfo(*current_tracks, stream_label, track_id);
1920 if (!track_info) {
1921 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1922 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1923 }
1924 }
1925}
1926
1927void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1928 const std::string& track_id,
1929 uint32_t ssrc,
1930 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001931 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001932 if (!sender) {
1933 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1934 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001935 return;
1936 }
1937
deadbeeffac06552015-11-25 11:26:01 -08001938 if (sender->media_type() != media_type) {
1939 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1940 << " description with an unexpected media type.";
1941 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001942 }
deadbeeffac06552015-11-25 11:26:01 -08001943
1944 sender->set_stream_id(stream_label);
1945 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001946}
1947
1948void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1949 const std::string& track_id,
1950 uint32_t ssrc,
1951 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001952 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001953 if (!sender) {
1954 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001955 // SessionDescriptions has been renegotiated.
1956 return;
1957 }
deadbeeffac06552015-11-25 11:26:01 -08001958
1959 // A sender has been removed from the SessionDescription but it's still
1960 // associated with the PeerConnection. This only occurs if the SDP doesn't
1961 // match with the calls to CreateSender, AddStream and RemoveStream.
1962 if (sender->media_type() != media_type) {
1963 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1964 << " description with an unexpected media type.";
1965 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001966 }
deadbeeffac06552015-11-25 11:26:01 -08001967
1968 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001969}
1970
1971void PeerConnection::UpdateLocalRtpDataChannels(
1972 const cricket::StreamParamsVec& streams) {
1973 std::vector<std::string> existing_channels;
1974
1975 // Find new and active data channels.
1976 for (const cricket::StreamParams& params : streams) {
1977 // |it->sync_label| is actually the data channel label. The reason is that
1978 // we use the same naming of data channels as we do for
1979 // MediaStreams and Tracks.
1980 // For MediaStreams, the sync_label is the MediaStream label and the
1981 // track label is the same as |streamid|.
1982 const std::string& channel_label = params.sync_label;
1983 auto data_channel_it = rtp_data_channels_.find(channel_label);
1984 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1985 continue;
1986 }
1987 // Set the SSRC the data channel should use for sending.
1988 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1989 existing_channels.push_back(data_channel_it->first);
1990 }
1991
1992 UpdateClosingRtpDataChannels(existing_channels, true);
1993}
1994
1995void PeerConnection::UpdateRemoteRtpDataChannels(
1996 const cricket::StreamParamsVec& streams) {
1997 std::vector<std::string> existing_channels;
1998
1999 // Find new and active data channels.
2000 for (const cricket::StreamParams& params : streams) {
2001 // The data channel label is either the mslabel or the SSRC if the mslabel
2002 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2003 std::string label = params.sync_label.empty()
2004 ? rtc::ToString(params.first_ssrc())
2005 : params.sync_label;
2006 auto data_channel_it = rtp_data_channels_.find(label);
2007 if (data_channel_it == rtp_data_channels_.end()) {
2008 // This is a new data channel.
2009 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2010 } else {
2011 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2012 }
2013 existing_channels.push_back(label);
2014 }
2015
2016 UpdateClosingRtpDataChannels(existing_channels, false);
2017}
2018
2019void PeerConnection::UpdateClosingRtpDataChannels(
2020 const std::vector<std::string>& active_channels,
2021 bool is_local_update) {
2022 auto it = rtp_data_channels_.begin();
2023 while (it != rtp_data_channels_.end()) {
2024 DataChannel* data_channel = it->second;
2025 if (std::find(active_channels.begin(), active_channels.end(),
2026 data_channel->label()) != active_channels.end()) {
2027 ++it;
2028 continue;
2029 }
2030
2031 if (is_local_update) {
2032 data_channel->SetSendSsrc(0);
2033 } else {
2034 data_channel->RemotePeerRequestClose();
2035 }
2036
2037 if (data_channel->state() == DataChannel::kClosed) {
2038 rtp_data_channels_.erase(it);
2039 it = rtp_data_channels_.begin();
2040 } else {
2041 ++it;
2042 }
2043 }
2044}
2045
2046void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2047 uint32_t remote_ssrc) {
2048 rtc::scoped_refptr<DataChannel> channel(
2049 InternalCreateDataChannel(label, nullptr));
2050 if (!channel.get()) {
2051 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2052 << "CreateDataChannel failed.";
2053 return;
2054 }
2055 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002056 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2057 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002058 // Call both the raw pointer and scoped_refptr versions of the method
2059 // for compatibility.
2060 observer_->OnDataChannel(proxy_channel.get());
2061 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002062}
2063
2064rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2065 const std::string& label,
2066 const InternalDataChannelInit* config) {
2067 if (IsClosed()) {
2068 return nullptr;
2069 }
2070 if (session_->data_channel_type() == cricket::DCT_NONE) {
2071 LOG(LS_ERROR)
2072 << "InternalCreateDataChannel: Data is not supported in this call.";
2073 return nullptr;
2074 }
2075 InternalDataChannelInit new_config =
2076 config ? (*config) : InternalDataChannelInit();
2077 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2078 if (new_config.id < 0) {
2079 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002080 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002081 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2082 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2083 return nullptr;
2084 }
2085 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2086 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2087 << "because the id is already in use or out of range.";
2088 return nullptr;
2089 }
2090 }
2091
2092 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2093 session_.get(), session_->data_channel_type(), label, new_config));
2094 if (!channel) {
2095 sid_allocator_.ReleaseSid(new_config.id);
2096 return nullptr;
2097 }
2098
2099 if (channel->data_channel_type() == cricket::DCT_RTP) {
2100 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2101 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2102 << " already exists.";
2103 return nullptr;
2104 }
2105 rtp_data_channels_[channel->label()] = channel;
2106 } else {
2107 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2108 sctp_data_channels_.push_back(channel);
2109 channel->SignalClosed.connect(this,
2110 &PeerConnection::OnSctpDataChannelClosed);
2111 }
2112
hbos82ebe022016-11-14 01:41:09 -08002113 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002114 return channel;
2115}
2116
2117bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002118#ifdef HAVE_QUIC
2119 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2120 (session_->quic_data_transport() &&
2121 session_->quic_data_transport()->HasDataChannels());
2122#else
deadbeefab9b2d12015-10-14 11:33:11 -07002123 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002124#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002125}
2126
2127void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2128 for (const auto& channel : sctp_data_channels_) {
2129 if (channel->id() < 0) {
2130 int sid;
2131 if (!sid_allocator_.AllocateSid(role, &sid)) {
2132 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2133 continue;
2134 }
2135 channel->SetSctpSid(sid);
2136 }
2137 }
2138}
2139
2140void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002141 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002142 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2143 ++it) {
2144 if (it->get() == channel) {
2145 if (channel->id() >= 0) {
2146 sid_allocator_.ReleaseSid(channel->id());
2147 }
deadbeefbd292462015-12-14 18:15:29 -08002148 // Since this method is triggered by a signal from the DataChannel,
2149 // we can't free it directly here; we need to free it asynchronously.
2150 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002151 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002152 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2153 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002154 return;
2155 }
2156 }
2157}
2158
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002159void PeerConnection::OnVoiceChannelCreated() {
2160 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2161 session_->voice_channel(), senders_, receivers_,
2162 cricket::MEDIA_TYPE_AUDIO);
2163}
2164
deadbeefab9b2d12015-10-14 11:33:11 -07002165void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002166 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2167 cricket::VoiceChannel>(
2168 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2169}
2170
2171void PeerConnection::OnVideoChannelCreated() {
2172 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2173 session_->video_channel(), senders_, receivers_,
2174 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002175}
2176
2177void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002178 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2179 cricket::VideoChannel>(
2180 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002181}
2182
2183void PeerConnection::OnDataChannelCreated() {
2184 for (const auto& channel : sctp_data_channels_) {
2185 channel->OnTransportChannelCreated();
2186 }
2187}
2188
2189void PeerConnection::OnDataChannelDestroyed() {
2190 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2191 // DataChannel may callback to us and try to modify the list.
2192 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2193 temp_rtp_dcs.swap(rtp_data_channels_);
2194 for (const auto& kv : temp_rtp_dcs) {
2195 kv.second->OnTransportChannelDestroyed();
2196 }
2197
2198 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2199 temp_sctp_dcs.swap(sctp_data_channels_);
2200 for (const auto& channel : temp_sctp_dcs) {
2201 channel->OnTransportChannelDestroyed();
2202 }
2203}
2204
2205void PeerConnection::OnDataChannelOpenMessage(
2206 const std::string& label,
2207 const InternalDataChannelInit& config) {
2208 rtc::scoped_refptr<DataChannel> channel(
2209 InternalCreateDataChannel(label, &config));
2210 if (!channel.get()) {
2211 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2212 return;
2213 }
2214
deadbeefa601f5c2016-06-06 14:27:39 -07002215 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2216 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002217 // Call both the raw pointer and scoped_refptr versions of the method
2218 // for compatibility.
2219 observer_->OnDataChannel(proxy_channel.get());
2220 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002221}
2222
deadbeefa601f5c2016-06-06 14:27:39 -07002223RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2224 auto it = std::find_if(
2225 senders_.begin(), senders_.end(),
2226 [id](const rtc::scoped_refptr<
2227 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2228 return sender->id() == id;
2229 });
2230 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002231}
2232
deadbeefa601f5c2016-06-06 14:27:39 -07002233std::vector<
2234 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002235PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2236 return std::find_if(
2237 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002238 [track](const rtc::scoped_refptr<
2239 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002240 return sender->track() == track;
2241 });
2242}
2243
deadbeefa601f5c2016-06-06 14:27:39 -07002244std::vector<rtc::scoped_refptr<
2245 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002246PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002247 return std::find_if(
2248 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002249 [track_id](const rtc::scoped_refptr<
2250 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002251 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002252 });
2253}
2254
deadbeefab9b2d12015-10-14 11:33:11 -07002255PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2256 cricket::MediaType media_type) {
2257 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2258 media_type == cricket::MEDIA_TYPE_VIDEO);
2259 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2260 : &remote_video_tracks_;
2261}
2262
2263PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2264 cricket::MediaType media_type) {
2265 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2266 media_type == cricket::MEDIA_TYPE_VIDEO);
2267 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2268 : &local_video_tracks_;
2269}
2270
2271const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2272 const PeerConnection::TrackInfos& infos,
2273 const std::string& stream_label,
2274 const std::string track_id) const {
2275 for (const TrackInfo& track_info : infos) {
2276 if (track_info.stream_label == stream_label &&
2277 track_info.track_id == track_id) {
2278 return &track_info;
2279 }
2280 }
2281 return nullptr;
2282}
2283
2284DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2285 for (const auto& channel : sctp_data_channels_) {
2286 if (channel->id() == sid) {
2287 return channel;
2288 }
2289 }
2290 return nullptr;
2291}
2292
deadbeef91dd5672016-05-18 16:55:30 -07002293bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002294 const RTCConfiguration& configuration) {
2295 cricket::ServerAddresses stun_servers;
2296 std::vector<cricket::RelayServerConfig> turn_servers;
2297 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2298 return false;
2299 }
2300
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002301 port_allocator_->Initialize();
2302
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002303 // To handle both internal and externally created port allocator, we will
2304 // enable BUNDLE here.
2305 int portallocator_flags = port_allocator_->flags();
2306 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2307 cricket::PORTALLOCATOR_ENABLE_IPV6;
2308 // If the disable-IPv6 flag was specified, we'll not override it
2309 // by experiment.
2310 if (configuration.disable_ipv6) {
2311 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2312 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2313 "Disabled") {
2314 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2315 }
2316
2317 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2318 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2319 LOG(LS_INFO) << "TCP candidates are disabled.";
2320 }
2321
honghaiz60347052016-05-31 18:29:12 -07002322 if (configuration.candidate_network_policy ==
2323 kCandidateNetworkPolicyLowCost) {
2324 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2325 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2326 }
2327
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002328 port_allocator_->set_flags(portallocator_flags);
2329 // No step delay is used while allocating ports.
2330 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2331 port_allocator_->set_candidate_filter(
2332 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2333
2334 // Call this last since it may create pooled allocator sessions using the
2335 // properties set above.
2336 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002337 configuration.ice_candidate_pool_size,
2338 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002339 return true;
2340}
2341
deadbeef91dd5672016-05-18 16:55:30 -07002342bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002343 const RTCConfiguration& configuration) {
2344 cricket::ServerAddresses stun_servers;
2345 std::vector<cricket::RelayServerConfig> turn_servers;
2346 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2347 return false;
2348 }
2349 port_allocator_->set_candidate_filter(
2350 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2351 // Call this last since it may create pooled allocator sessions using the
2352 // candidate filter set above.
2353 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002354 configuration.ice_candidate_pool_size,
2355 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002356 return true;
2357}
2358
ivoc14d5dbe2016-07-04 07:06:55 -07002359bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2360 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002361 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002362}
2363
2364void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002365 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002366}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002367} // namespace webrtc