blob: e1f19adf3eff51594d58cf510489b6c1baf28c9c [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070037#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010038#include "webrtc/base/trace_event.h"
ossuf515ab82016-12-07 04:52:58 -080039#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070040#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kjellandera96e2d72016-02-04 23:52:28 -080041#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010042#include "webrtc/pc/channelmanager.h"
skvlad11a9cbf2016-10-07 11:53:05 -070043#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010044#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045
46namespace {
47
deadbeefab9b2d12015-10-14 11:33:11 -070048using webrtc::DataChannel;
49using webrtc::MediaConstraintsInterface;
50using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070052using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080053using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070054using webrtc::RtpSenderProxy;
55using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070056using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
deadbeefab9b2d12015-10-14 11:33:11 -070058static const char kDefaultStreamLabel[] = "default";
59static const char kDefaultAudioTrackLabel[] = "defaulta0";
60static const char kDefaultVideoTrackLabel[] = "defaultv0";
61
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062// The min number of tokens must present in Turn host uri.
63// e.g. user@turn.example.org
64static const size_t kTurnHostTokensNum = 2;
65// Number of tokens must be preset when TURN uri has transport param.
66static const size_t kTurnTransportTokensNum = 2;
67// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000068static const int kDefaultStunPort = 3478;
69static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071
72// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070073static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
zhihuang8f65cdf2016-05-06 18:40:30 -070075// The length of RTCP CNAMEs.
76static const int kRtcpCnameLength = 16;
77
deadbeef0a6c4ca2015-10-06 11:38:28 -070078// NOTE: A loop below assumes that the first value of this enum is 0 and all
79// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070081 STUN = 0, // Indicates a STUN server.
82 STUNS, // Indicates a STUN server used with a TLS session.
83 TURN, // Indicates a TURN server
84 TURNS, // Indicates a TURN server used with a TLS session.
85 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086};
tfarina5237aaf2015-11-10 23:44:30 -080087static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070088 "kValidIceServiceTypes must have as many strings as ServiceType "
89 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
91enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000092 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070094 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080096 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097};
98
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000099struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 explicit SetSessionDescriptionMsg(
101 webrtc::SetSessionDescriptionObserver* observer)
102 : observer(observer) {
103 }
104
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000105 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 std::string error;
107};
108
deadbeefab9b2d12015-10-14 11:33:11 -0700109struct CreateSessionDescriptionMsg : public rtc::MessageData {
110 explicit CreateSessionDescriptionMsg(
111 webrtc::CreateSessionDescriptionObserver* observer)
112 : observer(observer) {}
113
114 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
115 std::string error;
116};
117
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000118struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000119 GetStatsMsg(webrtc::StatsObserver* observer,
120 webrtc::MediaStreamTrackInterface* track)
121 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000123 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000124 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125};
126
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000127// |in_str| should be of format
128// stunURI = scheme ":" stun-host [ ":" stun-port ]
129// scheme = "stun" / "stuns"
130// stun-host = IP-literal / IPv4address / reg-name
131// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700132//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000133// draft-petithuguenin-behave-turn-uris-01
134// turnURI = scheme ":" turn-host [ ":" turn-port ]
135// turn-host = username@IP-literal / IPv4address / reg-name
136bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
137 ServiceType* service_type,
138 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200139 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700140 if (colonpos == std::string::npos) {
141 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000142 return false;
143 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700144 if ((colonpos + 1) == in_str.length()) {
145 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
146 return false;
147 }
148 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800149 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700150 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000151 *service_type = static_cast<ServiceType>(i);
152 break;
153 }
154 }
155 if (*service_type == INVALID) {
156 return false;
157 }
158 *hostname = in_str.substr(colonpos + 1, std::string::npos);
159 return true;
160}
161
deadbeef0a6c4ca2015-10-06 11:38:28 -0700162bool ParsePort(const std::string& in_str, int* port) {
163 // Make sure port only contains digits. FromString doesn't check this.
164 for (const char& c : in_str) {
165 if (!std::isdigit(c)) {
166 return false;
167 }
168 }
169 return rtc::FromString(in_str, port);
170}
171
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000172// This method parses IPv6 and IPv4 literal strings, along with hostnames in
173// standard hostname:port format.
174// Consider following formats as correct.
175// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700176// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000177bool ParseHostnameAndPortFromString(const std::string& in_str,
178 std::string* host,
179 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700180 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000181 if (in_str.at(0) == '[') {
182 std::string::size_type closebracket = in_str.rfind(']');
183 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 std::string::size_type colonpos = in_str.find(':', closebracket);
185 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700186 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
187 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000188 return false;
189 }
190 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700191 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000192 } else {
193 return false;
194 }
195 } else {
196 std::string::size_type colonpos = in_str.find(':');
197 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700198 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000199 return false;
200 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 } else {
203 *host = in_str;
204 }
205 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700206 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000207}
208
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800209// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700210// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200211bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
212 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800213 cricket::ServerAddresses* stun_servers,
214 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 // draft-nandakumar-rtcweb-stun-uri-01
216 // stunURI = scheme ":" stun-host [ ":" stun-port ]
217 // scheme = "stun" / "stuns"
218 // stun-host = IP-literal / IPv4address / reg-name
219 // stun-port = *DIGIT
220
221 // draft-petithuguenin-behave-turn-uris-01
222 // turnURI = scheme ":" turn-host [ ":" turn-port ]
223 // [ "?transport=" transport ]
224 // scheme = "turn" / "turns"
225 // transport = "udp" / "tcp" / transport-ext
226 // transport-ext = 1*unreserved
227 // turn-host = IP-literal / IPv4address / reg-name
228 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800229 RTC_DCHECK(stun_servers != nullptr);
230 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200231 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800232 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700233 RTC_DCHECK(!url.empty());
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
deadbeef3edec7c2016-12-10 11:44:26 -0800435static const char* const kRtcErrorNames[] = {
436 "NONE",
437 "UNSUPPORTED_PARAMETER",
438 "INVALID_PARAMETER",
439 "INVALID_RANGE",
440 "SYNTAX_ERROR",
441 "INVALID_STATE",
442 "INVALID_MODIFICATION",
443 "NETWORK_ERROR",
444 "INTERNAL_ERROR",
445};
446
447std::ostream& operator<<(std::ostream& stream, RtcError error) {
448 int index = static_cast<int>(error);
449 RTC_CHECK(index < static_cast<int>(sizeof(kRtcErrorNames) /
450 sizeof(kRtcErrorNames[0])));
451 return stream << kRtcErrorNames[index];
452}
453
zhihuang8f65cdf2016-05-06 18:40:30 -0700454// Generate a RTCP CNAME when a PeerConnection is created.
455std::string GenerateRtcpCname() {
456 std::string cname;
457 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
458 LOG(LS_ERROR) << "Failed to generate CNAME.";
459 RTC_DCHECK(false);
460 }
461 return cname;
462}
463
htaa2a49d92016-03-04 02:51:39 -0800464bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700465 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800466 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700467 cricket::MediaSessionOptions* session_options) {
468 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
469 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
470 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
471 return false;
472 }
473
htaaac2dea2016-03-10 13:35:55 -0800474 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700475 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700476 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800477 } else {
478 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700479 }
htaaac2dea2016-03-10 13:35:55 -0800480 // For offers, we only offer video if we have it or it's forced by options.
481 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700482 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700483 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800484 } else if (is_offer) {
485 session_options->recv_video = false;
486 } else {
487 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700488 }
489
490 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700491 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800492 for (auto& kv : session_options->transport_options) {
493 kv.second.ice_restart = rtc_options.ice_restart;
494 }
deadbeefab9b2d12015-10-14 11:33:11 -0700495
496 return true;
497}
498
499bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
500 cricket::MediaSessionOptions* session_options) {
501 bool value = false;
502 size_t mandatory_constraints_satisfied = 0;
503
504 // kOfferToReceiveAudio defaults to true according to spec.
505 if (!FindConstraint(constraints,
506 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
507 &mandatory_constraints_satisfied) ||
508 value) {
509 session_options->recv_audio = true;
510 }
511
512 // kOfferToReceiveVideo defaults to false according to spec. But
513 // if it is an answer and video is offered, we should still accept video
514 // per default.
515 value = false;
516 if (!FindConstraint(constraints,
517 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
518 &mandatory_constraints_satisfied) ||
519 value) {
520 session_options->recv_video = true;
521 }
522
523 if (FindConstraint(constraints,
524 MediaConstraintsInterface::kVoiceActivityDetection, &value,
525 &mandatory_constraints_satisfied)) {
526 session_options->vad_enabled = value;
527 }
528
529 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
530 &mandatory_constraints_satisfied)) {
531 session_options->bundle_enabled = value;
532 } else {
533 // kUseRtpMux defaults to true according to spec.
534 session_options->bundle_enabled = true;
535 }
deadbeefab9b2d12015-10-14 11:33:11 -0700536
deadbeef0ed85b22016-02-23 17:24:52 -0800537 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700538 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
539 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700540 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800541 ice_restart = true;
542 }
543 for (auto& kv : session_options->transport_options) {
544 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700545 }
546
547 if (!constraints) {
548 return true;
549 }
550 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
551}
552
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200553bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800554 cricket::ServerAddresses* stun_servers,
555 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200556 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
557 if (!server.urls.empty()) {
558 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200559 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700560 LOG(LS_ERROR) << "Empty uri.";
561 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200562 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800563 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200564 return false;
565 }
566 }
567 } else if (!server.uri.empty()) {
568 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800569 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000570 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200571 }
572 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700573 LOG(LS_ERROR) << "Empty uri.";
574 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575 }
576 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800577 // Candidates must have unique priorities, so that connectivity checks
578 // are performed in a well-defined order.
579 int priority = static_cast<int>(turn_servers->size() - 1);
580 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
581 // First in the list gets highest priority.
582 turn_server.priority = priority--;
583 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000584 return true;
585}
586
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587PeerConnection::PeerConnection(PeerConnectionFactory* factory)
588 : factory_(factory),
589 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000590 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700593 ice_gathering_state_(kIceGatheringNew),
skvlad11a9cbf2016-10-07 11:53:05 -0700594 event_log_(RtcEventLog::Create(webrtc::Clock::GetRealTimeClock())),
zhihuang8f65cdf2016-05-06 18:40:30 -0700595 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700596 local_streams_(StreamCollection::Create()),
597 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598
599PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100600 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700601 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700602 // Need to detach RTP senders/receivers from WebRtcSession,
603 // since it's about to be destroyed.
604 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700605 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700606 }
607 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700608 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700609 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700610 // Destroy stats_ because it depends on session_.
611 stats_.reset(nullptr);
612 // Now destroy session_ before destroying other members,
613 // because its destruction fires signals (such as VoiceChannelDestroyed)
614 // which will trigger some final actions in PeerConnection...
615 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700616 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700617 network_thread()->Invoke<void>(RTC_FROM_HERE,
618 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619}
620
621bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000622 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700623 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200624 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800625 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100626 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800627 RTC_DCHECK(observer != nullptr);
628 if (!observer) {
629 return false;
630 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000631 observer_ = observer;
632
kwiberg0eb15ed2015-12-17 03:04:15 -0800633 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800634
deadbeef91dd5672016-05-18 16:55:30 -0700635 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700636 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700637 if (!network_thread()->Invoke<bool>(
638 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
639 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 return false;
641 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000642
skvlad11a9cbf2016-10-07 11:53:05 -0700643 media_controller_.reset(factory_->CreateMediaController(
644 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645
zhihuang29ff8442016-07-27 11:07:25 -0700646 session_.reset(new WebRtcSession(
647 media_controller_.get(), factory_->network_thread(),
648 factory_->worker_thread(), factory_->signaling_thread(),
649 port_allocator_.get(),
650 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700651 factory_->CreateTransportController(
652 port_allocator_.get(),
653 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700654
deadbeefab9b2d12015-10-14 11:33:11 -0700655 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700656 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657
658 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200659 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800660 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000661 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700662 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664 // Register PeerConnection as receiver of local ice candidates.
665 // All the callbacks will be posted to the application from PeerConnection.
666 session_->RegisterIceObserver(this);
667 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700668 session_->SignalVoiceChannelCreated.connect(
669 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700670 session_->SignalVoiceChannelDestroyed.connect(
671 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700672 session_->SignalVideoChannelCreated.connect(
673 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700674 session_->SignalVideoChannelDestroyed.connect(
675 this, &PeerConnection::OnVideoChannelDestroyed);
676 session_->SignalDataChannelCreated.connect(
677 this, &PeerConnection::OnDataChannelCreated);
678 session_->SignalDataChannelDestroyed.connect(
679 this, &PeerConnection::OnDataChannelDestroyed);
680 session_->SignalDataChannelOpenMessage.connect(
681 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800682
683 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 return true;
685}
686
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000687rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700689 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690}
691
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000692rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700694 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695}
696
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000697bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100698 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 if (IsClosed()) {
700 return false;
701 }
deadbeefab9b2d12015-10-14 11:33:11 -0700702 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 return false;
704 }
deadbeefab9b2d12015-10-14 11:33:11 -0700705
706 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800707 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
708 observer->SignalAudioTrackAdded.connect(this,
709 &PeerConnection::OnAudioTrackAdded);
710 observer->SignalAudioTrackRemoved.connect(
711 this, &PeerConnection::OnAudioTrackRemoved);
712 observer->SignalVideoTrackAdded.connect(this,
713 &PeerConnection::OnVideoTrackAdded);
714 observer->SignalVideoTrackRemoved.connect(
715 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700716 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700717
deadbeefab9b2d12015-10-14 11:33:11 -0700718 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800719 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700720 }
721 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800722 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700723 }
724
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000725 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 observer_->OnRenegotiationNeeded();
727 return true;
728}
729
730void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100731 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700732 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800733 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700734 }
735 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800736 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700737 }
738
739 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800740 stream_observers_.erase(
741 std::remove_if(
742 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700743 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800744 return observer->stream()->label().compare(local_stream->label()) ==
745 0;
746 }),
747 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700748
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 if (IsClosed()) {
750 return;
751 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752 observer_->OnRenegotiationNeeded();
753}
754
deadbeefe1f9d832016-01-14 15:35:42 -0800755rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
756 MediaStreamTrackInterface* track,
757 std::vector<MediaStreamInterface*> streams) {
758 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
759 if (IsClosed()) {
760 return nullptr;
761 }
762 if (streams.size() >= 2) {
763 LOG(LS_ERROR)
764 << "Adding a track with two streams is not currently supported.";
765 return nullptr;
766 }
767 // TODO(deadbeef): Support adding a track to two different senders.
768 if (FindSenderForTrack(track) != senders_.end()) {
769 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
770 return nullptr;
771 }
772
773 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700774 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800775 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700776 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800777 signaling_thread(),
778 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700779 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800780 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700781 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800782 }
783 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700784 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800785 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700786 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800787 }
788 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700789 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800790 signaling_thread(),
791 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700792 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800793 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700794 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800795 }
796 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700797 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800798 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700799 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800800 }
801 } else {
802 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
803 return rtc::scoped_refptr<RtpSenderInterface>();
804 }
805
806 senders_.push_back(new_sender);
807 observer_->OnRenegotiationNeeded();
808 return new_sender;
809}
810
811bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
812 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
813 if (IsClosed()) {
814 return false;
815 }
816
817 auto it = std::find(senders_.begin(), senders_.end(), sender);
818 if (it == senders_.end()) {
819 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
820 return false;
821 }
deadbeefa601f5c2016-06-06 14:27:39 -0700822 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800823 senders_.erase(it);
824
825 observer_->OnRenegotiationNeeded();
826 return true;
827}
828
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000829rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000830 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100831 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700832 if (IsClosed()) {
833 return nullptr;
834 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 if (!track) {
836 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
837 return NULL;
838 }
deadbeefab9b2d12015-10-14 11:33:11 -0700839 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
841 return NULL;
842 }
843
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000844 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000845 DtmfSender::Create(track, signaling_thread(), session_.get()));
846 if (!sender.get()) {
847 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
848 return NULL;
849 }
850 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
851}
852
deadbeeffac06552015-11-25 11:26:01 -0800853rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800854 const std::string& kind,
855 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100856 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700857 if (IsClosed()) {
858 return nullptr;
859 }
deadbeefa601f5c2016-06-06 14:27:39 -0700860 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800861 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700862 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700863 signaling_thread(),
864 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800865 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700866 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700867 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800868 } else {
869 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800870 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800871 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800872 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700873 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800874 }
deadbeeffac06552015-11-25 11:26:01 -0800875 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800876 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800877}
878
deadbeef70ab1a12015-09-28 16:53:55 -0700879std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
880 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700881 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
882 for (const auto& sender : senders_) {
883 ret.push_back(sender.get());
884 }
885 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700886}
887
888std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
889PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700890 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
891 for (const auto& receiver : receivers_) {
892 ret.push_back(receiver.get());
893 }
894 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700895}
896
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000898 MediaStreamTrackInterface* track,
899 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100900 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700901 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000902 if (!VERIFY(observer != NULL)) {
903 LOG(LS_ERROR) << "GetStats - observer is NULL.";
904 return false;
905 }
906
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000907 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700908 // The StatsCollector is used to tell if a track is valid because it may
909 // remember tracks that the PeerConnection previously removed.
910 if (track && !stats_->IsValidTrack(track->id())) {
911 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
912 << track->id();
913 return false;
914 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700915 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000916 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return true;
918}
919
hbos74e1a4f2016-09-15 23:33:01 -0700920void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
921 RTC_DCHECK(stats_collector_);
922 stats_collector_->GetStatsReport(callback);
923}
924
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
926 return signaling_state_;
927}
928
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929PeerConnectionInterface::IceConnectionState
930PeerConnection::ice_connection_state() {
931 return ice_connection_state_;
932}
933
934PeerConnectionInterface::IceGatheringState
935PeerConnection::ice_gathering_state() {
936 return ice_gathering_state_;
937}
938
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000939rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940PeerConnection::CreateDataChannel(
941 const std::string& label,
942 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100943 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700944#ifdef HAVE_QUIC
945 if (session_->data_channel_type() == cricket::DCT_QUIC) {
946 // TODO(zhihuang): Handle case when config is NULL.
947 if (!config) {
948 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
949 return nullptr;
950 }
951 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
952 if (!config->reliable || config->ordered) {
953 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
954 "ordered delivery.";
955 return nullptr;
956 }
957 return session_->quic_data_transport()->CreateDataChannel(label, config);
958 }
959#endif // HAVE_QUIC
960
deadbeefab9b2d12015-10-14 11:33:11 -0700961 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000962
kwibergd1fe2812016-04-27 06:47:29 -0700963 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000964 if (config) {
965 internal_config.reset(new InternalDataChannelInit(*config));
966 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000967 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700968 InternalCreateDataChannel(label, internal_config.get()));
969 if (!channel.get()) {
970 return nullptr;
971 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000973 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
974 // the first SCTP DataChannel.
975 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
976 observer_->OnRenegotiationNeeded();
977 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000978
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979 return DataChannelProxy::Create(signaling_thread(), channel.get());
980}
981
982void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
983 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100984 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700985 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
987 return;
988 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000989 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000990
991 bool value;
992 size_t mandatory_constraints = 0;
993
994 if (FindConstraint(constraints,
995 MediaConstraintsInterface::kOfferToReceiveAudio,
996 &value,
997 &mandatory_constraints)) {
998 options.offer_to_receive_audio =
999 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1000 }
1001
1002 if (FindConstraint(constraints,
1003 MediaConstraintsInterface::kOfferToReceiveVideo,
1004 &value,
1005 &mandatory_constraints)) {
1006 options.offer_to_receive_video =
1007 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1008 }
1009
1010 if (FindConstraint(constraints,
1011 MediaConstraintsInterface::kVoiceActivityDetection,
1012 &value,
1013 &mandatory_constraints)) {
1014 options.voice_activity_detection = value;
1015 }
1016
1017 if (FindConstraint(constraints,
1018 MediaConstraintsInterface::kIceRestart,
1019 &value,
1020 &mandatory_constraints)) {
1021 options.ice_restart = value;
1022 }
1023
1024 if (FindConstraint(constraints,
1025 MediaConstraintsInterface::kUseRtpMux,
1026 &value,
1027 &mandatory_constraints)) {
1028 options.use_rtp_mux = value;
1029 }
1030
1031 CreateOffer(observer, options);
1032}
1033
1034void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1035 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001036 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001037 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001038 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1039 return;
1040 }
deadbeefab9b2d12015-10-14 11:33:11 -07001041
1042 cricket::MediaSessionOptions session_options;
1043 if (!GetOptionsForOffer(options, &session_options)) {
1044 std::string error = "CreateOffer called with invalid options.";
1045 LOG(LS_ERROR) << error;
1046 PostCreateSessionDescriptionFailure(observer, error);
1047 return;
1048 }
1049
1050 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051}
1052
1053void PeerConnection::CreateAnswer(
1054 CreateSessionDescriptionObserver* observer,
1055 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001056 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001057 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1059 return;
1060 }
deadbeefab9b2d12015-10-14 11:33:11 -07001061
1062 cricket::MediaSessionOptions session_options;
1063 if (!GetOptionsForAnswer(constraints, &session_options)) {
1064 std::string error = "CreateAnswer called with invalid constraints.";
1065 LOG(LS_ERROR) << error;
1066 PostCreateSessionDescriptionFailure(observer, error);
1067 return;
1068 }
1069
htaa2a49d92016-03-04 02:51:39 -08001070 session_->CreateAnswer(observer, session_options);
1071}
1072
1073void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1074 const RTCOfferAnswerOptions& options) {
1075 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1076 if (!VERIFY(observer != nullptr)) {
1077 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1078 return;
1079 }
1080
1081 cricket::MediaSessionOptions session_options;
1082 if (!GetOptionsForAnswer(options, &session_options)) {
1083 std::string error = "CreateAnswer called with invalid options.";
1084 LOG(LS_ERROR) << error;
1085 PostCreateSessionDescriptionFailure(observer, error);
1086 return;
1087 }
1088
1089 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090}
1091
1092void PeerConnection::SetLocalDescription(
1093 SetSessionDescriptionObserver* observer,
1094 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001095 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001096 if (IsClosed()) {
1097 return;
1098 }
deadbeefab9b2d12015-10-14 11:33:11 -07001099 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1101 return;
1102 }
1103 if (!desc) {
1104 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1105 return;
1106 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001107 // Update stats here so that we have the most recent stats for tracks and
1108 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001109 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 std::string error;
1111 if (!session_->SetLocalDescription(desc, &error)) {
1112 PostSetSessionDescriptionFailure(observer, error);
1113 return;
1114 }
deadbeefab9b2d12015-10-14 11:33:11 -07001115
1116 // If setting the description decided our SSL role, allocate any necessary
1117 // SCTP sids.
1118 rtc::SSLRole role;
1119 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001120 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001121 AllocateSctpSids(role);
1122 }
1123
1124 // Update state and SSRC of local MediaStreams and DataChannels based on the
1125 // local session description.
1126 const cricket::ContentInfo* audio_content =
1127 GetFirstAudioContent(desc->description());
1128 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001129 if (audio_content->rejected) {
1130 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1131 } else {
1132 const cricket::AudioContentDescription* audio_desc =
1133 static_cast<const cricket::AudioContentDescription*>(
1134 audio_content->description);
1135 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1136 }
deadbeefab9b2d12015-10-14 11:33:11 -07001137 }
1138
1139 const cricket::ContentInfo* video_content =
1140 GetFirstVideoContent(desc->description());
1141 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001142 if (video_content->rejected) {
1143 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1144 } else {
1145 const cricket::VideoContentDescription* video_desc =
1146 static_cast<const cricket::VideoContentDescription*>(
1147 video_content->description);
1148 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1149 }
deadbeefab9b2d12015-10-14 11:33:11 -07001150 }
1151
1152 const cricket::ContentInfo* data_content =
1153 GetFirstDataContent(desc->description());
1154 if (data_content) {
1155 const cricket::DataContentDescription* data_desc =
1156 static_cast<const cricket::DataContentDescription*>(
1157 data_content->description);
1158 if (rtc::starts_with(data_desc->protocol().data(),
1159 cricket::kMediaProtocolRtpPrefix)) {
1160 UpdateLocalRtpDataChannels(data_desc->streams());
1161 }
1162 }
1163
1164 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001165 signaling_thread()->Post(RTC_FROM_HERE, this,
1166 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001167
deadbeefcbecd352015-09-23 11:50:27 -07001168 // MaybeStartGathering needs to be called after posting
1169 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1170 // before signaling that SetLocalDescription completed.
1171 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172}
1173
1174void PeerConnection::SetRemoteDescription(
1175 SetSessionDescriptionObserver* observer,
1176 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001177 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001178 if (IsClosed()) {
1179 return;
1180 }
deadbeefab9b2d12015-10-14 11:33:11 -07001181 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001182 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1183 return;
1184 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185 if (!desc) {
1186 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1187 return;
1188 }
1189 // Update stats here so that we have the most recent stats for tracks and
1190 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001191 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001192 std::string error;
1193 if (!session_->SetRemoteDescription(desc, &error)) {
1194 PostSetSessionDescriptionFailure(observer, error);
1195 return;
1196 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197
deadbeefab9b2d12015-10-14 11:33:11 -07001198 // If setting the description decided our SSL role, allocate any necessary
1199 // SCTP sids.
1200 rtc::SSLRole role;
1201 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001202 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001203 AllocateSctpSids(role);
1204 }
1205
1206 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001207 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1208 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1209 const cricket::AudioContentDescription* audio_desc =
1210 GetFirstAudioContentDescription(remote_desc);
1211 const cricket::VideoContentDescription* video_desc =
1212 GetFirstVideoContentDescription(remote_desc);
1213 const cricket::DataContentDescription* data_desc =
1214 GetFirstDataContentDescription(remote_desc);
1215
1216 // Check if the descriptions include streams, just in case the peer supports
1217 // MSID, but doesn't indicate so with "a=msid-semantic".
1218 if (remote_desc->msid_supported() ||
1219 (audio_desc && !audio_desc->streams().empty()) ||
1220 (video_desc && !video_desc->streams().empty())) {
1221 remote_peer_supports_msid_ = true;
1222 }
deadbeefab9b2d12015-10-14 11:33:11 -07001223
1224 // We wait to signal new streams until we finish processing the description,
1225 // since only at that point will new streams have all their tracks.
1226 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1227
1228 // Find all audio rtp streams and create corresponding remote AudioTracks
1229 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001230 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001231 if (audio_content->rejected) {
1232 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1233 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001234 bool default_audio_track_needed =
1235 !remote_peer_supports_msid_ &&
1236 MediaContentDirectionHasSend(audio_desc->direction());
1237 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1238 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001239 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001240 }
deadbeefab9b2d12015-10-14 11:33:11 -07001241 }
1242
1243 // Find all video rtp streams and create corresponding remote VideoTracks
1244 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001245 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001246 if (video_content->rejected) {
1247 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1248 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001249 bool default_video_track_needed =
1250 !remote_peer_supports_msid_ &&
1251 MediaContentDirectionHasSend(video_desc->direction());
1252 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1253 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001254 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001255 }
deadbeefab9b2d12015-10-14 11:33:11 -07001256 }
1257
1258 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001259 if (data_desc) {
1260 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001261 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001262 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001263 }
1264 }
1265
1266 // Iterate new_streams and notify the observer about new MediaStreams.
1267 for (size_t i = 0; i < new_streams->count(); ++i) {
1268 MediaStreamInterface* new_stream = new_streams->at(i);
1269 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001270 // Call both the raw pointer and scoped_refptr versions of the method
1271 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001272 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001273 observer_->OnAddStream(
1274 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001275 }
1276
deadbeefbda7e0b2015-12-08 17:13:40 -08001277 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001278
1279 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001280 signaling_thread()->Post(RTC_FROM_HERE, this,
1281 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001282}
1283
deadbeef46c73892016-11-16 19:42:04 -08001284PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1285 return configuration_;
1286}
1287
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001288bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001289 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef46c73892016-11-16 19:42:04 -08001290 // TODO(deadbeef): Return false and log an error if there are any unsupported
1291 // modifications.
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001292 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001293 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001294 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001295 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001296 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001297 return false;
1298 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001299 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001300
1301 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1302 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001303
deadbeef46c73892016-11-16 19:42:04 -08001304 configuration_ = configuration;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001305 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001306}
1307
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308bool PeerConnection::AddIceCandidate(
1309 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001310 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001311 if (IsClosed()) {
1312 return false;
1313 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314 return session_->ProcessIceMessage(ice_candidate);
1315}
1316
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001317bool PeerConnection::RemoveIceCandidates(
1318 const std::vector<cricket::Candidate>& candidates) {
1319 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1320 return session_->RemoveRemoteIceCandidates(candidates);
1321}
1322
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001323void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001324 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001325 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001326
1327 if (session_) {
1328 session_->set_metrics_observer(uma_observer_);
1329 }
1330
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001331 // Send information about IPv4/IPv6 status.
1332 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001333 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001334 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001335 uma_observer_->IncrementEnumCounter(
1336 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1337 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001338 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001339 uma_observer_->IncrementEnumCounter(
1340 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1341 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001342 }
1343 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001344}
1345
ivoc14d5dbe2016-07-04 07:06:55 -07001346bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1347 int64_t max_size_bytes) {
1348 return factory_->worker_thread()->Invoke<bool>(
1349 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1350 max_size_bytes));
1351}
1352
1353void PeerConnection::StopRtcEventLog() {
1354 factory_->worker_thread()->Invoke<void>(
1355 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1356}
1357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358const SessionDescriptionInterface* PeerConnection::local_description() const {
1359 return session_->local_description();
1360}
1361
1362const SessionDescriptionInterface* PeerConnection::remote_description() const {
1363 return session_->remote_description();
1364}
1365
1366void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001367 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 // Update stats here so that we have the most recent stats for tracks and
1369 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001370 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371
deadbeefd59daf82015-10-14 15:02:44 -07001372 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373}
1374
deadbeefd59daf82015-10-14 15:02:44 -07001375void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1376 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001378 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001380 break;
deadbeefd59daf82015-10-14 15:02:44 -07001381 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001382 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1383 break;
deadbeefd59daf82015-10-14 15:02:44 -07001384 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1386 break;
deadbeefd59daf82015-10-14 15:02:44 -07001387 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1389 break;
deadbeefd59daf82015-10-14 15:02:44 -07001390 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1392 break;
deadbeefd59daf82015-10-14 15:02:44 -07001393 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394 ChangeSignalingState(PeerConnectionInterface::kStable);
1395 break;
deadbeefd59daf82015-10-14 15:02:44 -07001396 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001397 ChangeSignalingState(PeerConnectionInterface::kClosed);
1398 break;
1399 default:
1400 break;
1401 }
1402}
1403
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001404void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1407 SetSessionDescriptionMsg* param =
1408 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1409 param->observer->OnSuccess();
1410 delete param;
1411 break;
1412 }
1413 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1414 SetSessionDescriptionMsg* param =
1415 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1416 param->observer->OnFailure(param->error);
1417 delete param;
1418 break;
1419 }
deadbeefab9b2d12015-10-14 11:33:11 -07001420 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1421 CreateSessionDescriptionMsg* param =
1422 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1423 param->observer->OnFailure(param->error);
1424 delete param;
1425 break;
1426 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427 case MSG_GETSTATS: {
1428 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001429 StatsReports reports;
1430 stats_->GetStats(param->track, &reports);
1431 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 delete param;
1433 break;
1434 }
deadbeefbd292462015-12-14 18:15:29 -08001435 case MSG_FREE_DATACHANNELS: {
1436 sctp_data_channels_to_free_.clear();
1437 break;
1438 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001440 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001441 break;
1442 }
1443}
1444
deadbeefab9b2d12015-10-14 11:33:11 -07001445void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001446 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001447 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001448 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1449 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001450 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001451 session_->voice_channel()));
1452
1453 receivers_.push_back(receiver);
1454 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1455 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1456 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457}
1458
deadbeefab9b2d12015-10-14 11:33:11 -07001459void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001460 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001461 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001462 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1463 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001464 signaling_thread(),
1465 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001466 ssrc, session_->video_channel()));
1467 receivers_.push_back(receiver);
1468 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1469 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1470 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471}
1472
deadbeef70ab1a12015-09-28 16:53:55 -07001473// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1474// description.
perkjd61bf802016-03-24 03:16:19 -07001475void PeerConnection::DestroyReceiver(const std::string& track_id) {
1476 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001477 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001478 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001479 << " doesn't exist.";
1480 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001481 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001482 receivers_.erase(it);
1483 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001484}
1485
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486void PeerConnection::OnIceConnectionChange(
1487 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001488 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001489 // After transitioning to "closed", ignore any additional states from
1490 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001491 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001492 return;
1493 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001495 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001496}
1497
1498void PeerConnection::OnIceGatheringChange(
1499 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001500 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501 if (IsClosed()) {
1502 return;
1503 }
1504 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001505 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001506}
1507
1508void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001509 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001510 if (IsClosed()) {
1511 return;
1512 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001513 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514}
1515
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001516void PeerConnection::OnIceCandidatesRemoved(
1517 const std::vector<cricket::Candidate>& candidates) {
1518 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001519 if (IsClosed()) {
1520 return;
1521 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001522 observer_->OnIceCandidatesRemoved(candidates);
1523}
1524
Peter Thatcher54360512015-07-08 11:08:35 -07001525void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001526 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001527 if (IsClosed()) {
1528 return;
1529 }
Peter Thatcher54360512015-07-08 11:08:35 -07001530 observer_->OnIceConnectionReceivingChange(receiving);
1531}
1532
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533void PeerConnection::ChangeSignalingState(
1534 PeerConnectionInterface::SignalingState signaling_state) {
1535 signaling_state_ = signaling_state;
1536 if (signaling_state == kClosed) {
1537 ice_connection_state_ = kIceConnectionClosed;
1538 observer_->OnIceConnectionChange(ice_connection_state_);
1539 if (ice_gathering_state_ != kIceGatheringComplete) {
1540 ice_gathering_state_ = kIceGatheringComplete;
1541 observer_->OnIceGatheringChange(ice_gathering_state_);
1542 }
1543 }
1544 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545}
1546
deadbeefeb459812015-12-15 19:24:43 -08001547void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1548 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001549 if (IsClosed()) {
1550 return;
1551 }
deadbeefeb459812015-12-15 19:24:43 -08001552 auto sender = FindSenderForTrack(track);
1553 if (sender != senders_.end()) {
1554 // We already have a sender for this track, so just change the stream_id
1555 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001556 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001557 return;
1558 }
1559
1560 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001561 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1562 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001563 signaling_thread(),
1564 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1565 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001566 senders_.push_back(new_sender);
1567 // If the sender has already been configured in SDP, we call SetSsrc,
1568 // which will connect the sender to the underlying transport. This can
1569 // occur if a local session description that contains the ID of the sender
1570 // is set before AddStream is called. It can also occur if the local
1571 // session description is not changed and RemoveStream is called, and
1572 // later AddStream is called again with the same stream.
1573 const TrackInfo* track_info =
1574 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1575 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001576 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001577 }
1578}
1579
1580// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1581// indefinitely, when we have unified plan SDP.
1582void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1583 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001584 if (IsClosed()) {
1585 return;
1586 }
deadbeefeb459812015-12-15 19:24:43 -08001587 auto sender = FindSenderForTrack(track);
1588 if (sender == senders_.end()) {
1589 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1590 << " doesn't exist.";
1591 return;
1592 }
deadbeefa601f5c2016-06-06 14:27:39 -07001593 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001594 senders_.erase(sender);
1595}
1596
1597void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1598 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001599 if (IsClosed()) {
1600 return;
1601 }
deadbeefeb459812015-12-15 19:24:43 -08001602 auto sender = FindSenderForTrack(track);
1603 if (sender != senders_.end()) {
1604 // We already have a sender for this track, so just change the stream_id
1605 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001606 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001607 return;
1608 }
1609
1610 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001611 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1612 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001613 signaling_thread(), new VideoRtpSender(track, stream->label(),
1614 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001615 senders_.push_back(new_sender);
1616 const TrackInfo* track_info =
1617 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1618 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001619 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001620 }
1621}
1622
1623void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1624 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001625 if (IsClosed()) {
1626 return;
1627 }
deadbeefeb459812015-12-15 19:24:43 -08001628 auto sender = FindSenderForTrack(track);
1629 if (sender == senders_.end()) {
1630 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1631 << " doesn't exist.";
1632 return;
1633 }
deadbeefa601f5c2016-06-06 14:27:39 -07001634 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001635 senders_.erase(sender);
1636}
1637
deadbeefab9b2d12015-10-14 11:33:11 -07001638void PeerConnection::PostSetSessionDescriptionFailure(
1639 SetSessionDescriptionObserver* observer,
1640 const std::string& error) {
1641 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1642 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001643 signaling_thread()->Post(RTC_FROM_HERE, this,
1644 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001645}
1646
1647void PeerConnection::PostCreateSessionDescriptionFailure(
1648 CreateSessionDescriptionObserver* observer,
1649 const std::string& error) {
1650 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1651 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001652 signaling_thread()->Post(RTC_FROM_HERE, this,
1653 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001654}
1655
1656bool PeerConnection::GetOptionsForOffer(
1657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1658 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001659 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1660 // ContentInfos.
1661 if (session_->local_description()) {
1662 for (const cricket::ContentInfo& content :
1663 session_->local_description()->description()->contents()) {
1664 session_options->transport_options[content.name] =
1665 cricket::TransportOptions();
1666 }
1667 }
deadbeef46c73892016-11-16 19:42:04 -08001668 session_options->enable_ice_renomination =
1669 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001670
htaaac2dea2016-03-10 13:35:55 -08001671 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001672 return false;
1673 }
1674
deadbeeffac06552015-11-25 11:26:01 -08001675 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001676 // Offer to receive audio/video if the constraint is not set and there are
1677 // send streams, or we're currently receiving.
1678 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1679 session_options->recv_audio =
1680 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1681 !remote_audio_tracks_.empty();
1682 }
1683 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1684 session_options->recv_video =
1685 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1686 !remote_video_tracks_.empty();
1687 }
deadbeefc80741f2015-10-22 13:14:45 -07001688
zhihuang9763d562016-08-05 11:14:50 -07001689 // Intentionally unset the data channel type for RTP data channel with the
1690 // second condition. Otherwise the RTP data channels would be successfully
1691 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1692 // when building with chromium. We want to leave RTP data channels broken, so
1693 // people won't try to use them.
1694 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1695 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001696 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001697
zhihuangaf388472016-11-02 16:49:48 -07001698 session_options->bundle_enabled =
1699 session_options->bundle_enabled &&
1700 (session_options->has_audio() || session_options->has_video() ||
1701 session_options->has_data());
1702
zhihuang8f65cdf2016-05-06 18:40:30 -07001703 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001704 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001705 return true;
1706}
1707
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001708void PeerConnection::InitializeOptionsForAnswer(
1709 cricket::MediaSessionOptions* session_options) {
1710 session_options->recv_audio = false;
1711 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001712 session_options->enable_ice_renomination =
1713 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001714}
1715
htaa2a49d92016-03-04 02:51:39 -08001716void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001717 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001718 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1719 // ContentInfos.
1720 if (session_->remote_description()) {
1721 // Initialize the transport_options map.
1722 for (const cricket::ContentInfo& content :
1723 session_->remote_description()->description()->contents()) {
1724 session_options->transport_options[content.name] =
1725 cricket::TransportOptions();
1726 }
1727 }
deadbeeffac06552015-11-25 11:26:01 -08001728 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001729 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1730 // are not signaled in the SDP so does not go through that path and must be
1731 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001732 // Intentionally unset the data channel type for RTP data channel. Otherwise
1733 // the RTP data channels would be successfully negotiated by default and the
1734 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1735 // We want to leave RTP data channels broken, so people won't try to use them.
1736 if (session_->data_channel_type() != cricket::DCT_RTP) {
1737 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001738 }
zhihuangaf388472016-11-02 16:49:48 -07001739 session_options->bundle_enabled =
1740 session_options->bundle_enabled &&
1741 (session_options->has_audio() || session_options->has_video() ||
1742 session_options->has_data());
1743
jbauchcb560652016-08-04 05:20:32 -07001744 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001745}
1746
1747bool PeerConnection::GetOptionsForAnswer(
1748 const MediaConstraintsInterface* constraints,
1749 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001750 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001751 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1752 return false;
1753 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001754 session_options->rtcp_cname = rtcp_cname_;
1755
htaa2a49d92016-03-04 02:51:39 -08001756 FinishOptionsForAnswer(session_options);
1757 return true;
1758}
1759
1760bool PeerConnection::GetOptionsForAnswer(
1761 const RTCOfferAnswerOptions& options,
1762 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001763 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001764 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001765 return false;
1766 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001767 session_options->rtcp_cname = rtcp_cname_;
1768
htaa2a49d92016-03-04 02:51:39 -08001769 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001770 return true;
1771}
1772
deadbeeffaac4972015-11-12 15:33:07 -08001773void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1774 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001775 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1776 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001777}
1778
deadbeefab9b2d12015-10-14 11:33:11 -07001779void PeerConnection::UpdateRemoteStreamsList(
1780 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001781 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001782 cricket::MediaType media_type,
1783 StreamCollection* new_streams) {
1784 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1785
1786 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001787 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001788 auto track_it = current_tracks->begin();
1789 while (track_it != current_tracks->end()) {
1790 const TrackInfo& info = *track_it;
1791 const cricket::StreamParams* params =
1792 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001793 bool track_exists = params && params->id == info.track_id;
1794 // If this is a default track, and we still need it, don't remove it.
1795 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1796 track_exists) {
1797 ++track_it;
1798 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001799 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1800 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001801 }
1802 }
1803
1804 // Find new and active tracks.
1805 for (const cricket::StreamParams& params : streams) {
1806 // The sync_label is the MediaStream label and the |stream.id| is the
1807 // track id.
1808 const std::string& stream_label = params.sync_label;
1809 const std::string& track_id = params.id;
1810 uint32_t ssrc = params.first_ssrc();
1811
1812 rtc::scoped_refptr<MediaStreamInterface> stream =
1813 remote_streams_->find(stream_label);
1814 if (!stream) {
1815 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001816 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1817 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001818 remote_streams_->AddStream(stream);
1819 new_streams->AddStream(stream);
1820 }
1821
1822 const TrackInfo* track_info =
1823 FindTrackInfo(*current_tracks, stream_label, track_id);
1824 if (!track_info) {
1825 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1826 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1827 }
1828 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001829
1830 // Add default track if necessary.
1831 if (default_track_needed) {
1832 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1833 remote_streams_->find(kDefaultStreamLabel);
1834 if (!default_stream) {
1835 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001836 default_stream = MediaStreamProxy::Create(
1837 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001838 remote_streams_->AddStream(default_stream);
1839 new_streams->AddStream(default_stream);
1840 }
1841 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1842 ? kDefaultAudioTrackLabel
1843 : kDefaultVideoTrackLabel;
1844 const TrackInfo* default_track_info =
1845 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1846 if (!default_track_info) {
1847 current_tracks->push_back(
1848 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1849 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1850 }
1851 }
deadbeefab9b2d12015-10-14 11:33:11 -07001852}
1853
1854void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1855 const std::string& track_id,
1856 uint32_t ssrc,
1857 cricket::MediaType media_type) {
1858 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1859
1860 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001861 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001862 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001863 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001864 } else {
1865 RTC_DCHECK(false && "Invalid media type");
1866 }
1867}
1868
1869void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1870 const std::string& track_id,
1871 cricket::MediaType media_type) {
1872 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1873
1874 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001875 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1876 // will be notified which will end the AudioRtpReceiver::track().
1877 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001878 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1879 stream->FindAudioTrack(track_id);
1880 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001881 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001882 }
1883 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001884 // Stopping or destroying a VideoRtpReceiver will end the
1885 // VideoRtpReceiver::track().
1886 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001887 rtc::scoped_refptr<VideoTrackInterface> video_track =
1888 stream->FindVideoTrack(track_id);
1889 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001890 // There's no guarantee the track is still available, e.g. the track may
1891 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001892 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001893 }
1894 } else {
1895 ASSERT(false && "Invalid media type");
1896 }
1897}
1898
1899void PeerConnection::UpdateEndedRemoteMediaStreams() {
1900 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1901 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1902 MediaStreamInterface* stream = remote_streams_->at(i);
1903 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1904 streams_to_remove.push_back(stream);
1905 }
1906 }
1907
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001908 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001909 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001910 // Call both the raw pointer and scoped_refptr versions of the method
1911 // for compatibility.
1912 observer_->OnRemoveStream(stream.get());
1913 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001914 }
1915}
1916
deadbeefab9b2d12015-10-14 11:33:11 -07001917void PeerConnection::UpdateLocalTracks(
1918 const std::vector<cricket::StreamParams>& streams,
1919 cricket::MediaType media_type) {
1920 TrackInfos* current_tracks = GetLocalTracks(media_type);
1921
1922 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1923 // don't match the new StreamParam.
1924 TrackInfos::iterator track_it = current_tracks->begin();
1925 while (track_it != current_tracks->end()) {
1926 const TrackInfo& info = *track_it;
1927 const cricket::StreamParams* params =
1928 cricket::GetStreamBySsrc(streams, info.ssrc);
1929 if (!params || params->id != info.track_id ||
1930 params->sync_label != info.stream_label) {
1931 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1932 media_type);
1933 track_it = current_tracks->erase(track_it);
1934 } else {
1935 ++track_it;
1936 }
1937 }
1938
1939 // Find new and active tracks.
1940 for (const cricket::StreamParams& params : streams) {
1941 // The sync_label is the MediaStream label and the |stream.id| is the
1942 // track id.
1943 const std::string& stream_label = params.sync_label;
1944 const std::string& track_id = params.id;
1945 uint32_t ssrc = params.first_ssrc();
1946 const TrackInfo* track_info =
1947 FindTrackInfo(*current_tracks, stream_label, track_id);
1948 if (!track_info) {
1949 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1950 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1951 }
1952 }
1953}
1954
1955void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1956 const std::string& track_id,
1957 uint32_t ssrc,
1958 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001959 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001960 if (!sender) {
1961 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1962 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001963 return;
1964 }
1965
deadbeeffac06552015-11-25 11:26:01 -08001966 if (sender->media_type() != media_type) {
1967 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1968 << " description with an unexpected media type.";
1969 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001970 }
deadbeeffac06552015-11-25 11:26:01 -08001971
1972 sender->set_stream_id(stream_label);
1973 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001974}
1975
1976void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1977 const std::string& track_id,
1978 uint32_t ssrc,
1979 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001980 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001981 if (!sender) {
1982 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001983 // SessionDescriptions has been renegotiated.
1984 return;
1985 }
deadbeeffac06552015-11-25 11:26:01 -08001986
1987 // A sender has been removed from the SessionDescription but it's still
1988 // associated with the PeerConnection. This only occurs if the SDP doesn't
1989 // match with the calls to CreateSender, AddStream and RemoveStream.
1990 if (sender->media_type() != media_type) {
1991 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1992 << " description with an unexpected media type.";
1993 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001994 }
deadbeeffac06552015-11-25 11:26:01 -08001995
1996 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001997}
1998
1999void PeerConnection::UpdateLocalRtpDataChannels(
2000 const cricket::StreamParamsVec& streams) {
2001 std::vector<std::string> existing_channels;
2002
2003 // Find new and active data channels.
2004 for (const cricket::StreamParams& params : streams) {
2005 // |it->sync_label| is actually the data channel label. The reason is that
2006 // we use the same naming of data channels as we do for
2007 // MediaStreams and Tracks.
2008 // For MediaStreams, the sync_label is the MediaStream label and the
2009 // track label is the same as |streamid|.
2010 const std::string& channel_label = params.sync_label;
2011 auto data_channel_it = rtp_data_channels_.find(channel_label);
2012 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
2013 continue;
2014 }
2015 // Set the SSRC the data channel should use for sending.
2016 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2017 existing_channels.push_back(data_channel_it->first);
2018 }
2019
2020 UpdateClosingRtpDataChannels(existing_channels, true);
2021}
2022
2023void PeerConnection::UpdateRemoteRtpDataChannels(
2024 const cricket::StreamParamsVec& streams) {
2025 std::vector<std::string> existing_channels;
2026
2027 // Find new and active data channels.
2028 for (const cricket::StreamParams& params : streams) {
2029 // The data channel label is either the mslabel or the SSRC if the mslabel
2030 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2031 std::string label = params.sync_label.empty()
2032 ? rtc::ToString(params.first_ssrc())
2033 : params.sync_label;
2034 auto data_channel_it = rtp_data_channels_.find(label);
2035 if (data_channel_it == rtp_data_channels_.end()) {
2036 // This is a new data channel.
2037 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2038 } else {
2039 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2040 }
2041 existing_channels.push_back(label);
2042 }
2043
2044 UpdateClosingRtpDataChannels(existing_channels, false);
2045}
2046
2047void PeerConnection::UpdateClosingRtpDataChannels(
2048 const std::vector<std::string>& active_channels,
2049 bool is_local_update) {
2050 auto it = rtp_data_channels_.begin();
2051 while (it != rtp_data_channels_.end()) {
2052 DataChannel* data_channel = it->second;
2053 if (std::find(active_channels.begin(), active_channels.end(),
2054 data_channel->label()) != active_channels.end()) {
2055 ++it;
2056 continue;
2057 }
2058
2059 if (is_local_update) {
2060 data_channel->SetSendSsrc(0);
2061 } else {
2062 data_channel->RemotePeerRequestClose();
2063 }
2064
2065 if (data_channel->state() == DataChannel::kClosed) {
2066 rtp_data_channels_.erase(it);
2067 it = rtp_data_channels_.begin();
2068 } else {
2069 ++it;
2070 }
2071 }
2072}
2073
2074void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2075 uint32_t remote_ssrc) {
2076 rtc::scoped_refptr<DataChannel> channel(
2077 InternalCreateDataChannel(label, nullptr));
2078 if (!channel.get()) {
2079 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2080 << "CreateDataChannel failed.";
2081 return;
2082 }
2083 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002084 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2085 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002086 // Call both the raw pointer and scoped_refptr versions of the method
2087 // for compatibility.
2088 observer_->OnDataChannel(proxy_channel.get());
2089 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002090}
2091
2092rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2093 const std::string& label,
2094 const InternalDataChannelInit* config) {
2095 if (IsClosed()) {
2096 return nullptr;
2097 }
2098 if (session_->data_channel_type() == cricket::DCT_NONE) {
2099 LOG(LS_ERROR)
2100 << "InternalCreateDataChannel: Data is not supported in this call.";
2101 return nullptr;
2102 }
2103 InternalDataChannelInit new_config =
2104 config ? (*config) : InternalDataChannelInit();
2105 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2106 if (new_config.id < 0) {
2107 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002108 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002109 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2110 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2111 return nullptr;
2112 }
2113 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2114 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2115 << "because the id is already in use or out of range.";
2116 return nullptr;
2117 }
2118 }
2119
2120 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2121 session_.get(), session_->data_channel_type(), label, new_config));
2122 if (!channel) {
2123 sid_allocator_.ReleaseSid(new_config.id);
2124 return nullptr;
2125 }
2126
2127 if (channel->data_channel_type() == cricket::DCT_RTP) {
2128 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2129 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2130 << " already exists.";
2131 return nullptr;
2132 }
2133 rtp_data_channels_[channel->label()] = channel;
2134 } else {
2135 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2136 sctp_data_channels_.push_back(channel);
2137 channel->SignalClosed.connect(this,
2138 &PeerConnection::OnSctpDataChannelClosed);
2139 }
2140
hbos82ebe022016-11-14 01:41:09 -08002141 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002142 return channel;
2143}
2144
2145bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002146#ifdef HAVE_QUIC
2147 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2148 (session_->quic_data_transport() &&
2149 session_->quic_data_transport()->HasDataChannels());
2150#else
deadbeefab9b2d12015-10-14 11:33:11 -07002151 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002152#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002153}
2154
2155void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2156 for (const auto& channel : sctp_data_channels_) {
2157 if (channel->id() < 0) {
2158 int sid;
2159 if (!sid_allocator_.AllocateSid(role, &sid)) {
2160 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2161 continue;
2162 }
2163 channel->SetSctpSid(sid);
2164 }
2165 }
2166}
2167
2168void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002169 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002170 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2171 ++it) {
2172 if (it->get() == channel) {
2173 if (channel->id() >= 0) {
2174 sid_allocator_.ReleaseSid(channel->id());
2175 }
deadbeefbd292462015-12-14 18:15:29 -08002176 // Since this method is triggered by a signal from the DataChannel,
2177 // we can't free it directly here; we need to free it asynchronously.
2178 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002179 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002180 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2181 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002182 return;
2183 }
2184 }
2185}
2186
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002187void PeerConnection::OnVoiceChannelCreated() {
2188 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2189 session_->voice_channel(), senders_, receivers_,
2190 cricket::MEDIA_TYPE_AUDIO);
2191}
2192
deadbeefab9b2d12015-10-14 11:33:11 -07002193void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002194 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2195 cricket::VoiceChannel>(
2196 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2197}
2198
2199void PeerConnection::OnVideoChannelCreated() {
2200 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2201 session_->video_channel(), senders_, receivers_,
2202 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002203}
2204
2205void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002206 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2207 cricket::VideoChannel>(
2208 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002209}
2210
2211void PeerConnection::OnDataChannelCreated() {
2212 for (const auto& channel : sctp_data_channels_) {
2213 channel->OnTransportChannelCreated();
2214 }
2215}
2216
2217void PeerConnection::OnDataChannelDestroyed() {
2218 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2219 // DataChannel may callback to us and try to modify the list.
2220 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2221 temp_rtp_dcs.swap(rtp_data_channels_);
2222 for (const auto& kv : temp_rtp_dcs) {
2223 kv.second->OnTransportChannelDestroyed();
2224 }
2225
2226 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2227 temp_sctp_dcs.swap(sctp_data_channels_);
2228 for (const auto& channel : temp_sctp_dcs) {
2229 channel->OnTransportChannelDestroyed();
2230 }
2231}
2232
2233void PeerConnection::OnDataChannelOpenMessage(
2234 const std::string& label,
2235 const InternalDataChannelInit& config) {
2236 rtc::scoped_refptr<DataChannel> channel(
2237 InternalCreateDataChannel(label, &config));
2238 if (!channel.get()) {
2239 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2240 return;
2241 }
2242
deadbeefa601f5c2016-06-06 14:27:39 -07002243 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2244 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002245 // Call both the raw pointer and scoped_refptr versions of the method
2246 // for compatibility.
2247 observer_->OnDataChannel(proxy_channel.get());
2248 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002249}
2250
deadbeefa601f5c2016-06-06 14:27:39 -07002251RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2252 auto it = std::find_if(
2253 senders_.begin(), senders_.end(),
2254 [id](const rtc::scoped_refptr<
2255 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2256 return sender->id() == id;
2257 });
2258 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002259}
2260
deadbeefa601f5c2016-06-06 14:27:39 -07002261std::vector<
2262 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002263PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2264 return std::find_if(
2265 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002266 [track](const rtc::scoped_refptr<
2267 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002268 return sender->track() == track;
2269 });
2270}
2271
deadbeefa601f5c2016-06-06 14:27:39 -07002272std::vector<rtc::scoped_refptr<
2273 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002274PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002275 return std::find_if(
2276 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002277 [track_id](const rtc::scoped_refptr<
2278 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002279 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002280 });
2281}
2282
deadbeefab9b2d12015-10-14 11:33:11 -07002283PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2284 cricket::MediaType media_type) {
2285 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2286 media_type == cricket::MEDIA_TYPE_VIDEO);
2287 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2288 : &remote_video_tracks_;
2289}
2290
2291PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2292 cricket::MediaType media_type) {
2293 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2294 media_type == cricket::MEDIA_TYPE_VIDEO);
2295 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2296 : &local_video_tracks_;
2297}
2298
2299const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2300 const PeerConnection::TrackInfos& infos,
2301 const std::string& stream_label,
2302 const std::string track_id) const {
2303 for (const TrackInfo& track_info : infos) {
2304 if (track_info.stream_label == stream_label &&
2305 track_info.track_id == track_id) {
2306 return &track_info;
2307 }
2308 }
2309 return nullptr;
2310}
2311
2312DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2313 for (const auto& channel : sctp_data_channels_) {
2314 if (channel->id() == sid) {
2315 return channel;
2316 }
2317 }
2318 return nullptr;
2319}
2320
deadbeef91dd5672016-05-18 16:55:30 -07002321bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002322 const RTCConfiguration& configuration) {
2323 cricket::ServerAddresses stun_servers;
2324 std::vector<cricket::RelayServerConfig> turn_servers;
2325 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2326 return false;
2327 }
2328
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002329 port_allocator_->Initialize();
2330
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002331 // To handle both internal and externally created port allocator, we will
2332 // enable BUNDLE here.
2333 int portallocator_flags = port_allocator_->flags();
2334 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2335 cricket::PORTALLOCATOR_ENABLE_IPV6;
2336 // If the disable-IPv6 flag was specified, we'll not override it
2337 // by experiment.
2338 if (configuration.disable_ipv6) {
2339 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2340 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2341 "Disabled") {
2342 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2343 }
2344
2345 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2346 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2347 LOG(LS_INFO) << "TCP candidates are disabled.";
2348 }
2349
honghaiz60347052016-05-31 18:29:12 -07002350 if (configuration.candidate_network_policy ==
2351 kCandidateNetworkPolicyLowCost) {
2352 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2353 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2354 }
2355
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002356 port_allocator_->set_flags(portallocator_flags);
2357 // No step delay is used while allocating ports.
2358 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2359 port_allocator_->set_candidate_filter(
2360 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2361
2362 // Call this last since it may create pooled allocator sessions using the
2363 // properties set above.
2364 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002365 configuration.ice_candidate_pool_size,
2366 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002367 return true;
2368}
2369
deadbeef91dd5672016-05-18 16:55:30 -07002370bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002371 const RTCConfiguration& configuration) {
2372 cricket::ServerAddresses stun_servers;
2373 std::vector<cricket::RelayServerConfig> turn_servers;
2374 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2375 return false;
2376 }
2377 port_allocator_->set_candidate_filter(
2378 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2379 // Call this last since it may create pooled allocator sessions using the
2380 // candidate filter set above.
2381 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002382 configuration.ice_candidate_pool_size,
2383 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002384 return true;
2385}
2386
ivoc14d5dbe2016-07-04 07:06:55 -07002387bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2388 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002389 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002390}
2391
2392void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002393 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002394}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002395} // namespace webrtc