blob: 3fdbefb8a9f5dc39cd51fe339a3e8fd787f88348 [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
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700639 enable_ice_renomination_ = configuration.enable_ice_renomination;
640
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200642 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800643 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700645 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000646
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000647 // Register PeerConnection as receiver of local ice candidates.
648 // All the callbacks will be posted to the application from PeerConnection.
649 session_->RegisterIceObserver(this);
650 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700651 session_->SignalVoiceChannelCreated.connect(
652 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700653 session_->SignalVoiceChannelDestroyed.connect(
654 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700655 session_->SignalVideoChannelCreated.connect(
656 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700657 session_->SignalVideoChannelDestroyed.connect(
658 this, &PeerConnection::OnVideoChannelDestroyed);
659 session_->SignalDataChannelCreated.connect(
660 this, &PeerConnection::OnDataChannelCreated);
661 session_->SignalDataChannelDestroyed.connect(
662 this, &PeerConnection::OnDataChannelDestroyed);
663 session_->SignalDataChannelOpenMessage.connect(
664 this, &PeerConnection::OnDataChannelOpenMessage);
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
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001265bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001266 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001267 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001268 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001269 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001270 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001271 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001272 return false;
1273 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001274 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001275
1276 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1277 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001278
1279 enable_ice_renomination_ = configuration.enable_ice_renomination;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001280 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001281}
1282
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283bool PeerConnection::AddIceCandidate(
1284 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001285 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001286 if (IsClosed()) {
1287 return false;
1288 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 return session_->ProcessIceMessage(ice_candidate);
1290}
1291
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001292bool PeerConnection::RemoveIceCandidates(
1293 const std::vector<cricket::Candidate>& candidates) {
1294 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1295 return session_->RemoveRemoteIceCandidates(candidates);
1296}
1297
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001298void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001299 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001300 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001301
1302 if (session_) {
1303 session_->set_metrics_observer(uma_observer_);
1304 }
1305
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001306 // Send information about IPv4/IPv6 status.
1307 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001308 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001309 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001310 uma_observer_->IncrementEnumCounter(
1311 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1312 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001313 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001314 uma_observer_->IncrementEnumCounter(
1315 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1316 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001317 }
1318 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001319}
1320
ivoc14d5dbe2016-07-04 07:06:55 -07001321bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1322 int64_t max_size_bytes) {
1323 return factory_->worker_thread()->Invoke<bool>(
1324 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1325 max_size_bytes));
1326}
1327
1328void PeerConnection::StopRtcEventLog() {
1329 factory_->worker_thread()->Invoke<void>(
1330 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1331}
1332
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333const SessionDescriptionInterface* PeerConnection::local_description() const {
1334 return session_->local_description();
1335}
1336
1337const SessionDescriptionInterface* PeerConnection::remote_description() const {
1338 return session_->remote_description();
1339}
1340
1341void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001342 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 // Update stats here so that we have the most recent stats for tracks and
1344 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001345 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346
deadbeefd59daf82015-10-14 15:02:44 -07001347 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348}
1349
deadbeefd59daf82015-10-14 15:02:44 -07001350void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1351 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001353 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001355 break;
deadbeefd59daf82015-10-14 15:02:44 -07001356 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1358 break;
deadbeefd59daf82015-10-14 15:02:44 -07001359 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1361 break;
deadbeefd59daf82015-10-14 15:02:44 -07001362 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1364 break;
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1367 break;
deadbeefd59daf82015-10-14 15:02:44 -07001368 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 ChangeSignalingState(PeerConnectionInterface::kStable);
1370 break;
deadbeefd59daf82015-10-14 15:02:44 -07001371 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 ChangeSignalingState(PeerConnectionInterface::kClosed);
1373 break;
1374 default:
1375 break;
1376 }
1377}
1378
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001379void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1382 SetSessionDescriptionMsg* param =
1383 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1384 param->observer->OnSuccess();
1385 delete param;
1386 break;
1387 }
1388 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1389 SetSessionDescriptionMsg* param =
1390 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1391 param->observer->OnFailure(param->error);
1392 delete param;
1393 break;
1394 }
deadbeefab9b2d12015-10-14 11:33:11 -07001395 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1396 CreateSessionDescriptionMsg* param =
1397 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1398 param->observer->OnFailure(param->error);
1399 delete param;
1400 break;
1401 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402 case MSG_GETSTATS: {
1403 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001404 StatsReports reports;
1405 stats_->GetStats(param->track, &reports);
1406 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 delete param;
1408 break;
1409 }
deadbeefbd292462015-12-14 18:15:29 -08001410 case MSG_FREE_DATACHANNELS: {
1411 sctp_data_channels_to_free_.clear();
1412 break;
1413 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001415 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 break;
1417 }
1418}
1419
deadbeefab9b2d12015-10-14 11:33:11 -07001420void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001421 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001422 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001423 receivers_.push_back(
1424 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001425 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
1426 session_->voice_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427}
1428
deadbeefab9b2d12015-10-14 11:33:11 -07001429void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001430 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001431 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001432 receivers_.push_back(
1433 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1434 signaling_thread(),
1435 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001436 ssrc, session_->video_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437}
1438
deadbeef70ab1a12015-09-28 16:53:55 -07001439// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1440// description.
perkjd61bf802016-03-24 03:16:19 -07001441void PeerConnection::DestroyReceiver(const std::string& track_id) {
1442 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001443 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001444 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001445 << " doesn't exist.";
1446 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001447 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001448 receivers_.erase(it);
1449 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450}
1451
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452void PeerConnection::OnIceConnectionChange(
1453 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001454 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001455 // After transitioning to "closed", ignore any additional states from
1456 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001457 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001458 return;
1459 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001461 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462}
1463
1464void PeerConnection::OnIceGatheringChange(
1465 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001466 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467 if (IsClosed()) {
1468 return;
1469 }
1470 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001471 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472}
1473
1474void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001475 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001476 if (IsClosed()) {
1477 return;
1478 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001479 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480}
1481
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001482void PeerConnection::OnIceCandidatesRemoved(
1483 const std::vector<cricket::Candidate>& candidates) {
1484 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001485 if (IsClosed()) {
1486 return;
1487 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001488 observer_->OnIceCandidatesRemoved(candidates);
1489}
1490
Peter Thatcher54360512015-07-08 11:08:35 -07001491void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001492 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001493 if (IsClosed()) {
1494 return;
1495 }
Peter Thatcher54360512015-07-08 11:08:35 -07001496 observer_->OnIceConnectionReceivingChange(receiving);
1497}
1498
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499void PeerConnection::ChangeSignalingState(
1500 PeerConnectionInterface::SignalingState signaling_state) {
1501 signaling_state_ = signaling_state;
1502 if (signaling_state == kClosed) {
1503 ice_connection_state_ = kIceConnectionClosed;
1504 observer_->OnIceConnectionChange(ice_connection_state_);
1505 if (ice_gathering_state_ != kIceGatheringComplete) {
1506 ice_gathering_state_ = kIceGatheringComplete;
1507 observer_->OnIceGatheringChange(ice_gathering_state_);
1508 }
1509 }
1510 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001511}
1512
deadbeefeb459812015-12-15 19:24:43 -08001513void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1514 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001515 if (IsClosed()) {
1516 return;
1517 }
deadbeefeb459812015-12-15 19:24:43 -08001518 auto sender = FindSenderForTrack(track);
1519 if (sender != senders_.end()) {
1520 // We already have a sender for this track, so just change the stream_id
1521 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001522 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001523 return;
1524 }
1525
1526 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001527 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1528 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001529 signaling_thread(),
1530 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1531 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001532 senders_.push_back(new_sender);
1533 // If the sender has already been configured in SDP, we call SetSsrc,
1534 // which will connect the sender to the underlying transport. This can
1535 // occur if a local session description that contains the ID of the sender
1536 // is set before AddStream is called. It can also occur if the local
1537 // session description is not changed and RemoveStream is called, and
1538 // later AddStream is called again with the same stream.
1539 const TrackInfo* track_info =
1540 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1541 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001542 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001543 }
1544}
1545
1546// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1547// indefinitely, when we have unified plan SDP.
1548void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1549 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001550 if (IsClosed()) {
1551 return;
1552 }
deadbeefeb459812015-12-15 19:24:43 -08001553 auto sender = FindSenderForTrack(track);
1554 if (sender == senders_.end()) {
1555 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1556 << " doesn't exist.";
1557 return;
1558 }
deadbeefa601f5c2016-06-06 14:27:39 -07001559 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001560 senders_.erase(sender);
1561}
1562
1563void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1564 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001565 if (IsClosed()) {
1566 return;
1567 }
deadbeefeb459812015-12-15 19:24:43 -08001568 auto sender = FindSenderForTrack(track);
1569 if (sender != senders_.end()) {
1570 // We already have a sender for this track, so just change the stream_id
1571 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001572 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001573 return;
1574 }
1575
1576 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001577 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1578 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001579 signaling_thread(), new VideoRtpSender(track, stream->label(),
1580 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001581 senders_.push_back(new_sender);
1582 const TrackInfo* track_info =
1583 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1584 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001585 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001586 }
1587}
1588
1589void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1590 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001591 if (IsClosed()) {
1592 return;
1593 }
deadbeefeb459812015-12-15 19:24:43 -08001594 auto sender = FindSenderForTrack(track);
1595 if (sender == senders_.end()) {
1596 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1597 << " doesn't exist.";
1598 return;
1599 }
deadbeefa601f5c2016-06-06 14:27:39 -07001600 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001601 senders_.erase(sender);
1602}
1603
deadbeefab9b2d12015-10-14 11:33:11 -07001604void PeerConnection::PostSetSessionDescriptionFailure(
1605 SetSessionDescriptionObserver* observer,
1606 const std::string& error) {
1607 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1608 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001609 signaling_thread()->Post(RTC_FROM_HERE, this,
1610 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001611}
1612
1613void PeerConnection::PostCreateSessionDescriptionFailure(
1614 CreateSessionDescriptionObserver* observer,
1615 const std::string& error) {
1616 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1617 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001618 signaling_thread()->Post(RTC_FROM_HERE, this,
1619 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001620}
1621
1622bool PeerConnection::GetOptionsForOffer(
1623 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1624 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001625 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1626 // ContentInfos.
1627 if (session_->local_description()) {
1628 for (const cricket::ContentInfo& content :
1629 session_->local_description()->description()->contents()) {
1630 session_options->transport_options[content.name] =
1631 cricket::TransportOptions();
1632 }
1633 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001634 session_options->enable_ice_renomination = enable_ice_renomination_;
1635
htaaac2dea2016-03-10 13:35:55 -08001636 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001637 return false;
1638 }
1639
deadbeeffac06552015-11-25 11:26:01 -08001640 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001641 // Offer to receive audio/video if the constraint is not set and there are
1642 // send streams, or we're currently receiving.
1643 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1644 session_options->recv_audio =
1645 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1646 !remote_audio_tracks_.empty();
1647 }
1648 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1649 session_options->recv_video =
1650 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1651 !remote_video_tracks_.empty();
1652 }
deadbeefc80741f2015-10-22 13:14:45 -07001653
zhihuang9763d562016-08-05 11:14:50 -07001654 // Intentionally unset the data channel type for RTP data channel with the
1655 // second condition. Otherwise the RTP data channels would be successfully
1656 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1657 // when building with chromium. We want to leave RTP data channels broken, so
1658 // people won't try to use them.
1659 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1660 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001661 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001662
zhihuangaf388472016-11-02 16:49:48 -07001663 session_options->bundle_enabled =
1664 session_options->bundle_enabled &&
1665 (session_options->has_audio() || session_options->has_video() ||
1666 session_options->has_data());
1667
zhihuang8f65cdf2016-05-06 18:40:30 -07001668 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001669 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001670 return true;
1671}
1672
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001673void PeerConnection::InitializeOptionsForAnswer(
1674 cricket::MediaSessionOptions* session_options) {
1675 session_options->recv_audio = false;
1676 session_options->recv_video = false;
1677 session_options->enable_ice_renomination = enable_ice_renomination_;
1678}
1679
htaa2a49d92016-03-04 02:51:39 -08001680void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001681 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001682 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1683 // ContentInfos.
1684 if (session_->remote_description()) {
1685 // Initialize the transport_options map.
1686 for (const cricket::ContentInfo& content :
1687 session_->remote_description()->description()->contents()) {
1688 session_options->transport_options[content.name] =
1689 cricket::TransportOptions();
1690 }
1691 }
deadbeeffac06552015-11-25 11:26:01 -08001692 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001693 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1694 // are not signaled in the SDP so does not go through that path and must be
1695 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001696 // Intentionally unset the data channel type for RTP data channel. Otherwise
1697 // the RTP data channels would be successfully negotiated by default and the
1698 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1699 // We want to leave RTP data channels broken, so people won't try to use them.
1700 if (session_->data_channel_type() != cricket::DCT_RTP) {
1701 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001702 }
zhihuangaf388472016-11-02 16:49:48 -07001703 session_options->bundle_enabled =
1704 session_options->bundle_enabled &&
1705 (session_options->has_audio() || session_options->has_video() ||
1706 session_options->has_data());
1707
jbauchcb560652016-08-04 05:20:32 -07001708 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001709}
1710
1711bool PeerConnection::GetOptionsForAnswer(
1712 const MediaConstraintsInterface* constraints,
1713 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001714 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001715 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1716 return false;
1717 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001718 session_options->rtcp_cname = rtcp_cname_;
1719
htaa2a49d92016-03-04 02:51:39 -08001720 FinishOptionsForAnswer(session_options);
1721 return true;
1722}
1723
1724bool PeerConnection::GetOptionsForAnswer(
1725 const RTCOfferAnswerOptions& options,
1726 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001727 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001728 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001729 return false;
1730 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001731 session_options->rtcp_cname = rtcp_cname_;
1732
htaa2a49d92016-03-04 02:51:39 -08001733 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001734 return true;
1735}
1736
deadbeeffaac4972015-11-12 15:33:07 -08001737void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1738 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001739 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1740 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001741}
1742
deadbeefab9b2d12015-10-14 11:33:11 -07001743void PeerConnection::UpdateRemoteStreamsList(
1744 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001745 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001746 cricket::MediaType media_type,
1747 StreamCollection* new_streams) {
1748 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1749
1750 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001751 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001752 auto track_it = current_tracks->begin();
1753 while (track_it != current_tracks->end()) {
1754 const TrackInfo& info = *track_it;
1755 const cricket::StreamParams* params =
1756 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001757 bool track_exists = params && params->id == info.track_id;
1758 // If this is a default track, and we still need it, don't remove it.
1759 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1760 track_exists) {
1761 ++track_it;
1762 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001763 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1764 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001765 }
1766 }
1767
1768 // Find new and active tracks.
1769 for (const cricket::StreamParams& params : streams) {
1770 // The sync_label is the MediaStream label and the |stream.id| is the
1771 // track id.
1772 const std::string& stream_label = params.sync_label;
1773 const std::string& track_id = params.id;
1774 uint32_t ssrc = params.first_ssrc();
1775
1776 rtc::scoped_refptr<MediaStreamInterface> stream =
1777 remote_streams_->find(stream_label);
1778 if (!stream) {
1779 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001780 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1781 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001782 remote_streams_->AddStream(stream);
1783 new_streams->AddStream(stream);
1784 }
1785
1786 const TrackInfo* track_info =
1787 FindTrackInfo(*current_tracks, stream_label, track_id);
1788 if (!track_info) {
1789 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1790 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1791 }
1792 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001793
1794 // Add default track if necessary.
1795 if (default_track_needed) {
1796 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1797 remote_streams_->find(kDefaultStreamLabel);
1798 if (!default_stream) {
1799 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001800 default_stream = MediaStreamProxy::Create(
1801 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001802 remote_streams_->AddStream(default_stream);
1803 new_streams->AddStream(default_stream);
1804 }
1805 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1806 ? kDefaultAudioTrackLabel
1807 : kDefaultVideoTrackLabel;
1808 const TrackInfo* default_track_info =
1809 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1810 if (!default_track_info) {
1811 current_tracks->push_back(
1812 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1813 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1814 }
1815 }
deadbeefab9b2d12015-10-14 11:33:11 -07001816}
1817
1818void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1819 const std::string& track_id,
1820 uint32_t ssrc,
1821 cricket::MediaType media_type) {
1822 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1823
1824 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001825 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001826 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001827 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001828 } else {
1829 RTC_DCHECK(false && "Invalid media type");
1830 }
1831}
1832
1833void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1834 const std::string& track_id,
1835 cricket::MediaType media_type) {
1836 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1837
1838 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001839 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1840 // will be notified which will end the AudioRtpReceiver::track().
1841 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001842 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1843 stream->FindAudioTrack(track_id);
1844 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001845 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001846 }
1847 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001848 // Stopping or destroying a VideoRtpReceiver will end the
1849 // VideoRtpReceiver::track().
1850 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001851 rtc::scoped_refptr<VideoTrackInterface> video_track =
1852 stream->FindVideoTrack(track_id);
1853 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001854 // There's no guarantee the track is still available, e.g. the track may
1855 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001856 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001857 }
1858 } else {
1859 ASSERT(false && "Invalid media type");
1860 }
1861}
1862
1863void PeerConnection::UpdateEndedRemoteMediaStreams() {
1864 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1865 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1866 MediaStreamInterface* stream = remote_streams_->at(i);
1867 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1868 streams_to_remove.push_back(stream);
1869 }
1870 }
1871
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001872 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001873 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001874 // Call both the raw pointer and scoped_refptr versions of the method
1875 // for compatibility.
1876 observer_->OnRemoveStream(stream.get());
1877 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001878 }
1879}
1880
deadbeefab9b2d12015-10-14 11:33:11 -07001881void PeerConnection::UpdateLocalTracks(
1882 const std::vector<cricket::StreamParams>& streams,
1883 cricket::MediaType media_type) {
1884 TrackInfos* current_tracks = GetLocalTracks(media_type);
1885
1886 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1887 // don't match the new StreamParam.
1888 TrackInfos::iterator track_it = current_tracks->begin();
1889 while (track_it != current_tracks->end()) {
1890 const TrackInfo& info = *track_it;
1891 const cricket::StreamParams* params =
1892 cricket::GetStreamBySsrc(streams, info.ssrc);
1893 if (!params || params->id != info.track_id ||
1894 params->sync_label != info.stream_label) {
1895 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1896 media_type);
1897 track_it = current_tracks->erase(track_it);
1898 } else {
1899 ++track_it;
1900 }
1901 }
1902
1903 // Find new and active tracks.
1904 for (const cricket::StreamParams& params : streams) {
1905 // The sync_label is the MediaStream label and the |stream.id| is the
1906 // track id.
1907 const std::string& stream_label = params.sync_label;
1908 const std::string& track_id = params.id;
1909 uint32_t ssrc = params.first_ssrc();
1910 const TrackInfo* track_info =
1911 FindTrackInfo(*current_tracks, stream_label, track_id);
1912 if (!track_info) {
1913 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1914 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1915 }
1916 }
1917}
1918
1919void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1920 const std::string& track_id,
1921 uint32_t ssrc,
1922 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001923 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001924 if (!sender) {
1925 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1926 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001927 return;
1928 }
1929
deadbeeffac06552015-11-25 11:26:01 -08001930 if (sender->media_type() != media_type) {
1931 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1932 << " description with an unexpected media type.";
1933 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001934 }
deadbeeffac06552015-11-25 11:26:01 -08001935
1936 sender->set_stream_id(stream_label);
1937 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001938}
1939
1940void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1941 const std::string& track_id,
1942 uint32_t ssrc,
1943 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001944 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001945 if (!sender) {
1946 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001947 // SessionDescriptions has been renegotiated.
1948 return;
1949 }
deadbeeffac06552015-11-25 11:26:01 -08001950
1951 // A sender has been removed from the SessionDescription but it's still
1952 // associated with the PeerConnection. This only occurs if the SDP doesn't
1953 // match with the calls to CreateSender, AddStream and RemoveStream.
1954 if (sender->media_type() != media_type) {
1955 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1956 << " description with an unexpected media type.";
1957 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001958 }
deadbeeffac06552015-11-25 11:26:01 -08001959
1960 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001961}
1962
1963void PeerConnection::UpdateLocalRtpDataChannels(
1964 const cricket::StreamParamsVec& streams) {
1965 std::vector<std::string> existing_channels;
1966
1967 // Find new and active data channels.
1968 for (const cricket::StreamParams& params : streams) {
1969 // |it->sync_label| is actually the data channel label. The reason is that
1970 // we use the same naming of data channels as we do for
1971 // MediaStreams and Tracks.
1972 // For MediaStreams, the sync_label is the MediaStream label and the
1973 // track label is the same as |streamid|.
1974 const std::string& channel_label = params.sync_label;
1975 auto data_channel_it = rtp_data_channels_.find(channel_label);
1976 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1977 continue;
1978 }
1979 // Set the SSRC the data channel should use for sending.
1980 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1981 existing_channels.push_back(data_channel_it->first);
1982 }
1983
1984 UpdateClosingRtpDataChannels(existing_channels, true);
1985}
1986
1987void PeerConnection::UpdateRemoteRtpDataChannels(
1988 const cricket::StreamParamsVec& streams) {
1989 std::vector<std::string> existing_channels;
1990
1991 // Find new and active data channels.
1992 for (const cricket::StreamParams& params : streams) {
1993 // The data channel label is either the mslabel or the SSRC if the mslabel
1994 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1995 std::string label = params.sync_label.empty()
1996 ? rtc::ToString(params.first_ssrc())
1997 : params.sync_label;
1998 auto data_channel_it = rtp_data_channels_.find(label);
1999 if (data_channel_it == rtp_data_channels_.end()) {
2000 // This is a new data channel.
2001 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2002 } else {
2003 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2004 }
2005 existing_channels.push_back(label);
2006 }
2007
2008 UpdateClosingRtpDataChannels(existing_channels, false);
2009}
2010
2011void PeerConnection::UpdateClosingRtpDataChannels(
2012 const std::vector<std::string>& active_channels,
2013 bool is_local_update) {
2014 auto it = rtp_data_channels_.begin();
2015 while (it != rtp_data_channels_.end()) {
2016 DataChannel* data_channel = it->second;
2017 if (std::find(active_channels.begin(), active_channels.end(),
2018 data_channel->label()) != active_channels.end()) {
2019 ++it;
2020 continue;
2021 }
2022
2023 if (is_local_update) {
2024 data_channel->SetSendSsrc(0);
2025 } else {
2026 data_channel->RemotePeerRequestClose();
2027 }
2028
2029 if (data_channel->state() == DataChannel::kClosed) {
2030 rtp_data_channels_.erase(it);
2031 it = rtp_data_channels_.begin();
2032 } else {
2033 ++it;
2034 }
2035 }
2036}
2037
2038void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2039 uint32_t remote_ssrc) {
2040 rtc::scoped_refptr<DataChannel> channel(
2041 InternalCreateDataChannel(label, nullptr));
2042 if (!channel.get()) {
2043 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2044 << "CreateDataChannel failed.";
2045 return;
2046 }
2047 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002048 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2049 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002050 // Call both the raw pointer and scoped_refptr versions of the method
2051 // for compatibility.
2052 observer_->OnDataChannel(proxy_channel.get());
2053 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002054}
2055
2056rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2057 const std::string& label,
2058 const InternalDataChannelInit* config) {
2059 if (IsClosed()) {
2060 return nullptr;
2061 }
2062 if (session_->data_channel_type() == cricket::DCT_NONE) {
2063 LOG(LS_ERROR)
2064 << "InternalCreateDataChannel: Data is not supported in this call.";
2065 return nullptr;
2066 }
2067 InternalDataChannelInit new_config =
2068 config ? (*config) : InternalDataChannelInit();
2069 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2070 if (new_config.id < 0) {
2071 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002072 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002073 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2074 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2075 return nullptr;
2076 }
2077 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2078 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2079 << "because the id is already in use or out of range.";
2080 return nullptr;
2081 }
2082 }
2083
2084 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2085 session_.get(), session_->data_channel_type(), label, new_config));
2086 if (!channel) {
2087 sid_allocator_.ReleaseSid(new_config.id);
2088 return nullptr;
2089 }
2090
2091 if (channel->data_channel_type() == cricket::DCT_RTP) {
2092 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2093 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2094 << " already exists.";
2095 return nullptr;
2096 }
2097 rtp_data_channels_[channel->label()] = channel;
2098 } else {
2099 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2100 sctp_data_channels_.push_back(channel);
2101 channel->SignalClosed.connect(this,
2102 &PeerConnection::OnSctpDataChannelClosed);
2103 }
2104
2105 return channel;
2106}
2107
2108bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002109#ifdef HAVE_QUIC
2110 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2111 (session_->quic_data_transport() &&
2112 session_->quic_data_transport()->HasDataChannels());
2113#else
deadbeefab9b2d12015-10-14 11:33:11 -07002114 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002115#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002116}
2117
2118void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2119 for (const auto& channel : sctp_data_channels_) {
2120 if (channel->id() < 0) {
2121 int sid;
2122 if (!sid_allocator_.AllocateSid(role, &sid)) {
2123 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2124 continue;
2125 }
2126 channel->SetSctpSid(sid);
2127 }
2128 }
2129}
2130
2131void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002132 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002133 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2134 ++it) {
2135 if (it->get() == channel) {
2136 if (channel->id() >= 0) {
2137 sid_allocator_.ReleaseSid(channel->id());
2138 }
deadbeefbd292462015-12-14 18:15:29 -08002139 // Since this method is triggered by a signal from the DataChannel,
2140 // we can't free it directly here; we need to free it asynchronously.
2141 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002142 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002143 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2144 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002145 return;
2146 }
2147 }
2148}
2149
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002150void PeerConnection::OnVoiceChannelCreated() {
2151 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2152 session_->voice_channel(), senders_, receivers_,
2153 cricket::MEDIA_TYPE_AUDIO);
2154}
2155
deadbeefab9b2d12015-10-14 11:33:11 -07002156void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002157 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2158 cricket::VoiceChannel>(
2159 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2160}
2161
2162void PeerConnection::OnVideoChannelCreated() {
2163 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2164 session_->video_channel(), senders_, receivers_,
2165 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002166}
2167
2168void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002169 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2170 cricket::VideoChannel>(
2171 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002172}
2173
2174void PeerConnection::OnDataChannelCreated() {
2175 for (const auto& channel : sctp_data_channels_) {
2176 channel->OnTransportChannelCreated();
2177 }
2178}
2179
2180void PeerConnection::OnDataChannelDestroyed() {
2181 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2182 // DataChannel may callback to us and try to modify the list.
2183 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2184 temp_rtp_dcs.swap(rtp_data_channels_);
2185 for (const auto& kv : temp_rtp_dcs) {
2186 kv.second->OnTransportChannelDestroyed();
2187 }
2188
2189 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2190 temp_sctp_dcs.swap(sctp_data_channels_);
2191 for (const auto& channel : temp_sctp_dcs) {
2192 channel->OnTransportChannelDestroyed();
2193 }
2194}
2195
2196void PeerConnection::OnDataChannelOpenMessage(
2197 const std::string& label,
2198 const InternalDataChannelInit& config) {
2199 rtc::scoped_refptr<DataChannel> channel(
2200 InternalCreateDataChannel(label, &config));
2201 if (!channel.get()) {
2202 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2203 return;
2204 }
2205
deadbeefa601f5c2016-06-06 14:27:39 -07002206 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2207 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002208 // Call both the raw pointer and scoped_refptr versions of the method
2209 // for compatibility.
2210 observer_->OnDataChannel(proxy_channel.get());
2211 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002212}
2213
deadbeefa601f5c2016-06-06 14:27:39 -07002214RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2215 auto it = std::find_if(
2216 senders_.begin(), senders_.end(),
2217 [id](const rtc::scoped_refptr<
2218 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2219 return sender->id() == id;
2220 });
2221 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002222}
2223
deadbeefa601f5c2016-06-06 14:27:39 -07002224std::vector<
2225 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002226PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2227 return std::find_if(
2228 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002229 [track](const rtc::scoped_refptr<
2230 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002231 return sender->track() == track;
2232 });
2233}
2234
deadbeefa601f5c2016-06-06 14:27:39 -07002235std::vector<rtc::scoped_refptr<
2236 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002237PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002238 return std::find_if(
2239 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002240 [track_id](const rtc::scoped_refptr<
2241 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002242 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002243 });
2244}
2245
deadbeefab9b2d12015-10-14 11:33:11 -07002246PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2247 cricket::MediaType media_type) {
2248 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2249 media_type == cricket::MEDIA_TYPE_VIDEO);
2250 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2251 : &remote_video_tracks_;
2252}
2253
2254PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2255 cricket::MediaType media_type) {
2256 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2257 media_type == cricket::MEDIA_TYPE_VIDEO);
2258 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2259 : &local_video_tracks_;
2260}
2261
2262const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2263 const PeerConnection::TrackInfos& infos,
2264 const std::string& stream_label,
2265 const std::string track_id) const {
2266 for (const TrackInfo& track_info : infos) {
2267 if (track_info.stream_label == stream_label &&
2268 track_info.track_id == track_id) {
2269 return &track_info;
2270 }
2271 }
2272 return nullptr;
2273}
2274
2275DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2276 for (const auto& channel : sctp_data_channels_) {
2277 if (channel->id() == sid) {
2278 return channel;
2279 }
2280 }
2281 return nullptr;
2282}
2283
deadbeef91dd5672016-05-18 16:55:30 -07002284bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002285 const RTCConfiguration& configuration) {
2286 cricket::ServerAddresses stun_servers;
2287 std::vector<cricket::RelayServerConfig> turn_servers;
2288 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2289 return false;
2290 }
2291
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002292 port_allocator_->Initialize();
2293
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002294 // To handle both internal and externally created port allocator, we will
2295 // enable BUNDLE here.
2296 int portallocator_flags = port_allocator_->flags();
2297 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2298 cricket::PORTALLOCATOR_ENABLE_IPV6;
2299 // If the disable-IPv6 flag was specified, we'll not override it
2300 // by experiment.
2301 if (configuration.disable_ipv6) {
2302 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2303 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2304 "Disabled") {
2305 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2306 }
2307
2308 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2309 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2310 LOG(LS_INFO) << "TCP candidates are disabled.";
2311 }
2312
honghaiz60347052016-05-31 18:29:12 -07002313 if (configuration.candidate_network_policy ==
2314 kCandidateNetworkPolicyLowCost) {
2315 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2316 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2317 }
2318
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002319 port_allocator_->set_flags(portallocator_flags);
2320 // No step delay is used while allocating ports.
2321 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2322 port_allocator_->set_candidate_filter(
2323 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2324
2325 // Call this last since it may create pooled allocator sessions using the
2326 // properties set above.
2327 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002328 configuration.ice_candidate_pool_size,
2329 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002330 return true;
2331}
2332
deadbeef91dd5672016-05-18 16:55:30 -07002333bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002334 const RTCConfiguration& configuration) {
2335 cricket::ServerAddresses stun_servers;
2336 std::vector<cricket::RelayServerConfig> turn_servers;
2337 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2338 return false;
2339 }
2340 port_allocator_->set_candidate_filter(
2341 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2342 // Call this last since it may create pooled allocator sessions using the
2343 // candidate filter set above.
2344 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002345 configuration.ice_candidate_pool_size,
2346 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002347 return true;
2348}
2349
ivoc14d5dbe2016-07-04 07:06:55 -07002350bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2351 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002352 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002353}
2354
2355void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002356 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002357}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002358} // namespace webrtc