blob: 46bdec594a9c90fcd1630db748921237807902d2 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070037#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010038#include "webrtc/base/trace_event.h"
ivoc14d5dbe2016-07-04 07:06:55 -070039#include "webrtc/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070040#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kjellandera96e2d72016-02-04 23:52:28 -080041#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010042#include "webrtc/pc/channelmanager.h"
skvlad11a9cbf2016-10-07 11:53:05 -070043#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010044#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045
46namespace {
47
deadbeefab9b2d12015-10-14 11:33:11 -070048using webrtc::DataChannel;
49using webrtc::MediaConstraintsInterface;
50using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070052using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080053using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070054using webrtc::RtpSenderProxy;
55using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070056using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
deadbeefab9b2d12015-10-14 11:33:11 -070058static const char kDefaultStreamLabel[] = "default";
59static const char kDefaultAudioTrackLabel[] = "defaulta0";
60static const char kDefaultVideoTrackLabel[] = "defaultv0";
61
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062// The min number of tokens must present in Turn host uri.
63// e.g. user@turn.example.org
64static const size_t kTurnHostTokensNum = 2;
65// Number of tokens must be preset when TURN uri has transport param.
66static const size_t kTurnTransportTokensNum = 2;
67// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000068static const int kDefaultStunPort = 3478;
69static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071
72// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070073static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
zhihuang8f65cdf2016-05-06 18:40:30 -070075// The length of RTCP CNAMEs.
76static const int kRtcpCnameLength = 16;
77
deadbeef0a6c4ca2015-10-06 11:38:28 -070078// NOTE: A loop below assumes that the first value of this enum is 0 and all
79// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070081 STUN = 0, // Indicates a STUN server.
82 STUNS, // Indicates a STUN server used with a TLS session.
83 TURN, // Indicates a TURN server
84 TURNS, // Indicates a TURN server used with a TLS session.
85 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086};
tfarina5237aaf2015-11-10 23:44:30 -080087static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070088 "kValidIceServiceTypes must have as many strings as ServiceType "
89 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
91enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000092 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070094 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080096 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097};
98
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000099struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 explicit SetSessionDescriptionMsg(
101 webrtc::SetSessionDescriptionObserver* observer)
102 : observer(observer) {
103 }
104
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000105 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 std::string error;
107};
108
deadbeefab9b2d12015-10-14 11:33:11 -0700109struct CreateSessionDescriptionMsg : public rtc::MessageData {
110 explicit CreateSessionDescriptionMsg(
111 webrtc::CreateSessionDescriptionObserver* observer)
112 : observer(observer) {}
113
114 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
115 std::string error;
116};
117
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000118struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000119 GetStatsMsg(webrtc::StatsObserver* observer,
120 webrtc::MediaStreamTrackInterface* track)
121 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000123 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000124 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125};
126
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000127// |in_str| should be of format
128// stunURI = scheme ":" stun-host [ ":" stun-port ]
129// scheme = "stun" / "stuns"
130// stun-host = IP-literal / IPv4address / reg-name
131// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700132//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000133// draft-petithuguenin-behave-turn-uris-01
134// turnURI = scheme ":" turn-host [ ":" turn-port ]
135// turn-host = username@IP-literal / IPv4address / reg-name
136bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
137 ServiceType* service_type,
138 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200139 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700140 if (colonpos == std::string::npos) {
141 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000142 return false;
143 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700144 if ((colonpos + 1) == in_str.length()) {
145 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
146 return false;
147 }
148 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800149 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700150 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000151 *service_type = static_cast<ServiceType>(i);
152 break;
153 }
154 }
155 if (*service_type == INVALID) {
156 return false;
157 }
158 *hostname = in_str.substr(colonpos + 1, std::string::npos);
159 return true;
160}
161
deadbeef0a6c4ca2015-10-06 11:38:28 -0700162bool ParsePort(const std::string& in_str, int* port) {
163 // Make sure port only contains digits. FromString doesn't check this.
164 for (const char& c : in_str) {
165 if (!std::isdigit(c)) {
166 return false;
167 }
168 }
169 return rtc::FromString(in_str, port);
170}
171
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000172// This method parses IPv6 and IPv4 literal strings, along with hostnames in
173// standard hostname:port format.
174// Consider following formats as correct.
175// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700176// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000177bool ParseHostnameAndPortFromString(const std::string& in_str,
178 std::string* host,
179 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700180 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000181 if (in_str.at(0) == '[') {
182 std::string::size_type closebracket = in_str.rfind(']');
183 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 std::string::size_type colonpos = in_str.find(':', closebracket);
185 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700186 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
187 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000188 return false;
189 }
190 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700191 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000192 } else {
193 return false;
194 }
195 } else {
196 std::string::size_type colonpos = in_str.find(':');
197 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700198 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000199 return false;
200 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 } else {
203 *host = in_str;
204 }
205 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700206 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000207}
208
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800209// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700210// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200211bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
212 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800213 cricket::ServerAddresses* stun_servers,
214 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 // draft-nandakumar-rtcweb-stun-uri-01
216 // stunURI = scheme ":" stun-host [ ":" stun-port ]
217 // scheme = "stun" / "stuns"
218 // stun-host = IP-literal / IPv4address / reg-name
219 // stun-port = *DIGIT
220
221 // draft-petithuguenin-behave-turn-uris-01
222 // turnURI = scheme ":" turn-host [ ":" turn-port ]
223 // [ "?transport=" transport ]
224 // scheme = "turn" / "turns"
225 // transport = "udp" / "tcp" / transport-ext
226 // transport-ext = 1*unreserved
227 // turn-host = IP-literal / IPv4address / reg-name
228 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800229 RTC_DCHECK(stun_servers != nullptr);
230 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200231 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800232 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700233 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200234 rtc::tokenize(url, '?', &tokens);
235 std::string uri_without_transport = tokens[0];
236 // Let's look into transport= param, if it exists.
237 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
238 std::string uri_transport_param = tokens[1];
239 rtc::tokenize(uri_transport_param, '=', &tokens);
240 if (tokens[0] == kTransport) {
241 // As per above grammar transport param will be consist of lower case
242 // letters.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800243 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
244 (turn_transport_type != cricket::PROTO_UDP &&
245 turn_transport_type != cricket::PROTO_TCP)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200246 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700247 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000248 }
249 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200250 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200252 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700253 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200254 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
255 &service_type,
256 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700257 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
258 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200259 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000260
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
262 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200263
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200264 // Let's break hostname.
265 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700266 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
267
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200268 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269 if (tokens.size() > kTurnHostTokensNum) {
270 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
271 return false;
272 }
273 if (tokens.size() == kTurnHostTokensNum) {
274 if (tokens[0].empty() || tokens[1].empty()) {
275 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
276 return false;
277 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200278 username.assign(rtc::s_url_decode(tokens[0]));
279 hoststring = tokens[1];
280 } else {
281 hoststring = tokens[0];
282 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000283
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200284 int port = kDefaultStunPort;
285 if (service_type == TURNS) {
286 port = kDefaultStunTlsPort;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800287 turn_transport_type = cricket::PROTO_TCP;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200288 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000289
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200290 std::string address;
291 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700292 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
293 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200294 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000295
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200296 if (port <= 0 || port > 0xffff) {
297 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700298 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000300
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200301 switch (service_type) {
302 case STUN:
303 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800304 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200305 break;
306 case TURN:
307 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200308 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800309 turn_servers->push_back(
310 cricket::RelayServerConfig(address, port, username, server.password,
311 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200312 break;
313 }
314 case INVALID:
315 default:
316 LOG(WARNING) << "Configuration not supported: " << url;
317 return false;
318 }
319 return true;
320}
321
deadbeefab9b2d12015-10-14 11:33:11 -0700322// Check if we can send |new_stream| on a PeerConnection.
323bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
324 webrtc::MediaStreamInterface* new_stream) {
325 if (!new_stream || !current_streams) {
326 return false;
327 }
328 if (current_streams->find(new_stream->label()) != nullptr) {
329 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
330 << " is already added.";
331 return false;
332 }
333 return true;
334}
335
336bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
337 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
338}
339
deadbeef5e97fb52015-10-15 12:49:08 -0700340// If the direction is "recvonly" or "inactive", treat the description
341// as containing no streams.
342// See: https://code.google.com/p/webrtc/issues/detail?id=5054
343std::vector<cricket::StreamParams> GetActiveStreams(
344 const cricket::MediaContentDescription* desc) {
345 return MediaContentDirectionHasSend(desc->direction())
346 ? desc->streams()
347 : std::vector<cricket::StreamParams>();
348}
349
deadbeefab9b2d12015-10-14 11:33:11 -0700350bool IsValidOfferToReceiveMedia(int value) {
351 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
352 return (value >= Options::kUndefined) &&
353 (value <= Options::kMaxOfferToReceiveMedia);
354}
355
356// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800357void AddSendStreams(
358 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700359 const std::vector<rtc::scoped_refptr<
360 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800361 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
362 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700363 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800364 for (const auto& sender : senders) {
365 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700366 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700367 }
368
369 // Check for data channels.
370 for (const auto& kv : rtp_data_channels) {
371 const DataChannel* channel = kv.second;
372 if (channel->state() == DataChannel::kConnecting ||
373 channel->state() == DataChannel::kOpen) {
374 // |streamid| and |sync_label| are both set to the DataChannel label
375 // here so they can be signaled the same way as MediaStreams and Tracks.
376 // For MediaStreams, the sync_label is the MediaStream label and the
377 // track label is the same as |streamid|.
378 const std::string& streamid = channel->label();
379 const std::string& sync_label = channel->label();
380 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
381 sync_label);
382 }
383 }
384}
385
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700386uint32_t ConvertIceTransportTypeToCandidateFilter(
387 PeerConnectionInterface::IceTransportsType type) {
388 switch (type) {
389 case PeerConnectionInterface::kNone:
390 return cricket::CF_NONE;
391 case PeerConnectionInterface::kRelay:
392 return cricket::CF_RELAY;
393 case PeerConnectionInterface::kNoHost:
394 return (cricket::CF_ALL & ~cricket::CF_HOST);
395 case PeerConnectionInterface::kAll:
396 return cricket::CF_ALL;
397 default:
398 ASSERT(false);
399 }
400 return cricket::CF_NONE;
401}
402
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700403// Helper method to set a voice/video channel on all applicable senders
404// and receivers when one is created/destroyed by WebRtcSession.
405//
406// Used by On(Voice|Video)Channel(Created|Destroyed)
407template <class SENDER,
408 class RECEIVER,
409 class CHANNEL,
410 class SENDERS,
411 class RECEIVERS>
412void SetChannelOnSendersAndReceivers(CHANNEL* channel,
413 SENDERS& senders,
414 RECEIVERS& receivers,
415 cricket::MediaType media_type) {
416 for (auto& sender : senders) {
417 if (sender->media_type() == media_type) {
418 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
419 }
420 }
421 for (auto& receiver : receivers) {
422 if (receiver->media_type() == media_type) {
423 if (!channel) {
424 receiver->internal()->Stop();
425 }
426 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
427 }
428 }
429}
430
deadbeef0a6c4ca2015-10-06 11:38:28 -0700431} // namespace
432
433namespace webrtc {
434
zhihuang8f65cdf2016-05-06 18:40:30 -0700435// Generate a RTCP CNAME when a PeerConnection is created.
436std::string GenerateRtcpCname() {
437 std::string cname;
438 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
439 LOG(LS_ERROR) << "Failed to generate CNAME.";
440 RTC_DCHECK(false);
441 }
442 return cname;
443}
444
htaa2a49d92016-03-04 02:51:39 -0800445bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700446 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800447 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700448 cricket::MediaSessionOptions* session_options) {
449 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
450 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
451 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
452 return false;
453 }
454
htaaac2dea2016-03-10 13:35:55 -0800455 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700456 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700457 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800458 } else {
459 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700460 }
htaaac2dea2016-03-10 13:35:55 -0800461 // For offers, we only offer video if we have it or it's forced by options.
462 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700463 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700464 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800465 } else if (is_offer) {
466 session_options->recv_video = false;
467 } else {
468 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700469 }
470
471 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700472 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800473 for (auto& kv : session_options->transport_options) {
474 kv.second.ice_restart = rtc_options.ice_restart;
475 }
deadbeefab9b2d12015-10-14 11:33:11 -0700476
477 return true;
478}
479
480bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
481 cricket::MediaSessionOptions* session_options) {
482 bool value = false;
483 size_t mandatory_constraints_satisfied = 0;
484
485 // kOfferToReceiveAudio defaults to true according to spec.
486 if (!FindConstraint(constraints,
487 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
488 &mandatory_constraints_satisfied) ||
489 value) {
490 session_options->recv_audio = true;
491 }
492
493 // kOfferToReceiveVideo defaults to false according to spec. But
494 // if it is an answer and video is offered, we should still accept video
495 // per default.
496 value = false;
497 if (!FindConstraint(constraints,
498 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
499 &mandatory_constraints_satisfied) ||
500 value) {
501 session_options->recv_video = true;
502 }
503
504 if (FindConstraint(constraints,
505 MediaConstraintsInterface::kVoiceActivityDetection, &value,
506 &mandatory_constraints_satisfied)) {
507 session_options->vad_enabled = value;
508 }
509
510 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
511 &mandatory_constraints_satisfied)) {
512 session_options->bundle_enabled = value;
513 } else {
514 // kUseRtpMux defaults to true according to spec.
515 session_options->bundle_enabled = true;
516 }
deadbeefab9b2d12015-10-14 11:33:11 -0700517
deadbeef0ed85b22016-02-23 17:24:52 -0800518 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700519 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
520 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700521 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800522 ice_restart = true;
523 }
524 for (auto& kv : session_options->transport_options) {
525 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700526 }
527
528 if (!constraints) {
529 return true;
530 }
531 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
532}
533
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200534bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800535 cricket::ServerAddresses* stun_servers,
536 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200537 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
538 if (!server.urls.empty()) {
539 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200540 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700541 LOG(LS_ERROR) << "Empty uri.";
542 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200543 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800544 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200545 return false;
546 }
547 }
548 } else if (!server.uri.empty()) {
549 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800550 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000551 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200552 }
553 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700554 LOG(LS_ERROR) << "Empty uri.";
555 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000556 }
557 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800558 // Candidates must have unique priorities, so that connectivity checks
559 // are performed in a well-defined order.
560 int priority = static_cast<int>(turn_servers->size() - 1);
561 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
562 // First in the list gets highest priority.
563 turn_server.priority = priority--;
564 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000565 return true;
566}
567
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568PeerConnection::PeerConnection(PeerConnectionFactory* factory)
569 : factory_(factory),
570 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000571 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000572 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700574 ice_gathering_state_(kIceGatheringNew),
skvlad11a9cbf2016-10-07 11:53:05 -0700575 event_log_(RtcEventLog::Create(webrtc::Clock::GetRealTimeClock())),
zhihuang8f65cdf2016-05-06 18:40:30 -0700576 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700577 local_streams_(StreamCollection::Create()),
578 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579
580PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100581 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700582 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700583 // Need to detach RTP senders/receivers from WebRtcSession,
584 // since it's about to be destroyed.
585 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700586 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700587 }
588 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700589 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700590 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700591 // Destroy stats_ because it depends on session_.
592 stats_.reset(nullptr);
593 // Now destroy session_ before destroying other members,
594 // because its destruction fires signals (such as VoiceChannelDestroyed)
595 // which will trigger some final actions in PeerConnection...
596 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700597 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700598 network_thread()->Invoke<void>(RTC_FROM_HERE,
599 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000600}
601
602bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000603 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700604 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200605 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800606 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100607 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800608 RTC_DCHECK(observer != nullptr);
609 if (!observer) {
610 return false;
611 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000612 observer_ = observer;
613
kwiberg0eb15ed2015-12-17 03:04:15 -0800614 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800615
deadbeef91dd5672016-05-18 16:55:30 -0700616 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700617 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700618 if (!network_thread()->Invoke<bool>(
619 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
620 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621 return false;
622 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000623
skvlad11a9cbf2016-10-07 11:53:05 -0700624 media_controller_.reset(factory_->CreateMediaController(
625 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626
zhihuang29ff8442016-07-27 11:07:25 -0700627 session_.reset(new WebRtcSession(
628 media_controller_.get(), factory_->network_thread(),
629 factory_->worker_thread(), factory_->signaling_thread(),
630 port_allocator_.get(),
631 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700632 factory_->CreateTransportController(
633 port_allocator_.get(),
634 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700635
deadbeefab9b2d12015-10-14 11:33:11 -0700636 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700637 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638
639 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200640 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800641 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000642 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645 // Register PeerConnection as receiver of local ice candidates.
646 // All the callbacks will be posted to the application from PeerConnection.
647 session_->RegisterIceObserver(this);
648 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700649 session_->SignalVoiceChannelCreated.connect(
650 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700651 session_->SignalVoiceChannelDestroyed.connect(
652 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700653 session_->SignalVideoChannelCreated.connect(
654 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700655 session_->SignalVideoChannelDestroyed.connect(
656 this, &PeerConnection::OnVideoChannelDestroyed);
657 session_->SignalDataChannelCreated.connect(
658 this, &PeerConnection::OnDataChannelCreated);
659 session_->SignalDataChannelDestroyed.connect(
660 this, &PeerConnection::OnDataChannelDestroyed);
661 session_->SignalDataChannelOpenMessage.connect(
662 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800663
664 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000665 return true;
666}
667
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000668rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700670 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671}
672
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000673rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700675 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676}
677
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000678bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100679 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 if (IsClosed()) {
681 return false;
682 }
deadbeefab9b2d12015-10-14 11:33:11 -0700683 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 return false;
685 }
deadbeefab9b2d12015-10-14 11:33:11 -0700686
687 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800688 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
689 observer->SignalAudioTrackAdded.connect(this,
690 &PeerConnection::OnAudioTrackAdded);
691 observer->SignalAudioTrackRemoved.connect(
692 this, &PeerConnection::OnAudioTrackRemoved);
693 observer->SignalVideoTrackAdded.connect(this,
694 &PeerConnection::OnVideoTrackAdded);
695 observer->SignalVideoTrackRemoved.connect(
696 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700697 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700698
deadbeefab9b2d12015-10-14 11:33:11 -0700699 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800700 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700701 }
702 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800703 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700704 }
705
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000706 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707 observer_->OnRenegotiationNeeded();
708 return true;
709}
710
711void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100712 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700713 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800714 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700715 }
716 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800717 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700718 }
719
720 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800721 stream_observers_.erase(
722 std::remove_if(
723 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700724 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800725 return observer->stream()->label().compare(local_stream->label()) ==
726 0;
727 }),
728 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700729
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730 if (IsClosed()) {
731 return;
732 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 observer_->OnRenegotiationNeeded();
734}
735
deadbeefe1f9d832016-01-14 15:35:42 -0800736rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
737 MediaStreamTrackInterface* track,
738 std::vector<MediaStreamInterface*> streams) {
739 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
740 if (IsClosed()) {
741 return nullptr;
742 }
743 if (streams.size() >= 2) {
744 LOG(LS_ERROR)
745 << "Adding a track with two streams is not currently supported.";
746 return nullptr;
747 }
748 // TODO(deadbeef): Support adding a track to two different senders.
749 if (FindSenderForTrack(track) != senders_.end()) {
750 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
751 return nullptr;
752 }
753
754 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700755 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800756 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700757 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800758 signaling_thread(),
759 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700760 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800761 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700762 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800763 }
764 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700765 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800766 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700767 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800768 }
769 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700770 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800771 signaling_thread(),
772 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700773 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800774 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700775 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800776 }
777 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700778 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800779 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700780 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800781 }
782 } else {
783 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
784 return rtc::scoped_refptr<RtpSenderInterface>();
785 }
786
787 senders_.push_back(new_sender);
788 observer_->OnRenegotiationNeeded();
789 return new_sender;
790}
791
792bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
793 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
794 if (IsClosed()) {
795 return false;
796 }
797
798 auto it = std::find(senders_.begin(), senders_.end(), sender);
799 if (it == senders_.end()) {
800 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
801 return false;
802 }
deadbeefa601f5c2016-06-06 14:27:39 -0700803 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800804 senders_.erase(it);
805
806 observer_->OnRenegotiationNeeded();
807 return true;
808}
809
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000810rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100812 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700813 if (IsClosed()) {
814 return nullptr;
815 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000816 if (!track) {
817 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
818 return NULL;
819 }
deadbeefab9b2d12015-10-14 11:33:11 -0700820 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
822 return NULL;
823 }
824
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000825 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 DtmfSender::Create(track, signaling_thread(), session_.get()));
827 if (!sender.get()) {
828 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
829 return NULL;
830 }
831 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
832}
833
deadbeeffac06552015-11-25 11:26:01 -0800834rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800835 const std::string& kind,
836 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100837 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700838 if (IsClosed()) {
839 return nullptr;
840 }
deadbeefa601f5c2016-06-06 14:27:39 -0700841 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800842 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700843 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700844 signaling_thread(),
845 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800846 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700847 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700848 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800849 } else {
850 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800851 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800852 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800853 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700854 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800855 }
deadbeeffac06552015-11-25 11:26:01 -0800856 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800857 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800858}
859
deadbeef70ab1a12015-09-28 16:53:55 -0700860std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
861 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700862 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
863 for (const auto& sender : senders_) {
864 ret.push_back(sender.get());
865 }
866 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700867}
868
869std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
870PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700871 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
872 for (const auto& receiver : receivers_) {
873 ret.push_back(receiver.get());
874 }
875 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700876}
877
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000879 MediaStreamTrackInterface* track,
880 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100881 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700882 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 if (!VERIFY(observer != NULL)) {
884 LOG(LS_ERROR) << "GetStats - observer is NULL.";
885 return false;
886 }
887
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000888 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700889 // The StatsCollector is used to tell if a track is valid because it may
890 // remember tracks that the PeerConnection previously removed.
891 if (track && !stats_->IsValidTrack(track->id())) {
892 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
893 << track->id();
894 return false;
895 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700896 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000897 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898 return true;
899}
900
hbos74e1a4f2016-09-15 23:33:01 -0700901void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
902 RTC_DCHECK(stats_collector_);
903 stats_collector_->GetStatsReport(callback);
904}
905
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
907 return signaling_state_;
908}
909
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910PeerConnectionInterface::IceConnectionState
911PeerConnection::ice_connection_state() {
912 return ice_connection_state_;
913}
914
915PeerConnectionInterface::IceGatheringState
916PeerConnection::ice_gathering_state() {
917 return ice_gathering_state_;
918}
919
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000920rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921PeerConnection::CreateDataChannel(
922 const std::string& label,
923 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100924 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700925#ifdef HAVE_QUIC
926 if (session_->data_channel_type() == cricket::DCT_QUIC) {
927 // TODO(zhihuang): Handle case when config is NULL.
928 if (!config) {
929 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
930 return nullptr;
931 }
932 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
933 if (!config->reliable || config->ordered) {
934 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
935 "ordered delivery.";
936 return nullptr;
937 }
938 return session_->quic_data_transport()->CreateDataChannel(label, config);
939 }
940#endif // HAVE_QUIC
941
deadbeefab9b2d12015-10-14 11:33:11 -0700942 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000943
kwibergd1fe2812016-04-27 06:47:29 -0700944 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000945 if (config) {
946 internal_config.reset(new InternalDataChannelInit(*config));
947 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000948 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700949 InternalCreateDataChannel(label, internal_config.get()));
950 if (!channel.get()) {
951 return nullptr;
952 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000954 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
955 // the first SCTP DataChannel.
956 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
957 observer_->OnRenegotiationNeeded();
958 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000959
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 return DataChannelProxy::Create(signaling_thread(), channel.get());
961}
962
963void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
964 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100965 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700966 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
968 return;
969 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000970 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000971
972 bool value;
973 size_t mandatory_constraints = 0;
974
975 if (FindConstraint(constraints,
976 MediaConstraintsInterface::kOfferToReceiveAudio,
977 &value,
978 &mandatory_constraints)) {
979 options.offer_to_receive_audio =
980 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
981 }
982
983 if (FindConstraint(constraints,
984 MediaConstraintsInterface::kOfferToReceiveVideo,
985 &value,
986 &mandatory_constraints)) {
987 options.offer_to_receive_video =
988 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
989 }
990
991 if (FindConstraint(constraints,
992 MediaConstraintsInterface::kVoiceActivityDetection,
993 &value,
994 &mandatory_constraints)) {
995 options.voice_activity_detection = value;
996 }
997
998 if (FindConstraint(constraints,
999 MediaConstraintsInterface::kIceRestart,
1000 &value,
1001 &mandatory_constraints)) {
1002 options.ice_restart = value;
1003 }
1004
1005 if (FindConstraint(constraints,
1006 MediaConstraintsInterface::kUseRtpMux,
1007 &value,
1008 &mandatory_constraints)) {
1009 options.use_rtp_mux = value;
1010 }
1011
1012 CreateOffer(observer, options);
1013}
1014
1015void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1016 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001017 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001018 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001019 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1020 return;
1021 }
deadbeefab9b2d12015-10-14 11:33:11 -07001022
1023 cricket::MediaSessionOptions session_options;
1024 if (!GetOptionsForOffer(options, &session_options)) {
1025 std::string error = "CreateOffer called with invalid options.";
1026 LOG(LS_ERROR) << error;
1027 PostCreateSessionDescriptionFailure(observer, error);
1028 return;
1029 }
1030
1031 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032}
1033
1034void PeerConnection::CreateAnswer(
1035 CreateSessionDescriptionObserver* observer,
1036 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001037 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001038 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1040 return;
1041 }
deadbeefab9b2d12015-10-14 11:33:11 -07001042
1043 cricket::MediaSessionOptions session_options;
1044 if (!GetOptionsForAnswer(constraints, &session_options)) {
1045 std::string error = "CreateAnswer called with invalid constraints.";
1046 LOG(LS_ERROR) << error;
1047 PostCreateSessionDescriptionFailure(observer, error);
1048 return;
1049 }
1050
htaa2a49d92016-03-04 02:51:39 -08001051 session_->CreateAnswer(observer, session_options);
1052}
1053
1054void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1055 const RTCOfferAnswerOptions& options) {
1056 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1057 if (!VERIFY(observer != nullptr)) {
1058 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1059 return;
1060 }
1061
1062 cricket::MediaSessionOptions session_options;
1063 if (!GetOptionsForAnswer(options, &session_options)) {
1064 std::string error = "CreateAnswer called with invalid options.";
1065 LOG(LS_ERROR) << error;
1066 PostCreateSessionDescriptionFailure(observer, error);
1067 return;
1068 }
1069
1070 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071}
1072
1073void PeerConnection::SetLocalDescription(
1074 SetSessionDescriptionObserver* observer,
1075 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001076 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001077 if (IsClosed()) {
1078 return;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1082 return;
1083 }
1084 if (!desc) {
1085 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1086 return;
1087 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 // Update stats here so that we have the most recent stats for tracks and
1089 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001090 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 std::string error;
1092 if (!session_->SetLocalDescription(desc, &error)) {
1093 PostSetSessionDescriptionFailure(observer, error);
1094 return;
1095 }
deadbeefab9b2d12015-10-14 11:33:11 -07001096
1097 // If setting the description decided our SSL role, allocate any necessary
1098 // SCTP sids.
1099 rtc::SSLRole role;
1100 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001101 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001102 AllocateSctpSids(role);
1103 }
1104
1105 // Update state and SSRC of local MediaStreams and DataChannels based on the
1106 // local session description.
1107 const cricket::ContentInfo* audio_content =
1108 GetFirstAudioContent(desc->description());
1109 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001110 if (audio_content->rejected) {
1111 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1112 } else {
1113 const cricket::AudioContentDescription* audio_desc =
1114 static_cast<const cricket::AudioContentDescription*>(
1115 audio_content->description);
1116 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1117 }
deadbeefab9b2d12015-10-14 11:33:11 -07001118 }
1119
1120 const cricket::ContentInfo* video_content =
1121 GetFirstVideoContent(desc->description());
1122 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001123 if (video_content->rejected) {
1124 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1125 } else {
1126 const cricket::VideoContentDescription* video_desc =
1127 static_cast<const cricket::VideoContentDescription*>(
1128 video_content->description);
1129 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1130 }
deadbeefab9b2d12015-10-14 11:33:11 -07001131 }
1132
1133 const cricket::ContentInfo* data_content =
1134 GetFirstDataContent(desc->description());
1135 if (data_content) {
1136 const cricket::DataContentDescription* data_desc =
1137 static_cast<const cricket::DataContentDescription*>(
1138 data_content->description);
1139 if (rtc::starts_with(data_desc->protocol().data(),
1140 cricket::kMediaProtocolRtpPrefix)) {
1141 UpdateLocalRtpDataChannels(data_desc->streams());
1142 }
1143 }
1144
1145 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001146 signaling_thread()->Post(RTC_FROM_HERE, this,
1147 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001148
deadbeefcbecd352015-09-23 11:50:27 -07001149 // MaybeStartGathering needs to be called after posting
1150 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1151 // before signaling that SetLocalDescription completed.
1152 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001153}
1154
1155void PeerConnection::SetRemoteDescription(
1156 SetSessionDescriptionObserver* observer,
1157 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001158 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001159 if (IsClosed()) {
1160 return;
1161 }
deadbeefab9b2d12015-10-14 11:33:11 -07001162 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1164 return;
1165 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001166 if (!desc) {
1167 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1168 return;
1169 }
1170 // Update stats here so that we have the most recent stats for tracks and
1171 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001172 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 std::string error;
1174 if (!session_->SetRemoteDescription(desc, &error)) {
1175 PostSetSessionDescriptionFailure(observer, error);
1176 return;
1177 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178
deadbeefab9b2d12015-10-14 11:33:11 -07001179 // If setting the description decided our SSL role, allocate any necessary
1180 // SCTP sids.
1181 rtc::SSLRole role;
1182 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001183 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001184 AllocateSctpSids(role);
1185 }
1186
1187 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001188 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1189 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1190 const cricket::AudioContentDescription* audio_desc =
1191 GetFirstAudioContentDescription(remote_desc);
1192 const cricket::VideoContentDescription* video_desc =
1193 GetFirstVideoContentDescription(remote_desc);
1194 const cricket::DataContentDescription* data_desc =
1195 GetFirstDataContentDescription(remote_desc);
1196
1197 // Check if the descriptions include streams, just in case the peer supports
1198 // MSID, but doesn't indicate so with "a=msid-semantic".
1199 if (remote_desc->msid_supported() ||
1200 (audio_desc && !audio_desc->streams().empty()) ||
1201 (video_desc && !video_desc->streams().empty())) {
1202 remote_peer_supports_msid_ = true;
1203 }
deadbeefab9b2d12015-10-14 11:33:11 -07001204
1205 // We wait to signal new streams until we finish processing the description,
1206 // since only at that point will new streams have all their tracks.
1207 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1208
1209 // Find all audio rtp streams and create corresponding remote AudioTracks
1210 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001211 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001212 if (audio_content->rejected) {
1213 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1214 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001215 bool default_audio_track_needed =
1216 !remote_peer_supports_msid_ &&
1217 MediaContentDirectionHasSend(audio_desc->direction());
1218 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1219 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001220 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001221 }
deadbeefab9b2d12015-10-14 11:33:11 -07001222 }
1223
1224 // Find all video rtp streams and create corresponding remote VideoTracks
1225 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001226 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001227 if (video_content->rejected) {
1228 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1229 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001230 bool default_video_track_needed =
1231 !remote_peer_supports_msid_ &&
1232 MediaContentDirectionHasSend(video_desc->direction());
1233 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1234 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001235 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001236 }
deadbeefab9b2d12015-10-14 11:33:11 -07001237 }
1238
1239 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001240 if (data_desc) {
1241 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001242 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001243 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001244 }
1245 }
1246
1247 // Iterate new_streams and notify the observer about new MediaStreams.
1248 for (size_t i = 0; i < new_streams->count(); ++i) {
1249 MediaStreamInterface* new_stream = new_streams->at(i);
1250 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001251 // Call both the raw pointer and scoped_refptr versions of the method
1252 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001253 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001254 observer_->OnAddStream(
1255 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001256 }
1257
deadbeefbda7e0b2015-12-08 17:13:40 -08001258 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001259
1260 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001261 signaling_thread()->Post(RTC_FROM_HERE, this,
1262 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001263}
1264
deadbeef46c73892016-11-16 19:42:04 -08001265PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1266 return configuration_;
1267}
1268
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001269bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001270 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef46c73892016-11-16 19:42:04 -08001271 // TODO(deadbeef): Return false and log an error if there are any unsupported
1272 // modifications.
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001273 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001274 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001275 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001276 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001277 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001278 return false;
1279 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001280 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001281
1282 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1283 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001284
deadbeef46c73892016-11-16 19:42:04 -08001285 configuration_ = configuration;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001286 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001287}
1288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289bool PeerConnection::AddIceCandidate(
1290 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001291 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001292 if (IsClosed()) {
1293 return false;
1294 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 return session_->ProcessIceMessage(ice_candidate);
1296}
1297
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001298bool PeerConnection::RemoveIceCandidates(
1299 const std::vector<cricket::Candidate>& candidates) {
1300 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1301 return session_->RemoveRemoteIceCandidates(candidates);
1302}
1303
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001304void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001305 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001306 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001307
1308 if (session_) {
1309 session_->set_metrics_observer(uma_observer_);
1310 }
1311
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001312 // Send information about IPv4/IPv6 status.
1313 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001314 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001315 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001316 uma_observer_->IncrementEnumCounter(
1317 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1318 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001319 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001320 uma_observer_->IncrementEnumCounter(
1321 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1322 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001323 }
1324 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001325}
1326
ivoc14d5dbe2016-07-04 07:06:55 -07001327bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1328 int64_t max_size_bytes) {
1329 return factory_->worker_thread()->Invoke<bool>(
1330 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1331 max_size_bytes));
1332}
1333
1334void PeerConnection::StopRtcEventLog() {
1335 factory_->worker_thread()->Invoke<void>(
1336 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1337}
1338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339const SessionDescriptionInterface* PeerConnection::local_description() const {
1340 return session_->local_description();
1341}
1342
1343const SessionDescriptionInterface* PeerConnection::remote_description() const {
1344 return session_->remote_description();
1345}
1346
1347void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001348 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 // Update stats here so that we have the most recent stats for tracks and
1350 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001351 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352
deadbeefd59daf82015-10-14 15:02:44 -07001353 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354}
1355
deadbeefd59daf82015-10-14 15:02:44 -07001356void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1357 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001359 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001361 break;
deadbeefd59daf82015-10-14 15:02:44 -07001362 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1364 break;
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1367 break;
deadbeefd59daf82015-10-14 15:02:44 -07001368 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1370 break;
deadbeefd59daf82015-10-14 15:02:44 -07001371 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1373 break;
deadbeefd59daf82015-10-14 15:02:44 -07001374 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 ChangeSignalingState(PeerConnectionInterface::kStable);
1376 break;
deadbeefd59daf82015-10-14 15:02:44 -07001377 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 ChangeSignalingState(PeerConnectionInterface::kClosed);
1379 break;
1380 default:
1381 break;
1382 }
1383}
1384
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001385void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1388 SetSessionDescriptionMsg* param =
1389 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1390 param->observer->OnSuccess();
1391 delete param;
1392 break;
1393 }
1394 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1395 SetSessionDescriptionMsg* param =
1396 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1397 param->observer->OnFailure(param->error);
1398 delete param;
1399 break;
1400 }
deadbeefab9b2d12015-10-14 11:33:11 -07001401 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1402 CreateSessionDescriptionMsg* param =
1403 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1404 param->observer->OnFailure(param->error);
1405 delete param;
1406 break;
1407 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 case MSG_GETSTATS: {
1409 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001410 StatsReports reports;
1411 stats_->GetStats(param->track, &reports);
1412 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 delete param;
1414 break;
1415 }
deadbeefbd292462015-12-14 18:15:29 -08001416 case MSG_FREE_DATACHANNELS: {
1417 sctp_data_channels_to_free_.clear();
1418 break;
1419 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001420 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001421 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 break;
1423 }
1424}
1425
deadbeefab9b2d12015-10-14 11:33:11 -07001426void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001427 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001428 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001429 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1430 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001431 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001432 session_->voice_channel()));
1433
1434 receivers_.push_back(receiver);
1435 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1436 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1437 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001438}
1439
deadbeefab9b2d12015-10-14 11:33:11 -07001440void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001441 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001442 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001443 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1444 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001445 signaling_thread(),
1446 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001447 ssrc, session_->video_channel()));
1448 receivers_.push_back(receiver);
1449 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1450 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1451 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452}
1453
deadbeef70ab1a12015-09-28 16:53:55 -07001454// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1455// description.
perkjd61bf802016-03-24 03:16:19 -07001456void PeerConnection::DestroyReceiver(const std::string& track_id) {
1457 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001458 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001459 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001460 << " doesn't exist.";
1461 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001462 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001463 receivers_.erase(it);
1464 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465}
1466
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467void PeerConnection::OnIceConnectionChange(
1468 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001469 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001470 // After transitioning to "closed", ignore any additional states from
1471 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001472 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001473 return;
1474 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001476 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477}
1478
1479void PeerConnection::OnIceGatheringChange(
1480 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001481 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001482 if (IsClosed()) {
1483 return;
1484 }
1485 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001486 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487}
1488
1489void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001490 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001491 if (IsClosed()) {
1492 return;
1493 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001494 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495}
1496
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001497void PeerConnection::OnIceCandidatesRemoved(
1498 const std::vector<cricket::Candidate>& candidates) {
1499 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001500 if (IsClosed()) {
1501 return;
1502 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001503 observer_->OnIceCandidatesRemoved(candidates);
1504}
1505
Peter Thatcher54360512015-07-08 11:08:35 -07001506void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001507 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001508 if (IsClosed()) {
1509 return;
1510 }
Peter Thatcher54360512015-07-08 11:08:35 -07001511 observer_->OnIceConnectionReceivingChange(receiving);
1512}
1513
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514void PeerConnection::ChangeSignalingState(
1515 PeerConnectionInterface::SignalingState signaling_state) {
1516 signaling_state_ = signaling_state;
1517 if (signaling_state == kClosed) {
1518 ice_connection_state_ = kIceConnectionClosed;
1519 observer_->OnIceConnectionChange(ice_connection_state_);
1520 if (ice_gathering_state_ != kIceGatheringComplete) {
1521 ice_gathering_state_ = kIceGatheringComplete;
1522 observer_->OnIceGatheringChange(ice_gathering_state_);
1523 }
1524 }
1525 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526}
1527
deadbeefeb459812015-12-15 19:24:43 -08001528void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1529 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001530 if (IsClosed()) {
1531 return;
1532 }
deadbeefeb459812015-12-15 19:24:43 -08001533 auto sender = FindSenderForTrack(track);
1534 if (sender != senders_.end()) {
1535 // We already have a sender for this track, so just change the stream_id
1536 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001537 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001538 return;
1539 }
1540
1541 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001542 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1543 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001544 signaling_thread(),
1545 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1546 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001547 senders_.push_back(new_sender);
1548 // If the sender has already been configured in SDP, we call SetSsrc,
1549 // which will connect the sender to the underlying transport. This can
1550 // occur if a local session description that contains the ID of the sender
1551 // is set before AddStream is called. It can also occur if the local
1552 // session description is not changed and RemoveStream is called, and
1553 // later AddStream is called again with the same stream.
1554 const TrackInfo* track_info =
1555 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1556 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001557 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001558 }
1559}
1560
1561// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1562// indefinitely, when we have unified plan SDP.
1563void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* 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 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1571 << " doesn't exist.";
1572 return;
1573 }
deadbeefa601f5c2016-06-06 14:27:39 -07001574 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001575 senders_.erase(sender);
1576}
1577
1578void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1579 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001580 if (IsClosed()) {
1581 return;
1582 }
deadbeefeb459812015-12-15 19:24:43 -08001583 auto sender = FindSenderForTrack(track);
1584 if (sender != senders_.end()) {
1585 // We already have a sender for this track, so just change the stream_id
1586 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001587 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001588 return;
1589 }
1590
1591 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001592 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1593 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001594 signaling_thread(), new VideoRtpSender(track, stream->label(),
1595 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001596 senders_.push_back(new_sender);
1597 const TrackInfo* track_info =
1598 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1599 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001600 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001601 }
1602}
1603
1604void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1605 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001606 if (IsClosed()) {
1607 return;
1608 }
deadbeefeb459812015-12-15 19:24:43 -08001609 auto sender = FindSenderForTrack(track);
1610 if (sender == senders_.end()) {
1611 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1612 << " doesn't exist.";
1613 return;
1614 }
deadbeefa601f5c2016-06-06 14:27:39 -07001615 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001616 senders_.erase(sender);
1617}
1618
deadbeefab9b2d12015-10-14 11:33:11 -07001619void PeerConnection::PostSetSessionDescriptionFailure(
1620 SetSessionDescriptionObserver* observer,
1621 const std::string& error) {
1622 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1623 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001624 signaling_thread()->Post(RTC_FROM_HERE, this,
1625 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001626}
1627
1628void PeerConnection::PostCreateSessionDescriptionFailure(
1629 CreateSessionDescriptionObserver* observer,
1630 const std::string& error) {
1631 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1632 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001633 signaling_thread()->Post(RTC_FROM_HERE, this,
1634 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001635}
1636
1637bool PeerConnection::GetOptionsForOffer(
1638 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1639 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001640 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1641 // ContentInfos.
1642 if (session_->local_description()) {
1643 for (const cricket::ContentInfo& content :
1644 session_->local_description()->description()->contents()) {
1645 session_options->transport_options[content.name] =
1646 cricket::TransportOptions();
1647 }
1648 }
deadbeef46c73892016-11-16 19:42:04 -08001649 session_options->enable_ice_renomination =
1650 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001651
htaaac2dea2016-03-10 13:35:55 -08001652 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001653 return false;
1654 }
1655
deadbeeffac06552015-11-25 11:26:01 -08001656 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001657 // Offer to receive audio/video if the constraint is not set and there are
1658 // send streams, or we're currently receiving.
1659 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1660 session_options->recv_audio =
1661 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1662 !remote_audio_tracks_.empty();
1663 }
1664 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1665 session_options->recv_video =
1666 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1667 !remote_video_tracks_.empty();
1668 }
deadbeefc80741f2015-10-22 13:14:45 -07001669
zhihuang9763d562016-08-05 11:14:50 -07001670 // Intentionally unset the data channel type for RTP data channel with the
1671 // second condition. Otherwise the RTP data channels would be successfully
1672 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1673 // when building with chromium. We want to leave RTP data channels broken, so
1674 // people won't try to use them.
1675 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1676 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001677 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001678
zhihuangaf388472016-11-02 16:49:48 -07001679 session_options->bundle_enabled =
1680 session_options->bundle_enabled &&
1681 (session_options->has_audio() || session_options->has_video() ||
1682 session_options->has_data());
1683
zhihuang8f65cdf2016-05-06 18:40:30 -07001684 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001685 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001686 return true;
1687}
1688
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001689void PeerConnection::InitializeOptionsForAnswer(
1690 cricket::MediaSessionOptions* session_options) {
1691 session_options->recv_audio = false;
1692 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001693 session_options->enable_ice_renomination =
1694 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001695}
1696
htaa2a49d92016-03-04 02:51:39 -08001697void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001698 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001699 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1700 // ContentInfos.
1701 if (session_->remote_description()) {
1702 // Initialize the transport_options map.
1703 for (const cricket::ContentInfo& content :
1704 session_->remote_description()->description()->contents()) {
1705 session_options->transport_options[content.name] =
1706 cricket::TransportOptions();
1707 }
1708 }
deadbeeffac06552015-11-25 11:26:01 -08001709 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001710 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1711 // are not signaled in the SDP so does not go through that path and must be
1712 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001713 // Intentionally unset the data channel type for RTP data channel. Otherwise
1714 // the RTP data channels would be successfully negotiated by default and the
1715 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1716 // We want to leave RTP data channels broken, so people won't try to use them.
1717 if (session_->data_channel_type() != cricket::DCT_RTP) {
1718 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001719 }
zhihuangaf388472016-11-02 16:49:48 -07001720 session_options->bundle_enabled =
1721 session_options->bundle_enabled &&
1722 (session_options->has_audio() || session_options->has_video() ||
1723 session_options->has_data());
1724
jbauchcb560652016-08-04 05:20:32 -07001725 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001726}
1727
1728bool PeerConnection::GetOptionsForAnswer(
1729 const MediaConstraintsInterface* constraints,
1730 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001731 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001732 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1733 return false;
1734 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001735 session_options->rtcp_cname = rtcp_cname_;
1736
htaa2a49d92016-03-04 02:51:39 -08001737 FinishOptionsForAnswer(session_options);
1738 return true;
1739}
1740
1741bool PeerConnection::GetOptionsForAnswer(
1742 const RTCOfferAnswerOptions& options,
1743 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001744 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001745 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001746 return false;
1747 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001748 session_options->rtcp_cname = rtcp_cname_;
1749
htaa2a49d92016-03-04 02:51:39 -08001750 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001751 return true;
1752}
1753
deadbeeffaac4972015-11-12 15:33:07 -08001754void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1755 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001756 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1757 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001758}
1759
deadbeefab9b2d12015-10-14 11:33:11 -07001760void PeerConnection::UpdateRemoteStreamsList(
1761 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001762 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001763 cricket::MediaType media_type,
1764 StreamCollection* new_streams) {
1765 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1766
1767 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001768 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001769 auto track_it = current_tracks->begin();
1770 while (track_it != current_tracks->end()) {
1771 const TrackInfo& info = *track_it;
1772 const cricket::StreamParams* params =
1773 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001774 bool track_exists = params && params->id == info.track_id;
1775 // If this is a default track, and we still need it, don't remove it.
1776 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1777 track_exists) {
1778 ++track_it;
1779 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001780 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1781 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001782 }
1783 }
1784
1785 // Find new and active tracks.
1786 for (const cricket::StreamParams& params : streams) {
1787 // The sync_label is the MediaStream label and the |stream.id| is the
1788 // track id.
1789 const std::string& stream_label = params.sync_label;
1790 const std::string& track_id = params.id;
1791 uint32_t ssrc = params.first_ssrc();
1792
1793 rtc::scoped_refptr<MediaStreamInterface> stream =
1794 remote_streams_->find(stream_label);
1795 if (!stream) {
1796 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001797 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1798 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001799 remote_streams_->AddStream(stream);
1800 new_streams->AddStream(stream);
1801 }
1802
1803 const TrackInfo* track_info =
1804 FindTrackInfo(*current_tracks, stream_label, track_id);
1805 if (!track_info) {
1806 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1807 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1808 }
1809 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001810
1811 // Add default track if necessary.
1812 if (default_track_needed) {
1813 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1814 remote_streams_->find(kDefaultStreamLabel);
1815 if (!default_stream) {
1816 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001817 default_stream = MediaStreamProxy::Create(
1818 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001819 remote_streams_->AddStream(default_stream);
1820 new_streams->AddStream(default_stream);
1821 }
1822 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1823 ? kDefaultAudioTrackLabel
1824 : kDefaultVideoTrackLabel;
1825 const TrackInfo* default_track_info =
1826 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1827 if (!default_track_info) {
1828 current_tracks->push_back(
1829 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1830 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1831 }
1832 }
deadbeefab9b2d12015-10-14 11:33:11 -07001833}
1834
1835void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1836 const std::string& track_id,
1837 uint32_t ssrc,
1838 cricket::MediaType media_type) {
1839 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1840
1841 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001842 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001843 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001844 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001845 } else {
1846 RTC_DCHECK(false && "Invalid media type");
1847 }
1848}
1849
1850void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1851 const std::string& track_id,
1852 cricket::MediaType media_type) {
1853 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1854
1855 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001856 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1857 // will be notified which will end the AudioRtpReceiver::track().
1858 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001859 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1860 stream->FindAudioTrack(track_id);
1861 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001862 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001863 }
1864 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001865 // Stopping or destroying a VideoRtpReceiver will end the
1866 // VideoRtpReceiver::track().
1867 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001868 rtc::scoped_refptr<VideoTrackInterface> video_track =
1869 stream->FindVideoTrack(track_id);
1870 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001871 // There's no guarantee the track is still available, e.g. the track may
1872 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001873 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001874 }
1875 } else {
1876 ASSERT(false && "Invalid media type");
1877 }
1878}
1879
1880void PeerConnection::UpdateEndedRemoteMediaStreams() {
1881 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1882 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1883 MediaStreamInterface* stream = remote_streams_->at(i);
1884 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1885 streams_to_remove.push_back(stream);
1886 }
1887 }
1888
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001889 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001890 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001891 // Call both the raw pointer and scoped_refptr versions of the method
1892 // for compatibility.
1893 observer_->OnRemoveStream(stream.get());
1894 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001895 }
1896}
1897
deadbeefab9b2d12015-10-14 11:33:11 -07001898void PeerConnection::UpdateLocalTracks(
1899 const std::vector<cricket::StreamParams>& streams,
1900 cricket::MediaType media_type) {
1901 TrackInfos* current_tracks = GetLocalTracks(media_type);
1902
1903 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1904 // don't match the new StreamParam.
1905 TrackInfos::iterator track_it = current_tracks->begin();
1906 while (track_it != current_tracks->end()) {
1907 const TrackInfo& info = *track_it;
1908 const cricket::StreamParams* params =
1909 cricket::GetStreamBySsrc(streams, info.ssrc);
1910 if (!params || params->id != info.track_id ||
1911 params->sync_label != info.stream_label) {
1912 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1913 media_type);
1914 track_it = current_tracks->erase(track_it);
1915 } else {
1916 ++track_it;
1917 }
1918 }
1919
1920 // Find new and active tracks.
1921 for (const cricket::StreamParams& params : streams) {
1922 // The sync_label is the MediaStream label and the |stream.id| is the
1923 // track id.
1924 const std::string& stream_label = params.sync_label;
1925 const std::string& track_id = params.id;
1926 uint32_t ssrc = params.first_ssrc();
1927 const TrackInfo* track_info =
1928 FindTrackInfo(*current_tracks, stream_label, track_id);
1929 if (!track_info) {
1930 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1931 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1932 }
1933 }
1934}
1935
1936void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1937 const std::string& track_id,
1938 uint32_t ssrc,
1939 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001940 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001941 if (!sender) {
1942 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1943 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001944 return;
1945 }
1946
deadbeeffac06552015-11-25 11:26:01 -08001947 if (sender->media_type() != media_type) {
1948 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1949 << " description with an unexpected media type.";
1950 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001951 }
deadbeeffac06552015-11-25 11:26:01 -08001952
1953 sender->set_stream_id(stream_label);
1954 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001955}
1956
1957void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1958 const std::string& track_id,
1959 uint32_t ssrc,
1960 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001961 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001962 if (!sender) {
1963 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001964 // SessionDescriptions has been renegotiated.
1965 return;
1966 }
deadbeeffac06552015-11-25 11:26:01 -08001967
1968 // A sender has been removed from the SessionDescription but it's still
1969 // associated with the PeerConnection. This only occurs if the SDP doesn't
1970 // match with the calls to CreateSender, AddStream and RemoveStream.
1971 if (sender->media_type() != media_type) {
1972 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1973 << " description with an unexpected media type.";
1974 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001975 }
deadbeeffac06552015-11-25 11:26:01 -08001976
1977 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001978}
1979
1980void PeerConnection::UpdateLocalRtpDataChannels(
1981 const cricket::StreamParamsVec& streams) {
1982 std::vector<std::string> existing_channels;
1983
1984 // Find new and active data channels.
1985 for (const cricket::StreamParams& params : streams) {
1986 // |it->sync_label| is actually the data channel label. The reason is that
1987 // we use the same naming of data channels as we do for
1988 // MediaStreams and Tracks.
1989 // For MediaStreams, the sync_label is the MediaStream label and the
1990 // track label is the same as |streamid|.
1991 const std::string& channel_label = params.sync_label;
1992 auto data_channel_it = rtp_data_channels_.find(channel_label);
1993 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1994 continue;
1995 }
1996 // Set the SSRC the data channel should use for sending.
1997 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1998 existing_channels.push_back(data_channel_it->first);
1999 }
2000
2001 UpdateClosingRtpDataChannels(existing_channels, true);
2002}
2003
2004void PeerConnection::UpdateRemoteRtpDataChannels(
2005 const cricket::StreamParamsVec& streams) {
2006 std::vector<std::string> existing_channels;
2007
2008 // Find new and active data channels.
2009 for (const cricket::StreamParams& params : streams) {
2010 // The data channel label is either the mslabel or the SSRC if the mslabel
2011 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2012 std::string label = params.sync_label.empty()
2013 ? rtc::ToString(params.first_ssrc())
2014 : params.sync_label;
2015 auto data_channel_it = rtp_data_channels_.find(label);
2016 if (data_channel_it == rtp_data_channels_.end()) {
2017 // This is a new data channel.
2018 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2019 } else {
2020 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2021 }
2022 existing_channels.push_back(label);
2023 }
2024
2025 UpdateClosingRtpDataChannels(existing_channels, false);
2026}
2027
2028void PeerConnection::UpdateClosingRtpDataChannels(
2029 const std::vector<std::string>& active_channels,
2030 bool is_local_update) {
2031 auto it = rtp_data_channels_.begin();
2032 while (it != rtp_data_channels_.end()) {
2033 DataChannel* data_channel = it->second;
2034 if (std::find(active_channels.begin(), active_channels.end(),
2035 data_channel->label()) != active_channels.end()) {
2036 ++it;
2037 continue;
2038 }
2039
2040 if (is_local_update) {
2041 data_channel->SetSendSsrc(0);
2042 } else {
2043 data_channel->RemotePeerRequestClose();
2044 }
2045
2046 if (data_channel->state() == DataChannel::kClosed) {
2047 rtp_data_channels_.erase(it);
2048 it = rtp_data_channels_.begin();
2049 } else {
2050 ++it;
2051 }
2052 }
2053}
2054
2055void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2056 uint32_t remote_ssrc) {
2057 rtc::scoped_refptr<DataChannel> channel(
2058 InternalCreateDataChannel(label, nullptr));
2059 if (!channel.get()) {
2060 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2061 << "CreateDataChannel failed.";
2062 return;
2063 }
2064 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002065 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2066 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002067 // Call both the raw pointer and scoped_refptr versions of the method
2068 // for compatibility.
2069 observer_->OnDataChannel(proxy_channel.get());
2070 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002071}
2072
2073rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2074 const std::string& label,
2075 const InternalDataChannelInit* config) {
2076 if (IsClosed()) {
2077 return nullptr;
2078 }
2079 if (session_->data_channel_type() == cricket::DCT_NONE) {
2080 LOG(LS_ERROR)
2081 << "InternalCreateDataChannel: Data is not supported in this call.";
2082 return nullptr;
2083 }
2084 InternalDataChannelInit new_config =
2085 config ? (*config) : InternalDataChannelInit();
2086 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2087 if (new_config.id < 0) {
2088 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002089 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002090 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2091 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2092 return nullptr;
2093 }
2094 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2095 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2096 << "because the id is already in use or out of range.";
2097 return nullptr;
2098 }
2099 }
2100
2101 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2102 session_.get(), session_->data_channel_type(), label, new_config));
2103 if (!channel) {
2104 sid_allocator_.ReleaseSid(new_config.id);
2105 return nullptr;
2106 }
2107
2108 if (channel->data_channel_type() == cricket::DCT_RTP) {
2109 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2110 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2111 << " already exists.";
2112 return nullptr;
2113 }
2114 rtp_data_channels_[channel->label()] = channel;
2115 } else {
2116 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2117 sctp_data_channels_.push_back(channel);
2118 channel->SignalClosed.connect(this,
2119 &PeerConnection::OnSctpDataChannelClosed);
2120 }
2121
hbos82ebe022016-11-14 01:41:09 -08002122 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002123 return channel;
2124}
2125
2126bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002127#ifdef HAVE_QUIC
2128 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2129 (session_->quic_data_transport() &&
2130 session_->quic_data_transport()->HasDataChannels());
2131#else
deadbeefab9b2d12015-10-14 11:33:11 -07002132 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002133#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002134}
2135
2136void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2137 for (const auto& channel : sctp_data_channels_) {
2138 if (channel->id() < 0) {
2139 int sid;
2140 if (!sid_allocator_.AllocateSid(role, &sid)) {
2141 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2142 continue;
2143 }
2144 channel->SetSctpSid(sid);
2145 }
2146 }
2147}
2148
2149void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002150 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002151 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2152 ++it) {
2153 if (it->get() == channel) {
2154 if (channel->id() >= 0) {
2155 sid_allocator_.ReleaseSid(channel->id());
2156 }
deadbeefbd292462015-12-14 18:15:29 -08002157 // Since this method is triggered by a signal from the DataChannel,
2158 // we can't free it directly here; we need to free it asynchronously.
2159 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002160 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002161 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2162 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002163 return;
2164 }
2165 }
2166}
2167
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002168void PeerConnection::OnVoiceChannelCreated() {
2169 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2170 session_->voice_channel(), senders_, receivers_,
2171 cricket::MEDIA_TYPE_AUDIO);
2172}
2173
deadbeefab9b2d12015-10-14 11:33:11 -07002174void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002175 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2176 cricket::VoiceChannel>(
2177 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2178}
2179
2180void PeerConnection::OnVideoChannelCreated() {
2181 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2182 session_->video_channel(), senders_, receivers_,
2183 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002184}
2185
2186void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002187 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2188 cricket::VideoChannel>(
2189 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002190}
2191
2192void PeerConnection::OnDataChannelCreated() {
2193 for (const auto& channel : sctp_data_channels_) {
2194 channel->OnTransportChannelCreated();
2195 }
2196}
2197
2198void PeerConnection::OnDataChannelDestroyed() {
2199 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2200 // DataChannel may callback to us and try to modify the list.
2201 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2202 temp_rtp_dcs.swap(rtp_data_channels_);
2203 for (const auto& kv : temp_rtp_dcs) {
2204 kv.second->OnTransportChannelDestroyed();
2205 }
2206
2207 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2208 temp_sctp_dcs.swap(sctp_data_channels_);
2209 for (const auto& channel : temp_sctp_dcs) {
2210 channel->OnTransportChannelDestroyed();
2211 }
2212}
2213
2214void PeerConnection::OnDataChannelOpenMessage(
2215 const std::string& label,
2216 const InternalDataChannelInit& config) {
2217 rtc::scoped_refptr<DataChannel> channel(
2218 InternalCreateDataChannel(label, &config));
2219 if (!channel.get()) {
2220 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2221 return;
2222 }
2223
deadbeefa601f5c2016-06-06 14:27:39 -07002224 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2225 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002226 // Call both the raw pointer and scoped_refptr versions of the method
2227 // for compatibility.
2228 observer_->OnDataChannel(proxy_channel.get());
2229 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002230}
2231
deadbeefa601f5c2016-06-06 14:27:39 -07002232RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2233 auto it = std::find_if(
2234 senders_.begin(), senders_.end(),
2235 [id](const rtc::scoped_refptr<
2236 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2237 return sender->id() == id;
2238 });
2239 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002240}
2241
deadbeefa601f5c2016-06-06 14:27:39 -07002242std::vector<
2243 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002244PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2245 return std::find_if(
2246 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002247 [track](const rtc::scoped_refptr<
2248 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002249 return sender->track() == track;
2250 });
2251}
2252
deadbeefa601f5c2016-06-06 14:27:39 -07002253std::vector<rtc::scoped_refptr<
2254 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002255PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002256 return std::find_if(
2257 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002258 [track_id](const rtc::scoped_refptr<
2259 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002260 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002261 });
2262}
2263
deadbeefab9b2d12015-10-14 11:33:11 -07002264PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2265 cricket::MediaType media_type) {
2266 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2267 media_type == cricket::MEDIA_TYPE_VIDEO);
2268 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2269 : &remote_video_tracks_;
2270}
2271
2272PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2273 cricket::MediaType media_type) {
2274 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2275 media_type == cricket::MEDIA_TYPE_VIDEO);
2276 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2277 : &local_video_tracks_;
2278}
2279
2280const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2281 const PeerConnection::TrackInfos& infos,
2282 const std::string& stream_label,
2283 const std::string track_id) const {
2284 for (const TrackInfo& track_info : infos) {
2285 if (track_info.stream_label == stream_label &&
2286 track_info.track_id == track_id) {
2287 return &track_info;
2288 }
2289 }
2290 return nullptr;
2291}
2292
2293DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2294 for (const auto& channel : sctp_data_channels_) {
2295 if (channel->id() == sid) {
2296 return channel;
2297 }
2298 }
2299 return nullptr;
2300}
2301
deadbeef91dd5672016-05-18 16:55:30 -07002302bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002303 const RTCConfiguration& configuration) {
2304 cricket::ServerAddresses stun_servers;
2305 std::vector<cricket::RelayServerConfig> turn_servers;
2306 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2307 return false;
2308 }
2309
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002310 port_allocator_->Initialize();
2311
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002312 // To handle both internal and externally created port allocator, we will
2313 // enable BUNDLE here.
2314 int portallocator_flags = port_allocator_->flags();
2315 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2316 cricket::PORTALLOCATOR_ENABLE_IPV6;
2317 // If the disable-IPv6 flag was specified, we'll not override it
2318 // by experiment.
2319 if (configuration.disable_ipv6) {
2320 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2321 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2322 "Disabled") {
2323 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2324 }
2325
2326 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2327 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2328 LOG(LS_INFO) << "TCP candidates are disabled.";
2329 }
2330
honghaiz60347052016-05-31 18:29:12 -07002331 if (configuration.candidate_network_policy ==
2332 kCandidateNetworkPolicyLowCost) {
2333 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2334 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2335 }
2336
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002337 port_allocator_->set_flags(portallocator_flags);
2338 // No step delay is used while allocating ports.
2339 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2340 port_allocator_->set_candidate_filter(
2341 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2342
2343 // Call this last since it may create pooled allocator sessions using the
2344 // properties set above.
2345 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002346 configuration.ice_candidate_pool_size,
2347 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002348 return true;
2349}
2350
deadbeef91dd5672016-05-18 16:55:30 -07002351bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002352 const RTCConfiguration& configuration) {
2353 cricket::ServerAddresses stun_servers;
2354 std::vector<cricket::RelayServerConfig> turn_servers;
2355 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2356 return false;
2357 }
2358 port_allocator_->set_candidate_filter(
2359 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2360 // Call this last since it may create pooled allocator sessions using the
2361 // candidate filter set above.
2362 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002363 configuration.ice_candidate_pool_size,
2364 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002365 return true;
2366}
2367
ivoc14d5dbe2016-07-04 07:06:55 -07002368bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2369 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002370 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002371}
2372
2373void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002374 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002375}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002376} // namespace webrtc