blob: 6d7d07d027b5db15811fc5a681ee27708f18e60d [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"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
45namespace {
46
deadbeefab9b2d12015-10-14 11:33:11 -070047using webrtc::DataChannel;
48using webrtc::MediaConstraintsInterface;
49using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070051using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080052using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070053using webrtc::RtpSenderProxy;
54using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070055using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
deadbeefab9b2d12015-10-14 11:33:11 -070057static const char kDefaultStreamLabel[] = "default";
58static const char kDefaultAudioTrackLabel[] = "defaulta0";
59static const char kDefaultVideoTrackLabel[] = "defaultv0";
60
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061// The min number of tokens must present in Turn host uri.
62// e.g. user@turn.example.org
63static const size_t kTurnHostTokensNum = 2;
64// Number of tokens must be preset when TURN uri has transport param.
65static const size_t kTurnTransportTokensNum = 2;
66// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000067static const int kDefaultStunPort = 3478;
68static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070
71// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070072static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073
zhihuang8f65cdf2016-05-06 18:40:30 -070074// The length of RTCP CNAMEs.
75static const int kRtcpCnameLength = 16;
76
deadbeef0a6c4ca2015-10-06 11:38:28 -070077// NOTE: A loop below assumes that the first value of this enum is 0 and all
78// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070080 STUN = 0, // Indicates a STUN server.
81 STUNS, // Indicates a STUN server used with a TLS session.
82 TURN, // Indicates a TURN server
83 TURNS, // Indicates a TURN server used with a TLS session.
84 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085};
tfarina5237aaf2015-11-10 23:44:30 -080086static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070087 "kValidIceServiceTypes must have as many strings as ServiceType "
88 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089
90enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000091 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070093 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080095 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096};
97
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000098struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099 explicit SetSessionDescriptionMsg(
100 webrtc::SetSessionDescriptionObserver* observer)
101 : observer(observer) {
102 }
103
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000104 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 std::string error;
106};
107
deadbeefab9b2d12015-10-14 11:33:11 -0700108struct CreateSessionDescriptionMsg : public rtc::MessageData {
109 explicit CreateSessionDescriptionMsg(
110 webrtc::CreateSessionDescriptionObserver* observer)
111 : observer(observer) {}
112
113 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
114 std::string error;
115};
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000118 GetStatsMsg(webrtc::StatsObserver* observer,
119 webrtc::MediaStreamTrackInterface* track)
120 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000122 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000123 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124};
125
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000126// |in_str| should be of format
127// stunURI = scheme ":" stun-host [ ":" stun-port ]
128// scheme = "stun" / "stuns"
129// stun-host = IP-literal / IPv4address / reg-name
130// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700131//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000132// draft-petithuguenin-behave-turn-uris-01
133// turnURI = scheme ":" turn-host [ ":" turn-port ]
134// turn-host = username@IP-literal / IPv4address / reg-name
135bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
136 ServiceType* service_type,
137 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200138 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700139 if (colonpos == std::string::npos) {
140 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000141 return false;
142 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700143 if ((colonpos + 1) == in_str.length()) {
144 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
145 return false;
146 }
147 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800148 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700149 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000150 *service_type = static_cast<ServiceType>(i);
151 break;
152 }
153 }
154 if (*service_type == INVALID) {
155 return false;
156 }
157 *hostname = in_str.substr(colonpos + 1, std::string::npos);
158 return true;
159}
160
deadbeef0a6c4ca2015-10-06 11:38:28 -0700161bool ParsePort(const std::string& in_str, int* port) {
162 // Make sure port only contains digits. FromString doesn't check this.
163 for (const char& c : in_str) {
164 if (!std::isdigit(c)) {
165 return false;
166 }
167 }
168 return rtc::FromString(in_str, port);
169}
170
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000171// This method parses IPv6 and IPv4 literal strings, along with hostnames in
172// standard hostname:port format.
173// Consider following formats as correct.
174// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700175// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000176bool ParseHostnameAndPortFromString(const std::string& in_str,
177 std::string* host,
178 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700179 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000180 if (in_str.at(0) == '[') {
181 std::string::size_type closebracket = in_str.rfind(']');
182 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000183 std::string::size_type colonpos = in_str.find(':', closebracket);
184 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700185 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
186 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000187 return false;
188 }
189 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700190 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000191 } else {
192 return false;
193 }
194 } else {
195 std::string::size_type colonpos = in_str.find(':');
196 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700197 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000198 return false;
199 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700200 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000201 } else {
202 *host = in_str;
203 }
204 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700205 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000206}
207
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800208// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700209// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200210bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
211 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800212 cricket::ServerAddresses* stun_servers,
213 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214 // draft-nandakumar-rtcweb-stun-uri-01
215 // stunURI = scheme ":" stun-host [ ":" stun-port ]
216 // scheme = "stun" / "stuns"
217 // stun-host = IP-literal / IPv4address / reg-name
218 // stun-port = *DIGIT
219
220 // draft-petithuguenin-behave-turn-uris-01
221 // turnURI = scheme ":" turn-host [ ":" turn-port ]
222 // [ "?transport=" transport ]
223 // scheme = "turn" / "turns"
224 // transport = "udp" / "tcp" / transport-ext
225 // transport-ext = 1*unreserved
226 // turn-host = IP-literal / IPv4address / reg-name
227 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800228 RTC_DCHECK(stun_servers != nullptr);
229 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200230 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800231 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700232 RTC_DCHECK(!url.empty());
hnslbd44bb02016-12-12 03:14:30 -0800233 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200234 std::string uri_without_transport = tokens[0];
235 // Let's look into transport= param, if it exists.
236 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
237 std::string uri_transport_param = tokens[1];
hnslbd44bb02016-12-12 03:14:30 -0800238 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
239 if (tokens[0] != kTransport) {
240 LOG(LS_WARNING) << "Invalid transport parameter key.";
241 return false;
242 }
243 if (tokens.size() < 2 ||
244 !cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
245 (turn_transport_type != cricket::PROTO_UDP &&
246 turn_transport_type != cricket::PROTO_TCP)) {
247 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
248 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249 }
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;
hnsl277b2502016-12-13 05:17:23 -0800287 turn_transport_type = cricket::PROTO_TLS;
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: {
magjedd5236e22016-12-20 02:22:06 -0800308 turn_servers->push_back(cricket::RelayServerConfig(
309 address, port, username, server.password, turn_transport_type));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200310 break;
311 }
312 case INVALID:
313 default:
314 LOG(WARNING) << "Configuration not supported: " << url;
315 return false;
316 }
317 return true;
318}
319
deadbeefab9b2d12015-10-14 11:33:11 -0700320// Check if we can send |new_stream| on a PeerConnection.
321bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
322 webrtc::MediaStreamInterface* new_stream) {
323 if (!new_stream || !current_streams) {
324 return false;
325 }
326 if (current_streams->find(new_stream->label()) != nullptr) {
327 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
328 << " is already added.";
329 return false;
330 }
331 return true;
332}
333
334bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
335 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
336}
337
deadbeef5e97fb52015-10-15 12:49:08 -0700338// If the direction is "recvonly" or "inactive", treat the description
339// as containing no streams.
340// See: https://code.google.com/p/webrtc/issues/detail?id=5054
341std::vector<cricket::StreamParams> GetActiveStreams(
342 const cricket::MediaContentDescription* desc) {
343 return MediaContentDirectionHasSend(desc->direction())
344 ? desc->streams()
345 : std::vector<cricket::StreamParams>();
346}
347
deadbeefab9b2d12015-10-14 11:33:11 -0700348bool IsValidOfferToReceiveMedia(int value) {
349 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
350 return (value >= Options::kUndefined) &&
351 (value <= Options::kMaxOfferToReceiveMedia);
352}
353
354// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800355void AddSendStreams(
356 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700357 const std::vector<rtc::scoped_refptr<
358 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800359 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
360 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700361 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800362 for (const auto& sender : senders) {
363 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700364 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700365 }
366
367 // Check for data channels.
368 for (const auto& kv : rtp_data_channels) {
369 const DataChannel* channel = kv.second;
370 if (channel->state() == DataChannel::kConnecting ||
371 channel->state() == DataChannel::kOpen) {
372 // |streamid| and |sync_label| are both set to the DataChannel label
373 // here so they can be signaled the same way as MediaStreams and Tracks.
374 // For MediaStreams, the sync_label is the MediaStream label and the
375 // track label is the same as |streamid|.
376 const std::string& streamid = channel->label();
377 const std::string& sync_label = channel->label();
378 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
379 sync_label);
380 }
381 }
382}
383
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700384uint32_t ConvertIceTransportTypeToCandidateFilter(
385 PeerConnectionInterface::IceTransportsType type) {
386 switch (type) {
387 case PeerConnectionInterface::kNone:
388 return cricket::CF_NONE;
389 case PeerConnectionInterface::kRelay:
390 return cricket::CF_RELAY;
391 case PeerConnectionInterface::kNoHost:
392 return (cricket::CF_ALL & ~cricket::CF_HOST);
393 case PeerConnectionInterface::kAll:
394 return cricket::CF_ALL;
395 default:
396 ASSERT(false);
397 }
398 return cricket::CF_NONE;
399}
400
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700401// Helper method to set a voice/video channel on all applicable senders
402// and receivers when one is created/destroyed by WebRtcSession.
403//
404// Used by On(Voice|Video)Channel(Created|Destroyed)
405template <class SENDER,
406 class RECEIVER,
407 class CHANNEL,
408 class SENDERS,
409 class RECEIVERS>
410void SetChannelOnSendersAndReceivers(CHANNEL* channel,
411 SENDERS& senders,
412 RECEIVERS& receivers,
413 cricket::MediaType media_type) {
414 for (auto& sender : senders) {
415 if (sender->media_type() == media_type) {
416 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
417 }
418 }
419 for (auto& receiver : receivers) {
420 if (receiver->media_type() == media_type) {
421 if (!channel) {
422 receiver->internal()->Stop();
423 }
424 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
425 }
426 }
427}
428
deadbeef0a6c4ca2015-10-06 11:38:28 -0700429} // namespace
430
431namespace webrtc {
432
deadbeef3edec7c2016-12-10 11:44:26 -0800433static const char* const kRtcErrorNames[] = {
434 "NONE",
435 "UNSUPPORTED_PARAMETER",
436 "INVALID_PARAMETER",
437 "INVALID_RANGE",
438 "SYNTAX_ERROR",
439 "INVALID_STATE",
440 "INVALID_MODIFICATION",
441 "NETWORK_ERROR",
442 "INTERNAL_ERROR",
443};
444
445std::ostream& operator<<(std::ostream& stream, RtcError error) {
446 int index = static_cast<int>(error);
447 RTC_CHECK(index < static_cast<int>(sizeof(kRtcErrorNames) /
448 sizeof(kRtcErrorNames[0])));
449 return stream << kRtcErrorNames[index];
450}
451
zhihuang8f65cdf2016-05-06 18:40:30 -0700452// Generate a RTCP CNAME when a PeerConnection is created.
453std::string GenerateRtcpCname() {
454 std::string cname;
455 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
456 LOG(LS_ERROR) << "Failed to generate CNAME.";
457 RTC_DCHECK(false);
458 }
459 return cname;
460}
461
htaa2a49d92016-03-04 02:51:39 -0800462bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700463 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800464 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700465 cricket::MediaSessionOptions* session_options) {
466 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
467 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
468 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
469 return false;
470 }
471
htaaac2dea2016-03-10 13:35:55 -0800472 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700473 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700474 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800475 } else {
476 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700477 }
htaaac2dea2016-03-10 13:35:55 -0800478 // For offers, we only offer video if we have it or it's forced by options.
479 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700480 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700481 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800482 } else if (is_offer) {
483 session_options->recv_video = false;
484 } else {
485 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700486 }
487
488 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700489 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800490 for (auto& kv : session_options->transport_options) {
491 kv.second.ice_restart = rtc_options.ice_restart;
492 }
deadbeefab9b2d12015-10-14 11:33:11 -0700493
494 return true;
495}
496
497bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
498 cricket::MediaSessionOptions* session_options) {
499 bool value = false;
500 size_t mandatory_constraints_satisfied = 0;
501
502 // kOfferToReceiveAudio defaults to true according to spec.
503 if (!FindConstraint(constraints,
504 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
505 &mandatory_constraints_satisfied) ||
506 value) {
507 session_options->recv_audio = true;
508 }
509
510 // kOfferToReceiveVideo defaults to false according to spec. But
511 // if it is an answer and video is offered, we should still accept video
512 // per default.
513 value = false;
514 if (!FindConstraint(constraints,
515 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
516 &mandatory_constraints_satisfied) ||
517 value) {
518 session_options->recv_video = true;
519 }
520
521 if (FindConstraint(constraints,
522 MediaConstraintsInterface::kVoiceActivityDetection, &value,
523 &mandatory_constraints_satisfied)) {
524 session_options->vad_enabled = value;
525 }
526
527 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
528 &mandatory_constraints_satisfied)) {
529 session_options->bundle_enabled = value;
530 } else {
531 // kUseRtpMux defaults to true according to spec.
532 session_options->bundle_enabled = true;
533 }
deadbeefab9b2d12015-10-14 11:33:11 -0700534
deadbeef0ed85b22016-02-23 17:24:52 -0800535 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700536 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
537 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700538 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800539 ice_restart = true;
540 }
541 for (auto& kv : session_options->transport_options) {
542 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700543 }
544
545 if (!constraints) {
546 return true;
547 }
548 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
549}
550
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200551bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800552 cricket::ServerAddresses* stun_servers,
553 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200554 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
555 if (!server.urls.empty()) {
556 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200557 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700558 LOG(LS_ERROR) << "Empty uri.";
559 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200560 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800561 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200562 return false;
563 }
564 }
565 } else if (!server.uri.empty()) {
566 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800567 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200569 }
570 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700571 LOG(LS_ERROR) << "Empty uri.";
572 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573 }
574 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800575 // Candidates must have unique priorities, so that connectivity checks
576 // are performed in a well-defined order.
577 int priority = static_cast<int>(turn_servers->size() - 1);
578 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
579 // First in the list gets highest priority.
580 turn_server.priority = priority--;
581 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000582 return true;
583}
584
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585PeerConnection::PeerConnection(PeerConnectionFactory* factory)
586 : factory_(factory),
587 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000588 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700591 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800592 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700593 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700594 local_streams_(StreamCollection::Create()),
595 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000596
597PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100598 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700599 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700600 // Need to detach RTP senders/receivers from WebRtcSession,
601 // since it's about to be destroyed.
602 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700603 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700604 }
605 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700606 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700607 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700608 // Destroy stats_ because it depends on session_.
609 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800610 if (stats_collector_) {
611 stats_collector_->WaitForPendingRequest();
612 stats_collector_ = nullptr;
613 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700614 // Now destroy session_ before destroying other members,
615 // because its destruction fires signals (such as VoiceChannelDestroyed)
616 // which will trigger some final actions in PeerConnection...
617 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700618 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700619 network_thread()->Invoke<void>(RTC_FROM_HERE,
620 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621}
622
623bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000624 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700625 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200626 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800627 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100628 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800629 RTC_DCHECK(observer != nullptr);
630 if (!observer) {
631 return false;
632 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000633 observer_ = observer;
634
kwiberg0eb15ed2015-12-17 03:04:15 -0800635 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800636
deadbeef91dd5672016-05-18 16:55:30 -0700637 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700638 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700639 if (!network_thread()->Invoke<bool>(
640 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
641 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000642 return false;
643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644
skvlad11a9cbf2016-10-07 11:53:05 -0700645 media_controller_.reset(factory_->CreateMediaController(
646 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000647
zhihuang29ff8442016-07-27 11:07:25 -0700648 session_.reset(new WebRtcSession(
649 media_controller_.get(), factory_->network_thread(),
650 factory_->worker_thread(), factory_->signaling_thread(),
651 port_allocator_.get(),
652 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700653 factory_->CreateTransportController(
654 port_allocator_.get(),
655 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700656
deadbeefab9b2d12015-10-14 11:33:11 -0700657 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700658 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659
660 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200661 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800662 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700664 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000665
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666 // Register PeerConnection as receiver of local ice candidates.
667 // All the callbacks will be posted to the application from PeerConnection.
668 session_->RegisterIceObserver(this);
669 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700670 session_->SignalVoiceChannelCreated.connect(
671 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700672 session_->SignalVoiceChannelDestroyed.connect(
673 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700674 session_->SignalVideoChannelCreated.connect(
675 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700676 session_->SignalVideoChannelDestroyed.connect(
677 this, &PeerConnection::OnVideoChannelDestroyed);
678 session_->SignalDataChannelCreated.connect(
679 this, &PeerConnection::OnDataChannelCreated);
680 session_->SignalDataChannelDestroyed.connect(
681 this, &PeerConnection::OnDataChannelDestroyed);
682 session_->SignalDataChannelOpenMessage.connect(
683 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800684
685 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000686 return true;
687}
688
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000689rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700691 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692}
693
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000694rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700696 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000697}
698
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000699bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100700 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701 if (IsClosed()) {
702 return false;
703 }
deadbeefab9b2d12015-10-14 11:33:11 -0700704 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705 return false;
706 }
deadbeefab9b2d12015-10-14 11:33:11 -0700707
708 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800709 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
710 observer->SignalAudioTrackAdded.connect(this,
711 &PeerConnection::OnAudioTrackAdded);
712 observer->SignalAudioTrackRemoved.connect(
713 this, &PeerConnection::OnAudioTrackRemoved);
714 observer->SignalVideoTrackAdded.connect(this,
715 &PeerConnection::OnVideoTrackAdded);
716 observer->SignalVideoTrackRemoved.connect(
717 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700718 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700719
deadbeefab9b2d12015-10-14 11:33:11 -0700720 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800721 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700722 }
723 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800724 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700725 }
726
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000727 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 observer_->OnRenegotiationNeeded();
729 return true;
730}
731
732void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100733 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700734 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800735 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700736 }
737 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800738 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700739 }
740
741 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800742 stream_observers_.erase(
743 std::remove_if(
744 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700745 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800746 return observer->stream()->label().compare(local_stream->label()) ==
747 0;
748 }),
749 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700750
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000751 if (IsClosed()) {
752 return;
753 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754 observer_->OnRenegotiationNeeded();
755}
756
deadbeefe1f9d832016-01-14 15:35:42 -0800757rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
758 MediaStreamTrackInterface* track,
759 std::vector<MediaStreamInterface*> streams) {
760 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
761 if (IsClosed()) {
762 return nullptr;
763 }
764 if (streams.size() >= 2) {
765 LOG(LS_ERROR)
766 << "Adding a track with two streams is not currently supported.";
767 return nullptr;
768 }
769 // TODO(deadbeef): Support adding a track to two different senders.
770 if (FindSenderForTrack(track) != senders_.end()) {
771 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
772 return nullptr;
773 }
774
775 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700776 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800777 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700778 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800779 signaling_thread(),
780 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700781 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800782 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700783 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800784 }
785 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700786 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800787 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700788 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800789 }
790 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700791 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800792 signaling_thread(),
793 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700794 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800795 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700796 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800797 }
798 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700799 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800800 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700801 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800802 }
803 } else {
804 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
805 return rtc::scoped_refptr<RtpSenderInterface>();
806 }
807
808 senders_.push_back(new_sender);
809 observer_->OnRenegotiationNeeded();
810 return new_sender;
811}
812
813bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
814 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
815 if (IsClosed()) {
816 return false;
817 }
818
819 auto it = std::find(senders_.begin(), senders_.end(), sender);
820 if (it == senders_.end()) {
821 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
822 return false;
823 }
deadbeefa601f5c2016-06-06 14:27:39 -0700824 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800825 senders_.erase(it);
826
827 observer_->OnRenegotiationNeeded();
828 return true;
829}
830
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000831rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100833 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700834 if (IsClosed()) {
835 return nullptr;
836 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000837 if (!track) {
838 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
839 return NULL;
840 }
deadbeefab9b2d12015-10-14 11:33:11 -0700841 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
843 return NULL;
844 }
845
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000846 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 DtmfSender::Create(track, signaling_thread(), session_.get()));
848 if (!sender.get()) {
849 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
850 return NULL;
851 }
852 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
853}
854
deadbeeffac06552015-11-25 11:26:01 -0800855rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800856 const std::string& kind,
857 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100858 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700859 if (IsClosed()) {
860 return nullptr;
861 }
deadbeefa601f5c2016-06-06 14:27:39 -0700862 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800863 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700864 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700865 signaling_thread(),
866 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800867 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700868 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700869 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800870 } else {
871 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800872 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800873 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800874 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700875 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800876 }
deadbeeffac06552015-11-25 11:26:01 -0800877 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800878 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800879}
880
deadbeef70ab1a12015-09-28 16:53:55 -0700881std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
882 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700883 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
884 for (const auto& sender : senders_) {
885 ret.push_back(sender.get());
886 }
887 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700888}
889
890std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
891PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700892 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
893 for (const auto& receiver : receivers_) {
894 ret.push_back(receiver.get());
895 }
896 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700897}
898
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000900 MediaStreamTrackInterface* track,
901 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100902 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700903 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904 if (!VERIFY(observer != NULL)) {
905 LOG(LS_ERROR) << "GetStats - observer is NULL.";
906 return false;
907 }
908
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000909 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700910 // The StatsCollector is used to tell if a track is valid because it may
911 // remember tracks that the PeerConnection previously removed.
912 if (track && !stats_->IsValidTrack(track->id())) {
913 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
914 << track->id();
915 return false;
916 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700917 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000918 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919 return true;
920}
921
hbos74e1a4f2016-09-15 23:33:01 -0700922void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
923 RTC_DCHECK(stats_collector_);
924 stats_collector_->GetStatsReport(callback);
925}
926
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
928 return signaling_state_;
929}
930
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931PeerConnectionInterface::IceConnectionState
932PeerConnection::ice_connection_state() {
933 return ice_connection_state_;
934}
935
936PeerConnectionInterface::IceGatheringState
937PeerConnection::ice_gathering_state() {
938 return ice_gathering_state_;
939}
940
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000941rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942PeerConnection::CreateDataChannel(
943 const std::string& label,
944 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100945 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700946#ifdef HAVE_QUIC
947 if (session_->data_channel_type() == cricket::DCT_QUIC) {
948 // TODO(zhihuang): Handle case when config is NULL.
949 if (!config) {
950 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
951 return nullptr;
952 }
953 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
954 if (!config->reliable || config->ordered) {
955 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
956 "ordered delivery.";
957 return nullptr;
958 }
959 return session_->quic_data_transport()->CreateDataChannel(label, config);
960 }
961#endif // HAVE_QUIC
962
deadbeefab9b2d12015-10-14 11:33:11 -0700963 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000964
kwibergd1fe2812016-04-27 06:47:29 -0700965 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000966 if (config) {
967 internal_config.reset(new InternalDataChannelInit(*config));
968 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000969 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700970 InternalCreateDataChannel(label, internal_config.get()));
971 if (!channel.get()) {
972 return nullptr;
973 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000975 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
976 // the first SCTP DataChannel.
977 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
978 observer_->OnRenegotiationNeeded();
979 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000980
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000981 return DataChannelProxy::Create(signaling_thread(), channel.get());
982}
983
984void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
985 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100986 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700987 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
989 return;
990 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000991 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000992
993 bool value;
994 size_t mandatory_constraints = 0;
995
996 if (FindConstraint(constraints,
997 MediaConstraintsInterface::kOfferToReceiveAudio,
998 &value,
999 &mandatory_constraints)) {
1000 options.offer_to_receive_audio =
1001 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1002 }
1003
1004 if (FindConstraint(constraints,
1005 MediaConstraintsInterface::kOfferToReceiveVideo,
1006 &value,
1007 &mandatory_constraints)) {
1008 options.offer_to_receive_video =
1009 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1010 }
1011
1012 if (FindConstraint(constraints,
1013 MediaConstraintsInterface::kVoiceActivityDetection,
1014 &value,
1015 &mandatory_constraints)) {
1016 options.voice_activity_detection = value;
1017 }
1018
1019 if (FindConstraint(constraints,
1020 MediaConstraintsInterface::kIceRestart,
1021 &value,
1022 &mandatory_constraints)) {
1023 options.ice_restart = value;
1024 }
1025
1026 if (FindConstraint(constraints,
1027 MediaConstraintsInterface::kUseRtpMux,
1028 &value,
1029 &mandatory_constraints)) {
1030 options.use_rtp_mux = value;
1031 }
1032
1033 CreateOffer(observer, options);
1034}
1035
1036void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1037 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001038 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001039 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001040 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1041 return;
1042 }
deadbeefab9b2d12015-10-14 11:33:11 -07001043
1044 cricket::MediaSessionOptions session_options;
1045 if (!GetOptionsForOffer(options, &session_options)) {
1046 std::string error = "CreateOffer called with invalid options.";
1047 LOG(LS_ERROR) << error;
1048 PostCreateSessionDescriptionFailure(observer, error);
1049 return;
1050 }
1051
1052 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053}
1054
1055void PeerConnection::CreateAnswer(
1056 CreateSessionDescriptionObserver* observer,
1057 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001058 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001059 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1061 return;
1062 }
deadbeefab9b2d12015-10-14 11:33:11 -07001063
1064 cricket::MediaSessionOptions session_options;
1065 if (!GetOptionsForAnswer(constraints, &session_options)) {
1066 std::string error = "CreateAnswer called with invalid constraints.";
1067 LOG(LS_ERROR) << error;
1068 PostCreateSessionDescriptionFailure(observer, error);
1069 return;
1070 }
1071
htaa2a49d92016-03-04 02:51:39 -08001072 session_->CreateAnswer(observer, session_options);
1073}
1074
1075void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1076 const RTCOfferAnswerOptions& options) {
1077 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1078 if (!VERIFY(observer != nullptr)) {
1079 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1080 return;
1081 }
1082
1083 cricket::MediaSessionOptions session_options;
1084 if (!GetOptionsForAnswer(options, &session_options)) {
1085 std::string error = "CreateAnswer called with invalid options.";
1086 LOG(LS_ERROR) << error;
1087 PostCreateSessionDescriptionFailure(observer, error);
1088 return;
1089 }
1090
1091 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092}
1093
1094void PeerConnection::SetLocalDescription(
1095 SetSessionDescriptionObserver* observer,
1096 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001097 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001098 if (IsClosed()) {
1099 return;
1100 }
deadbeefab9b2d12015-10-14 11:33:11 -07001101 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1103 return;
1104 }
1105 if (!desc) {
1106 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1107 return;
1108 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 // Update stats here so that we have the most recent stats for tracks and
1110 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001111 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 std::string error;
1113 if (!session_->SetLocalDescription(desc, &error)) {
1114 PostSetSessionDescriptionFailure(observer, error);
1115 return;
1116 }
deadbeefab9b2d12015-10-14 11:33:11 -07001117
1118 // If setting the description decided our SSL role, allocate any necessary
1119 // SCTP sids.
1120 rtc::SSLRole role;
1121 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001122 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001123 AllocateSctpSids(role);
1124 }
1125
1126 // Update state and SSRC of local MediaStreams and DataChannels based on the
1127 // local session description.
1128 const cricket::ContentInfo* audio_content =
1129 GetFirstAudioContent(desc->description());
1130 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001131 if (audio_content->rejected) {
1132 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1133 } else {
1134 const cricket::AudioContentDescription* audio_desc =
1135 static_cast<const cricket::AudioContentDescription*>(
1136 audio_content->description);
1137 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1138 }
deadbeefab9b2d12015-10-14 11:33:11 -07001139 }
1140
1141 const cricket::ContentInfo* video_content =
1142 GetFirstVideoContent(desc->description());
1143 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001144 if (video_content->rejected) {
1145 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1146 } else {
1147 const cricket::VideoContentDescription* video_desc =
1148 static_cast<const cricket::VideoContentDescription*>(
1149 video_content->description);
1150 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1151 }
deadbeefab9b2d12015-10-14 11:33:11 -07001152 }
1153
1154 const cricket::ContentInfo* data_content =
1155 GetFirstDataContent(desc->description());
1156 if (data_content) {
1157 const cricket::DataContentDescription* data_desc =
1158 static_cast<const cricket::DataContentDescription*>(
1159 data_content->description);
1160 if (rtc::starts_with(data_desc->protocol().data(),
1161 cricket::kMediaProtocolRtpPrefix)) {
1162 UpdateLocalRtpDataChannels(data_desc->streams());
1163 }
1164 }
1165
1166 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001167 signaling_thread()->Post(RTC_FROM_HERE, this,
1168 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001169
deadbeefcbecd352015-09-23 11:50:27 -07001170 // MaybeStartGathering needs to be called after posting
1171 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1172 // before signaling that SetLocalDescription completed.
1173 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174}
1175
1176void PeerConnection::SetRemoteDescription(
1177 SetSessionDescriptionObserver* observer,
1178 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001179 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001180 if (IsClosed()) {
1181 return;
1182 }
deadbeefab9b2d12015-10-14 11:33:11 -07001183 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1185 return;
1186 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 if (!desc) {
1188 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1189 return;
1190 }
1191 // Update stats here so that we have the most recent stats for tracks and
1192 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001193 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194 std::string error;
1195 if (!session_->SetRemoteDescription(desc, &error)) {
1196 PostSetSessionDescriptionFailure(observer, error);
1197 return;
1198 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199
deadbeefab9b2d12015-10-14 11:33:11 -07001200 // If setting the description decided our SSL role, allocate any necessary
1201 // SCTP sids.
1202 rtc::SSLRole role;
1203 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001204 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001205 AllocateSctpSids(role);
1206 }
1207
1208 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001209 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1210 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1211 const cricket::AudioContentDescription* audio_desc =
1212 GetFirstAudioContentDescription(remote_desc);
1213 const cricket::VideoContentDescription* video_desc =
1214 GetFirstVideoContentDescription(remote_desc);
1215 const cricket::DataContentDescription* data_desc =
1216 GetFirstDataContentDescription(remote_desc);
1217
1218 // Check if the descriptions include streams, just in case the peer supports
1219 // MSID, but doesn't indicate so with "a=msid-semantic".
1220 if (remote_desc->msid_supported() ||
1221 (audio_desc && !audio_desc->streams().empty()) ||
1222 (video_desc && !video_desc->streams().empty())) {
1223 remote_peer_supports_msid_ = true;
1224 }
deadbeefab9b2d12015-10-14 11:33:11 -07001225
1226 // We wait to signal new streams until we finish processing the description,
1227 // since only at that point will new streams have all their tracks.
1228 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1229
1230 // Find all audio rtp streams and create corresponding remote AudioTracks
1231 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001232 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001233 if (audio_content->rejected) {
1234 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1235 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001236 bool default_audio_track_needed =
1237 !remote_peer_supports_msid_ &&
1238 MediaContentDirectionHasSend(audio_desc->direction());
1239 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1240 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001241 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001242 }
deadbeefab9b2d12015-10-14 11:33:11 -07001243 }
1244
1245 // Find all video rtp streams and create corresponding remote VideoTracks
1246 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001247 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001248 if (video_content->rejected) {
1249 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1250 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001251 bool default_video_track_needed =
1252 !remote_peer_supports_msid_ &&
1253 MediaContentDirectionHasSend(video_desc->direction());
1254 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1255 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001256 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001257 }
deadbeefab9b2d12015-10-14 11:33:11 -07001258 }
1259
1260 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001261 if (data_desc) {
1262 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001263 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001264 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001265 }
1266 }
1267
1268 // Iterate new_streams and notify the observer about new MediaStreams.
1269 for (size_t i = 0; i < new_streams->count(); ++i) {
1270 MediaStreamInterface* new_stream = new_streams->at(i);
1271 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001272 // Call both the raw pointer and scoped_refptr versions of the method
1273 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001274 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001275 observer_->OnAddStream(
1276 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001277 }
1278
deadbeefbda7e0b2015-12-08 17:13:40 -08001279 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001280
1281 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001282 signaling_thread()->Post(RTC_FROM_HERE, this,
1283 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001284}
1285
deadbeef46c73892016-11-16 19:42:04 -08001286PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1287 return configuration_;
1288}
1289
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001290bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001291 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001292
1293 if (session_->local_description() &&
1294 configuration.ice_candidate_pool_size !=
1295 configuration_.ice_candidate_pool_size) {
1296 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1297 "SetLocalDescription.";
1298 return false;
1299 }
deadbeef46c73892016-11-16 19:42:04 -08001300 // TODO(deadbeef): Return false and log an error if there are any unsupported
1301 // modifications.
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001302 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001303 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001304 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001305 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001306 configuration))) {
deadbeef6de92f92016-12-12 18:49:32 -08001307 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001308 return false;
1309 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001310 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001311
deadbeefd1a38b52016-12-10 13:15:33 -08001312 // TODO(deadbeef): Shouldn't have to hop to the network thread twice...
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001313 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001314
deadbeefd1a38b52016-12-10 13:15:33 -08001315 // As described in JSEP, calling setConfiguration with new ICE servers or
1316 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1317 // triggers an ICE restart which will pick up the changes.
1318 if (configuration.servers != configuration_.servers ||
1319 configuration.type != configuration_.type) {
1320 session_->SetNeedsIceRestartFlag();
1321 }
deadbeef46c73892016-11-16 19:42:04 -08001322 configuration_ = configuration;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001323 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001324}
1325
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326bool PeerConnection::AddIceCandidate(
1327 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001328 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001329 if (IsClosed()) {
1330 return false;
1331 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 return session_->ProcessIceMessage(ice_candidate);
1333}
1334
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001335bool PeerConnection::RemoveIceCandidates(
1336 const std::vector<cricket::Candidate>& candidates) {
1337 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1338 return session_->RemoveRemoteIceCandidates(candidates);
1339}
1340
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001341void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001342 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001343 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001344
1345 if (session_) {
1346 session_->set_metrics_observer(uma_observer_);
1347 }
1348
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001349 // Send information about IPv4/IPv6 status.
1350 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001351 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001352 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001353 uma_observer_->IncrementEnumCounter(
1354 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1355 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001356 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001357 uma_observer_->IncrementEnumCounter(
1358 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1359 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001360 }
1361 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001362}
1363
ivoc14d5dbe2016-07-04 07:06:55 -07001364bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1365 int64_t max_size_bytes) {
1366 return factory_->worker_thread()->Invoke<bool>(
1367 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1368 max_size_bytes));
1369}
1370
1371void PeerConnection::StopRtcEventLog() {
1372 factory_->worker_thread()->Invoke<void>(
1373 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1374}
1375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376const SessionDescriptionInterface* PeerConnection::local_description() const {
1377 return session_->local_description();
1378}
1379
1380const SessionDescriptionInterface* PeerConnection::remote_description() const {
1381 return session_->remote_description();
1382}
1383
1384void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001385 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386 // Update stats here so that we have the most recent stats for tracks and
1387 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001388 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389
deadbeefd59daf82015-10-14 15:02:44 -07001390 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391}
1392
deadbeefd59daf82015-10-14 15:02:44 -07001393void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1394 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001396 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001397 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001398 break;
deadbeefd59daf82015-10-14 15:02:44 -07001399 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1401 break;
deadbeefd59daf82015-10-14 15:02:44 -07001402 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1404 break;
deadbeefd59daf82015-10-14 15:02:44 -07001405 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1407 break;
deadbeefd59daf82015-10-14 15:02:44 -07001408 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1410 break;
deadbeefd59daf82015-10-14 15:02:44 -07001411 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 ChangeSignalingState(PeerConnectionInterface::kStable);
1413 break;
deadbeefd59daf82015-10-14 15:02:44 -07001414 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 ChangeSignalingState(PeerConnectionInterface::kClosed);
1416 break;
1417 default:
1418 break;
1419 }
1420}
1421
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001422void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001423 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001424 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1425 SetSessionDescriptionMsg* param =
1426 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1427 param->observer->OnSuccess();
1428 delete param;
1429 break;
1430 }
1431 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1432 SetSessionDescriptionMsg* param =
1433 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1434 param->observer->OnFailure(param->error);
1435 delete param;
1436 break;
1437 }
deadbeefab9b2d12015-10-14 11:33:11 -07001438 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1439 CreateSessionDescriptionMsg* param =
1440 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1441 param->observer->OnFailure(param->error);
1442 delete param;
1443 break;
1444 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445 case MSG_GETSTATS: {
1446 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nisseb36ee8d2016-12-20 03:30:00 -08001447 std::unique_ptr<StatsReports> reports(new StatsReports);
1448 stats_->GetStats(param->track, reports.get());
1449 param->observer->OnCompleteReports(std::move(reports));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 delete param;
1451 break;
1452 }
deadbeefbd292462015-12-14 18:15:29 -08001453 case MSG_FREE_DATACHANNELS: {
1454 sctp_data_channels_to_free_.clear();
1455 break;
1456 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001458 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459 break;
1460 }
1461}
1462
deadbeefab9b2d12015-10-14 11:33:11 -07001463void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001464 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001465 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001466 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1467 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001468 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001469 session_->voice_channel()));
1470
1471 receivers_.push_back(receiver);
1472 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1473 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1474 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475}
1476
deadbeefab9b2d12015-10-14 11:33:11 -07001477void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001478 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001479 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001480 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1481 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001482 signaling_thread(),
1483 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001484 ssrc, session_->video_channel()));
1485 receivers_.push_back(receiver);
1486 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1487 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1488 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489}
1490
deadbeef70ab1a12015-09-28 16:53:55 -07001491// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1492// description.
perkjd61bf802016-03-24 03:16:19 -07001493void PeerConnection::DestroyReceiver(const std::string& track_id) {
1494 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001495 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001496 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001497 << " doesn't exist.";
1498 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001499 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001500 receivers_.erase(it);
1501 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001502}
1503
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001504void PeerConnection::OnIceConnectionChange(
1505 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001506 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001507 // After transitioning to "closed", ignore any additional states from
1508 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001509 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001510 return;
1511 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001513 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514}
1515
1516void PeerConnection::OnIceGatheringChange(
1517 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001518 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519 if (IsClosed()) {
1520 return;
1521 }
1522 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001523 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524}
1525
1526void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001527 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001528 if (IsClosed()) {
1529 return;
1530 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001531 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001532}
1533
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001534void PeerConnection::OnIceCandidatesRemoved(
1535 const std::vector<cricket::Candidate>& candidates) {
1536 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001537 if (IsClosed()) {
1538 return;
1539 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001540 observer_->OnIceCandidatesRemoved(candidates);
1541}
1542
Peter Thatcher54360512015-07-08 11:08:35 -07001543void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001544 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001545 if (IsClosed()) {
1546 return;
1547 }
Peter Thatcher54360512015-07-08 11:08:35 -07001548 observer_->OnIceConnectionReceivingChange(receiving);
1549}
1550
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551void PeerConnection::ChangeSignalingState(
1552 PeerConnectionInterface::SignalingState signaling_state) {
1553 signaling_state_ = signaling_state;
1554 if (signaling_state == kClosed) {
1555 ice_connection_state_ = kIceConnectionClosed;
1556 observer_->OnIceConnectionChange(ice_connection_state_);
1557 if (ice_gathering_state_ != kIceGatheringComplete) {
1558 ice_gathering_state_ = kIceGatheringComplete;
1559 observer_->OnIceGatheringChange(ice_gathering_state_);
1560 }
1561 }
1562 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563}
1564
deadbeefeb459812015-12-15 19:24:43 -08001565void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1566 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001567 if (IsClosed()) {
1568 return;
1569 }
deadbeefeb459812015-12-15 19:24:43 -08001570 auto sender = FindSenderForTrack(track);
1571 if (sender != senders_.end()) {
1572 // We already have a sender for this track, so just change the stream_id
1573 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001574 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001575 return;
1576 }
1577
1578 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001579 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1580 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001581 signaling_thread(),
1582 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1583 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001584 senders_.push_back(new_sender);
1585 // If the sender has already been configured in SDP, we call SetSsrc,
1586 // which will connect the sender to the underlying transport. This can
1587 // occur if a local session description that contains the ID of the sender
1588 // is set before AddStream is called. It can also occur if the local
1589 // session description is not changed and RemoveStream is called, and
1590 // later AddStream is called again with the same stream.
1591 const TrackInfo* track_info =
1592 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1593 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001594 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001595 }
1596}
1597
1598// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1599// indefinitely, when we have unified plan SDP.
1600void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1601 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001602 if (IsClosed()) {
1603 return;
1604 }
deadbeefeb459812015-12-15 19:24:43 -08001605 auto sender = FindSenderForTrack(track);
1606 if (sender == senders_.end()) {
1607 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1608 << " doesn't exist.";
1609 return;
1610 }
deadbeefa601f5c2016-06-06 14:27:39 -07001611 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001612 senders_.erase(sender);
1613}
1614
1615void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1616 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001617 if (IsClosed()) {
1618 return;
1619 }
deadbeefeb459812015-12-15 19:24:43 -08001620 auto sender = FindSenderForTrack(track);
1621 if (sender != senders_.end()) {
1622 // We already have a sender for this track, so just change the stream_id
1623 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001624 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001625 return;
1626 }
1627
1628 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001629 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1630 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001631 signaling_thread(), new VideoRtpSender(track, stream->label(),
1632 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001633 senders_.push_back(new_sender);
1634 const TrackInfo* track_info =
1635 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1636 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001637 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001638 }
1639}
1640
1641void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1642 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001643 if (IsClosed()) {
1644 return;
1645 }
deadbeefeb459812015-12-15 19:24:43 -08001646 auto sender = FindSenderForTrack(track);
1647 if (sender == senders_.end()) {
1648 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1649 << " doesn't exist.";
1650 return;
1651 }
deadbeefa601f5c2016-06-06 14:27:39 -07001652 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001653 senders_.erase(sender);
1654}
1655
deadbeefab9b2d12015-10-14 11:33:11 -07001656void PeerConnection::PostSetSessionDescriptionFailure(
1657 SetSessionDescriptionObserver* observer,
1658 const std::string& error) {
1659 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1660 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001661 signaling_thread()->Post(RTC_FROM_HERE, this,
1662 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001663}
1664
1665void PeerConnection::PostCreateSessionDescriptionFailure(
1666 CreateSessionDescriptionObserver* observer,
1667 const std::string& error) {
1668 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1669 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001670 signaling_thread()->Post(RTC_FROM_HERE, this,
1671 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001672}
1673
1674bool PeerConnection::GetOptionsForOffer(
1675 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1676 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001677 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1678 // ContentInfos.
1679 if (session_->local_description()) {
1680 for (const cricket::ContentInfo& content :
1681 session_->local_description()->description()->contents()) {
1682 session_options->transport_options[content.name] =
1683 cricket::TransportOptions();
1684 }
1685 }
deadbeef46c73892016-11-16 19:42:04 -08001686 session_options->enable_ice_renomination =
1687 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001688
htaaac2dea2016-03-10 13:35:55 -08001689 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001690 return false;
1691 }
1692
deadbeeffac06552015-11-25 11:26:01 -08001693 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001694 // Offer to receive audio/video if the constraint is not set and there are
1695 // send streams, or we're currently receiving.
1696 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1697 session_options->recv_audio =
1698 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1699 !remote_audio_tracks_.empty();
1700 }
1701 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1702 session_options->recv_video =
1703 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1704 !remote_video_tracks_.empty();
1705 }
deadbeefc80741f2015-10-22 13:14:45 -07001706
zhihuang9763d562016-08-05 11:14:50 -07001707 // Intentionally unset the data channel type for RTP data channel with the
1708 // second condition. Otherwise the RTP data channels would be successfully
1709 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1710 // when building with chromium. We want to leave RTP data channels broken, so
1711 // people won't try to use them.
1712 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1713 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001714 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001715
zhihuangaf388472016-11-02 16:49:48 -07001716 session_options->bundle_enabled =
1717 session_options->bundle_enabled &&
1718 (session_options->has_audio() || session_options->has_video() ||
1719 session_options->has_data());
1720
zhihuang8f65cdf2016-05-06 18:40:30 -07001721 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001722 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001723 return true;
1724}
1725
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001726void PeerConnection::InitializeOptionsForAnswer(
1727 cricket::MediaSessionOptions* session_options) {
1728 session_options->recv_audio = false;
1729 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001730 session_options->enable_ice_renomination =
1731 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001732}
1733
htaa2a49d92016-03-04 02:51:39 -08001734void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001735 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001736 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1737 // ContentInfos.
1738 if (session_->remote_description()) {
1739 // Initialize the transport_options map.
1740 for (const cricket::ContentInfo& content :
1741 session_->remote_description()->description()->contents()) {
1742 session_options->transport_options[content.name] =
1743 cricket::TransportOptions();
1744 }
1745 }
deadbeeffac06552015-11-25 11:26:01 -08001746 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001747 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1748 // are not signaled in the SDP so does not go through that path and must be
1749 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001750 // Intentionally unset the data channel type for RTP data channel. Otherwise
1751 // the RTP data channels would be successfully negotiated by default and the
1752 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1753 // We want to leave RTP data channels broken, so people won't try to use them.
1754 if (session_->data_channel_type() != cricket::DCT_RTP) {
1755 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001756 }
zhihuangaf388472016-11-02 16:49:48 -07001757 session_options->bundle_enabled =
1758 session_options->bundle_enabled &&
1759 (session_options->has_audio() || session_options->has_video() ||
1760 session_options->has_data());
1761
jbauchcb560652016-08-04 05:20:32 -07001762 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001763}
1764
1765bool PeerConnection::GetOptionsForAnswer(
1766 const MediaConstraintsInterface* constraints,
1767 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001768 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001769 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1770 return false;
1771 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001772 session_options->rtcp_cname = rtcp_cname_;
1773
htaa2a49d92016-03-04 02:51:39 -08001774 FinishOptionsForAnswer(session_options);
1775 return true;
1776}
1777
1778bool PeerConnection::GetOptionsForAnswer(
1779 const RTCOfferAnswerOptions& options,
1780 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001781 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001782 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001783 return false;
1784 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001785 session_options->rtcp_cname = rtcp_cname_;
1786
htaa2a49d92016-03-04 02:51:39 -08001787 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001788 return true;
1789}
1790
deadbeeffaac4972015-11-12 15:33:07 -08001791void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1792 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001793 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1794 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001795}
1796
deadbeefab9b2d12015-10-14 11:33:11 -07001797void PeerConnection::UpdateRemoteStreamsList(
1798 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001799 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001800 cricket::MediaType media_type,
1801 StreamCollection* new_streams) {
1802 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1803
1804 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001805 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001806 auto track_it = current_tracks->begin();
1807 while (track_it != current_tracks->end()) {
1808 const TrackInfo& info = *track_it;
1809 const cricket::StreamParams* params =
1810 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001811 bool track_exists = params && params->id == info.track_id;
1812 // If this is a default track, and we still need it, don't remove it.
1813 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1814 track_exists) {
1815 ++track_it;
1816 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001817 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1818 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001819 }
1820 }
1821
1822 // Find new and active tracks.
1823 for (const cricket::StreamParams& params : streams) {
1824 // The sync_label is the MediaStream label and the |stream.id| is the
1825 // track id.
1826 const std::string& stream_label = params.sync_label;
1827 const std::string& track_id = params.id;
1828 uint32_t ssrc = params.first_ssrc();
1829
1830 rtc::scoped_refptr<MediaStreamInterface> stream =
1831 remote_streams_->find(stream_label);
1832 if (!stream) {
1833 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001834 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1835 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001836 remote_streams_->AddStream(stream);
1837 new_streams->AddStream(stream);
1838 }
1839
1840 const TrackInfo* track_info =
1841 FindTrackInfo(*current_tracks, stream_label, track_id);
1842 if (!track_info) {
1843 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1844 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1845 }
1846 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001847
1848 // Add default track if necessary.
1849 if (default_track_needed) {
1850 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1851 remote_streams_->find(kDefaultStreamLabel);
1852 if (!default_stream) {
1853 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001854 default_stream = MediaStreamProxy::Create(
1855 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001856 remote_streams_->AddStream(default_stream);
1857 new_streams->AddStream(default_stream);
1858 }
1859 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1860 ? kDefaultAudioTrackLabel
1861 : kDefaultVideoTrackLabel;
1862 const TrackInfo* default_track_info =
1863 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1864 if (!default_track_info) {
1865 current_tracks->push_back(
1866 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1867 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1868 }
1869 }
deadbeefab9b2d12015-10-14 11:33:11 -07001870}
1871
1872void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1873 const std::string& track_id,
1874 uint32_t ssrc,
1875 cricket::MediaType media_type) {
1876 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1877
1878 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001879 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001880 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001881 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001882 } else {
1883 RTC_DCHECK(false && "Invalid media type");
1884 }
1885}
1886
1887void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1888 const std::string& track_id,
1889 cricket::MediaType media_type) {
1890 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1891
1892 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001893 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1894 // will be notified which will end the AudioRtpReceiver::track().
1895 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001896 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1897 stream->FindAudioTrack(track_id);
1898 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001899 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001900 }
1901 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001902 // Stopping or destroying a VideoRtpReceiver will end the
1903 // VideoRtpReceiver::track().
1904 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001905 rtc::scoped_refptr<VideoTrackInterface> video_track =
1906 stream->FindVideoTrack(track_id);
1907 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001908 // There's no guarantee the track is still available, e.g. the track may
1909 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001910 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001911 }
1912 } else {
1913 ASSERT(false && "Invalid media type");
1914 }
1915}
1916
1917void PeerConnection::UpdateEndedRemoteMediaStreams() {
1918 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1919 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1920 MediaStreamInterface* stream = remote_streams_->at(i);
1921 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1922 streams_to_remove.push_back(stream);
1923 }
1924 }
1925
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001926 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001927 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001928 // Call both the raw pointer and scoped_refptr versions of the method
1929 // for compatibility.
1930 observer_->OnRemoveStream(stream.get());
1931 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001932 }
1933}
1934
deadbeefab9b2d12015-10-14 11:33:11 -07001935void PeerConnection::UpdateLocalTracks(
1936 const std::vector<cricket::StreamParams>& streams,
1937 cricket::MediaType media_type) {
1938 TrackInfos* current_tracks = GetLocalTracks(media_type);
1939
1940 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1941 // don't match the new StreamParam.
1942 TrackInfos::iterator track_it = current_tracks->begin();
1943 while (track_it != current_tracks->end()) {
1944 const TrackInfo& info = *track_it;
1945 const cricket::StreamParams* params =
1946 cricket::GetStreamBySsrc(streams, info.ssrc);
1947 if (!params || params->id != info.track_id ||
1948 params->sync_label != info.stream_label) {
1949 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1950 media_type);
1951 track_it = current_tracks->erase(track_it);
1952 } else {
1953 ++track_it;
1954 }
1955 }
1956
1957 // Find new and active tracks.
1958 for (const cricket::StreamParams& params : streams) {
1959 // The sync_label is the MediaStream label and the |stream.id| is the
1960 // track id.
1961 const std::string& stream_label = params.sync_label;
1962 const std::string& track_id = params.id;
1963 uint32_t ssrc = params.first_ssrc();
1964 const TrackInfo* track_info =
1965 FindTrackInfo(*current_tracks, stream_label, track_id);
1966 if (!track_info) {
1967 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1968 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1969 }
1970 }
1971}
1972
1973void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1974 const std::string& track_id,
1975 uint32_t ssrc,
1976 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001977 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001978 if (!sender) {
1979 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1980 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001981 return;
1982 }
1983
deadbeeffac06552015-11-25 11:26:01 -08001984 if (sender->media_type() != media_type) {
1985 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1986 << " description with an unexpected media type.";
1987 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001988 }
deadbeeffac06552015-11-25 11:26:01 -08001989
1990 sender->set_stream_id(stream_label);
1991 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001992}
1993
1994void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1995 const std::string& track_id,
1996 uint32_t ssrc,
1997 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001998 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001999 if (!sender) {
2000 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002001 // SessionDescriptions has been renegotiated.
2002 return;
2003 }
deadbeeffac06552015-11-25 11:26:01 -08002004
2005 // A sender has been removed from the SessionDescription but it's still
2006 // associated with the PeerConnection. This only occurs if the SDP doesn't
2007 // match with the calls to CreateSender, AddStream and RemoveStream.
2008 if (sender->media_type() != media_type) {
2009 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2010 << " description with an unexpected media type.";
2011 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002012 }
deadbeeffac06552015-11-25 11:26:01 -08002013
2014 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002015}
2016
2017void PeerConnection::UpdateLocalRtpDataChannels(
2018 const cricket::StreamParamsVec& streams) {
2019 std::vector<std::string> existing_channels;
2020
2021 // Find new and active data channels.
2022 for (const cricket::StreamParams& params : streams) {
2023 // |it->sync_label| is actually the data channel label. The reason is that
2024 // we use the same naming of data channels as we do for
2025 // MediaStreams and Tracks.
2026 // For MediaStreams, the sync_label is the MediaStream label and the
2027 // track label is the same as |streamid|.
2028 const std::string& channel_label = params.sync_label;
2029 auto data_channel_it = rtp_data_channels_.find(channel_label);
2030 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
2031 continue;
2032 }
2033 // Set the SSRC the data channel should use for sending.
2034 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2035 existing_channels.push_back(data_channel_it->first);
2036 }
2037
2038 UpdateClosingRtpDataChannels(existing_channels, true);
2039}
2040
2041void PeerConnection::UpdateRemoteRtpDataChannels(
2042 const cricket::StreamParamsVec& streams) {
2043 std::vector<std::string> existing_channels;
2044
2045 // Find new and active data channels.
2046 for (const cricket::StreamParams& params : streams) {
2047 // The data channel label is either the mslabel or the SSRC if the mslabel
2048 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2049 std::string label = params.sync_label.empty()
2050 ? rtc::ToString(params.first_ssrc())
2051 : params.sync_label;
2052 auto data_channel_it = rtp_data_channels_.find(label);
2053 if (data_channel_it == rtp_data_channels_.end()) {
2054 // This is a new data channel.
2055 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2056 } else {
2057 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2058 }
2059 existing_channels.push_back(label);
2060 }
2061
2062 UpdateClosingRtpDataChannels(existing_channels, false);
2063}
2064
2065void PeerConnection::UpdateClosingRtpDataChannels(
2066 const std::vector<std::string>& active_channels,
2067 bool is_local_update) {
2068 auto it = rtp_data_channels_.begin();
2069 while (it != rtp_data_channels_.end()) {
2070 DataChannel* data_channel = it->second;
2071 if (std::find(active_channels.begin(), active_channels.end(),
2072 data_channel->label()) != active_channels.end()) {
2073 ++it;
2074 continue;
2075 }
2076
2077 if (is_local_update) {
2078 data_channel->SetSendSsrc(0);
2079 } else {
2080 data_channel->RemotePeerRequestClose();
2081 }
2082
2083 if (data_channel->state() == DataChannel::kClosed) {
2084 rtp_data_channels_.erase(it);
2085 it = rtp_data_channels_.begin();
2086 } else {
2087 ++it;
2088 }
2089 }
2090}
2091
2092void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2093 uint32_t remote_ssrc) {
2094 rtc::scoped_refptr<DataChannel> channel(
2095 InternalCreateDataChannel(label, nullptr));
2096 if (!channel.get()) {
2097 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2098 << "CreateDataChannel failed.";
2099 return;
2100 }
2101 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002102 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2103 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002104 // Call both the raw pointer and scoped_refptr versions of the method
2105 // for compatibility.
2106 observer_->OnDataChannel(proxy_channel.get());
2107 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002108}
2109
2110rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2111 const std::string& label,
2112 const InternalDataChannelInit* config) {
2113 if (IsClosed()) {
2114 return nullptr;
2115 }
2116 if (session_->data_channel_type() == cricket::DCT_NONE) {
2117 LOG(LS_ERROR)
2118 << "InternalCreateDataChannel: Data is not supported in this call.";
2119 return nullptr;
2120 }
2121 InternalDataChannelInit new_config =
2122 config ? (*config) : InternalDataChannelInit();
2123 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2124 if (new_config.id < 0) {
2125 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002126 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002127 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2128 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2129 return nullptr;
2130 }
2131 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2132 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2133 << "because the id is already in use or out of range.";
2134 return nullptr;
2135 }
2136 }
2137
2138 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2139 session_.get(), session_->data_channel_type(), label, new_config));
2140 if (!channel) {
2141 sid_allocator_.ReleaseSid(new_config.id);
2142 return nullptr;
2143 }
2144
2145 if (channel->data_channel_type() == cricket::DCT_RTP) {
2146 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2147 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2148 << " already exists.";
2149 return nullptr;
2150 }
2151 rtp_data_channels_[channel->label()] = channel;
2152 } else {
2153 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2154 sctp_data_channels_.push_back(channel);
2155 channel->SignalClosed.connect(this,
2156 &PeerConnection::OnSctpDataChannelClosed);
2157 }
2158
hbos82ebe022016-11-14 01:41:09 -08002159 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002160 return channel;
2161}
2162
2163bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002164#ifdef HAVE_QUIC
2165 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2166 (session_->quic_data_transport() &&
2167 session_->quic_data_transport()->HasDataChannels());
2168#else
deadbeefab9b2d12015-10-14 11:33:11 -07002169 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002170#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002171}
2172
2173void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2174 for (const auto& channel : sctp_data_channels_) {
2175 if (channel->id() < 0) {
2176 int sid;
2177 if (!sid_allocator_.AllocateSid(role, &sid)) {
2178 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2179 continue;
2180 }
2181 channel->SetSctpSid(sid);
2182 }
2183 }
2184}
2185
2186void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002187 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002188 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2189 ++it) {
2190 if (it->get() == channel) {
2191 if (channel->id() >= 0) {
2192 sid_allocator_.ReleaseSid(channel->id());
2193 }
deadbeefbd292462015-12-14 18:15:29 -08002194 // Since this method is triggered by a signal from the DataChannel,
2195 // we can't free it directly here; we need to free it asynchronously.
2196 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002197 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002198 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2199 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002200 return;
2201 }
2202 }
2203}
2204
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002205void PeerConnection::OnVoiceChannelCreated() {
2206 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2207 session_->voice_channel(), senders_, receivers_,
2208 cricket::MEDIA_TYPE_AUDIO);
2209}
2210
deadbeefab9b2d12015-10-14 11:33:11 -07002211void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002212 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2213 cricket::VoiceChannel>(
2214 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2215}
2216
2217void PeerConnection::OnVideoChannelCreated() {
2218 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2219 session_->video_channel(), senders_, receivers_,
2220 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002221}
2222
2223void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002224 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2225 cricket::VideoChannel>(
2226 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002227}
2228
2229void PeerConnection::OnDataChannelCreated() {
2230 for (const auto& channel : sctp_data_channels_) {
2231 channel->OnTransportChannelCreated();
2232 }
2233}
2234
2235void PeerConnection::OnDataChannelDestroyed() {
2236 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2237 // DataChannel may callback to us and try to modify the list.
2238 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2239 temp_rtp_dcs.swap(rtp_data_channels_);
2240 for (const auto& kv : temp_rtp_dcs) {
2241 kv.second->OnTransportChannelDestroyed();
2242 }
2243
2244 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2245 temp_sctp_dcs.swap(sctp_data_channels_);
2246 for (const auto& channel : temp_sctp_dcs) {
2247 channel->OnTransportChannelDestroyed();
2248 }
2249}
2250
2251void PeerConnection::OnDataChannelOpenMessage(
2252 const std::string& label,
2253 const InternalDataChannelInit& config) {
2254 rtc::scoped_refptr<DataChannel> channel(
2255 InternalCreateDataChannel(label, &config));
2256 if (!channel.get()) {
2257 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2258 return;
2259 }
2260
deadbeefa601f5c2016-06-06 14:27:39 -07002261 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2262 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002263 // Call both the raw pointer and scoped_refptr versions of the method
2264 // for compatibility.
2265 observer_->OnDataChannel(proxy_channel.get());
2266 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002267}
2268
deadbeefa601f5c2016-06-06 14:27:39 -07002269RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2270 auto it = std::find_if(
2271 senders_.begin(), senders_.end(),
2272 [id](const rtc::scoped_refptr<
2273 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2274 return sender->id() == id;
2275 });
2276 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002277}
2278
deadbeefa601f5c2016-06-06 14:27:39 -07002279std::vector<
2280 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002281PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2282 return std::find_if(
2283 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002284 [track](const rtc::scoped_refptr<
2285 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002286 return sender->track() == track;
2287 });
2288}
2289
deadbeefa601f5c2016-06-06 14:27:39 -07002290std::vector<rtc::scoped_refptr<
2291 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002292PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002293 return std::find_if(
2294 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002295 [track_id](const rtc::scoped_refptr<
2296 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002297 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002298 });
2299}
2300
deadbeefab9b2d12015-10-14 11:33:11 -07002301PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2302 cricket::MediaType media_type) {
2303 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2304 media_type == cricket::MEDIA_TYPE_VIDEO);
2305 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2306 : &remote_video_tracks_;
2307}
2308
2309PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2310 cricket::MediaType media_type) {
2311 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2312 media_type == cricket::MEDIA_TYPE_VIDEO);
2313 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2314 : &local_video_tracks_;
2315}
2316
2317const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2318 const PeerConnection::TrackInfos& infos,
2319 const std::string& stream_label,
2320 const std::string track_id) const {
2321 for (const TrackInfo& track_info : infos) {
2322 if (track_info.stream_label == stream_label &&
2323 track_info.track_id == track_id) {
2324 return &track_info;
2325 }
2326 }
2327 return nullptr;
2328}
2329
2330DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2331 for (const auto& channel : sctp_data_channels_) {
2332 if (channel->id() == sid) {
2333 return channel;
2334 }
2335 }
2336 return nullptr;
2337}
2338
deadbeef91dd5672016-05-18 16:55:30 -07002339bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002340 const RTCConfiguration& configuration) {
2341 cricket::ServerAddresses stun_servers;
2342 std::vector<cricket::RelayServerConfig> turn_servers;
2343 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2344 return false;
2345 }
2346
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002347 port_allocator_->Initialize();
2348
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002349 // To handle both internal and externally created port allocator, we will
2350 // enable BUNDLE here.
2351 int portallocator_flags = port_allocator_->flags();
2352 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2353 cricket::PORTALLOCATOR_ENABLE_IPV6;
2354 // If the disable-IPv6 flag was specified, we'll not override it
2355 // by experiment.
2356 if (configuration.disable_ipv6) {
2357 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2358 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2359 "Disabled") {
2360 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2361 }
2362
2363 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2364 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2365 LOG(LS_INFO) << "TCP candidates are disabled.";
2366 }
2367
honghaiz60347052016-05-31 18:29:12 -07002368 if (configuration.candidate_network_policy ==
2369 kCandidateNetworkPolicyLowCost) {
2370 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2371 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2372 }
2373
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002374 port_allocator_->set_flags(portallocator_flags);
2375 // No step delay is used while allocating ports.
2376 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2377 port_allocator_->set_candidate_filter(
2378 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2379
2380 // Call this last since it may create pooled allocator sessions using the
2381 // properties set above.
2382 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002383 configuration.ice_candidate_pool_size,
2384 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002385 return true;
2386}
2387
deadbeef91dd5672016-05-18 16:55:30 -07002388bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002389 const RTCConfiguration& configuration) {
2390 cricket::ServerAddresses stun_servers;
2391 std::vector<cricket::RelayServerConfig> turn_servers;
2392 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2393 return false;
2394 }
2395 port_allocator_->set_candidate_filter(
2396 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2397 // Call this last since it may create pooled allocator sessions using the
2398 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002399 return port_allocator_->SetConfiguration(
2400 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
2401 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002402}
2403
ivoc14d5dbe2016-07-04 07:06:55 -07002404bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2405 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002406 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002407}
2408
2409void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002410 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002411}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412} // namespace webrtc