blob: 58174f08c11bbd10d36e58c3420a3d06ff8b909e [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070037#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010038#include "webrtc/base/trace_event.h"
ossuf515ab82016-12-07 04:52:58 -080039#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070040#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kjellandera96e2d72016-02-04 23:52:28 -080041#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010042#include "webrtc/pc/channelmanager.h"
skvlad11a9cbf2016-10-07 11:53:05 -070043#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010044#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045
46namespace {
47
deadbeefab9b2d12015-10-14 11:33:11 -070048using webrtc::DataChannel;
49using webrtc::MediaConstraintsInterface;
50using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070052using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080053using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070054using webrtc::RtpSenderProxy;
55using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070056using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
deadbeefab9b2d12015-10-14 11:33:11 -070058static const char kDefaultStreamLabel[] = "default";
59static const char kDefaultAudioTrackLabel[] = "defaulta0";
60static const char kDefaultVideoTrackLabel[] = "defaultv0";
61
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062// The min number of tokens must present in Turn host uri.
63// e.g. user@turn.example.org
64static const size_t kTurnHostTokensNum = 2;
65// Number of tokens must be preset when TURN uri has transport param.
66static const size_t kTurnTransportTokensNum = 2;
67// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000068static const int kDefaultStunPort = 3478;
69static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071
72// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070073static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074
zhihuang8f65cdf2016-05-06 18:40:30 -070075// The length of RTCP CNAMEs.
76static const int kRtcpCnameLength = 16;
77
deadbeef0a6c4ca2015-10-06 11:38:28 -070078// NOTE: A loop below assumes that the first value of this enum is 0 and all
79// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000080enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070081 STUN = 0, // Indicates a STUN server.
82 STUNS, // Indicates a STUN server used with a TLS session.
83 TURN, // Indicates a TURN server
84 TURNS, // Indicates a TURN server used with a TLS session.
85 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086};
tfarina5237aaf2015-11-10 23:44:30 -080087static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070088 "kValidIceServiceTypes must have as many strings as ServiceType "
89 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
91enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000092 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070094 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080096 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097};
98
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000099struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 explicit SetSessionDescriptionMsg(
101 webrtc::SetSessionDescriptionObserver* observer)
102 : observer(observer) {
103 }
104
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000105 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 std::string error;
107};
108
deadbeefab9b2d12015-10-14 11:33:11 -0700109struct CreateSessionDescriptionMsg : public rtc::MessageData {
110 explicit CreateSessionDescriptionMsg(
111 webrtc::CreateSessionDescriptionObserver* observer)
112 : observer(observer) {}
113
114 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
115 std::string error;
116};
117
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000118struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000119 GetStatsMsg(webrtc::StatsObserver* observer,
120 webrtc::MediaStreamTrackInterface* track)
121 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000123 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000124 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125};
126
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000127// |in_str| should be of format
128// stunURI = scheme ":" stun-host [ ":" stun-port ]
129// scheme = "stun" / "stuns"
130// stun-host = IP-literal / IPv4address / reg-name
131// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700132//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000133// draft-petithuguenin-behave-turn-uris-01
134// turnURI = scheme ":" turn-host [ ":" turn-port ]
135// turn-host = username@IP-literal / IPv4address / reg-name
136bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
137 ServiceType* service_type,
138 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200139 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700140 if (colonpos == std::string::npos) {
141 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000142 return false;
143 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700144 if ((colonpos + 1) == in_str.length()) {
145 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
146 return false;
147 }
148 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800149 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700150 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000151 *service_type = static_cast<ServiceType>(i);
152 break;
153 }
154 }
155 if (*service_type == INVALID) {
156 return false;
157 }
158 *hostname = in_str.substr(colonpos + 1, std::string::npos);
159 return true;
160}
161
deadbeef0a6c4ca2015-10-06 11:38:28 -0700162bool ParsePort(const std::string& in_str, int* port) {
163 // Make sure port only contains digits. FromString doesn't check this.
164 for (const char& c : in_str) {
165 if (!std::isdigit(c)) {
166 return false;
167 }
168 }
169 return rtc::FromString(in_str, port);
170}
171
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000172// This method parses IPv6 and IPv4 literal strings, along with hostnames in
173// standard hostname:port format.
174// Consider following formats as correct.
175// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700176// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000177bool ParseHostnameAndPortFromString(const std::string& in_str,
178 std::string* host,
179 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700180 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000181 if (in_str.at(0) == '[') {
182 std::string::size_type closebracket = in_str.rfind(']');
183 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 std::string::size_type colonpos = in_str.find(':', closebracket);
185 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700186 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
187 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000188 return false;
189 }
190 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700191 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000192 } else {
193 return false;
194 }
195 } else {
196 std::string::size_type colonpos = in_str.find(':');
197 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700198 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000199 return false;
200 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 } else {
203 *host = in_str;
204 }
205 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700206 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000207}
208
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800209// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700210// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200211bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
212 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800213 cricket::ServerAddresses* stun_servers,
214 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 // draft-nandakumar-rtcweb-stun-uri-01
216 // stunURI = scheme ":" stun-host [ ":" stun-port ]
217 // scheme = "stun" / "stuns"
218 // stun-host = IP-literal / IPv4address / reg-name
219 // stun-port = *DIGIT
220
221 // draft-petithuguenin-behave-turn-uris-01
222 // turnURI = scheme ":" turn-host [ ":" turn-port ]
223 // [ "?transport=" transport ]
224 // scheme = "turn" / "turns"
225 // transport = "udp" / "tcp" / transport-ext
226 // transport-ext = 1*unreserved
227 // turn-host = IP-literal / IPv4address / reg-name
228 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800229 RTC_DCHECK(stun_servers != nullptr);
230 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200231 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800232 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700233 RTC_DCHECK(!url.empty());
hnslbd44bb02016-12-12 03:14:30 -0800234 rtc::tokenize_with_empty_tokens(url, '?', &tokens);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200235 std::string uri_without_transport = tokens[0];
236 // Let's look into transport= param, if it exists.
237 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
238 std::string uri_transport_param = tokens[1];
hnslbd44bb02016-12-12 03:14:30 -0800239 rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
240 if (tokens[0] != kTransport) {
241 LOG(LS_WARNING) << "Invalid transport parameter key.";
242 return false;
243 }
244 if (tokens.size() < 2 ||
245 !cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
246 (turn_transport_type != cricket::PROTO_UDP &&
247 turn_transport_type != cricket::PROTO_TCP)) {
248 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
249 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200251 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000252
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200253 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700254 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200255 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
256 &service_type,
257 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700258 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
259 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000261
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
263 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200264
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200265 // Let's break hostname.
266 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700267 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
268
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200269 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270 if (tokens.size() > kTurnHostTokensNum) {
271 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
272 return false;
273 }
274 if (tokens.size() == kTurnHostTokensNum) {
275 if (tokens[0].empty() || tokens[1].empty()) {
276 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
277 return false;
278 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200279 username.assign(rtc::s_url_decode(tokens[0]));
280 hoststring = tokens[1];
281 } else {
282 hoststring = tokens[0];
283 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000284
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200285 int port = kDefaultStunPort;
286 if (service_type == TURNS) {
287 port = kDefaultStunTlsPort;
hnsl277b2502016-12-13 05:17:23 -0800288 turn_transport_type = cricket::PROTO_TLS;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200289 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000290
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200291 std::string address;
292 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700293 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
294 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200295 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000296
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 if (port <= 0 || port > 0xffff) {
298 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700299 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200300 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000301
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200302 switch (service_type) {
303 case STUN:
304 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800305 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200306 break;
307 case TURN:
308 case TURNS: {
magjedd5236e22016-12-20 02:22:06 -0800309 turn_servers->push_back(cricket::RelayServerConfig(
310 address, port, username, server.password, turn_transport_type));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200311 break;
312 }
313 case INVALID:
314 default:
315 LOG(WARNING) << "Configuration not supported: " << url;
316 return false;
317 }
318 return true;
319}
320
deadbeefab9b2d12015-10-14 11:33:11 -0700321// Check if we can send |new_stream| on a PeerConnection.
322bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
323 webrtc::MediaStreamInterface* new_stream) {
324 if (!new_stream || !current_streams) {
325 return false;
326 }
327 if (current_streams->find(new_stream->label()) != nullptr) {
328 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
329 << " is already added.";
330 return false;
331 }
332 return true;
333}
334
335bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
336 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
337}
338
deadbeef5e97fb52015-10-15 12:49:08 -0700339// If the direction is "recvonly" or "inactive", treat the description
340// as containing no streams.
341// See: https://code.google.com/p/webrtc/issues/detail?id=5054
342std::vector<cricket::StreamParams> GetActiveStreams(
343 const cricket::MediaContentDescription* desc) {
344 return MediaContentDirectionHasSend(desc->direction())
345 ? desc->streams()
346 : std::vector<cricket::StreamParams>();
347}
348
deadbeefab9b2d12015-10-14 11:33:11 -0700349bool IsValidOfferToReceiveMedia(int value) {
350 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
351 return (value >= Options::kUndefined) &&
352 (value <= Options::kMaxOfferToReceiveMedia);
353}
354
355// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800356void AddSendStreams(
357 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700358 const std::vector<rtc::scoped_refptr<
359 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800360 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
361 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700362 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800363 for (const auto& sender : senders) {
364 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700365 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700366 }
367
368 // Check for data channels.
369 for (const auto& kv : rtp_data_channels) {
370 const DataChannel* channel = kv.second;
371 if (channel->state() == DataChannel::kConnecting ||
372 channel->state() == DataChannel::kOpen) {
373 // |streamid| and |sync_label| are both set to the DataChannel label
374 // here so they can be signaled the same way as MediaStreams and Tracks.
375 // For MediaStreams, the sync_label is the MediaStream label and the
376 // track label is the same as |streamid|.
377 const std::string& streamid = channel->label();
378 const std::string& sync_label = channel->label();
379 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
380 sync_label);
381 }
382 }
383}
384
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700385uint32_t ConvertIceTransportTypeToCandidateFilter(
386 PeerConnectionInterface::IceTransportsType type) {
387 switch (type) {
388 case PeerConnectionInterface::kNone:
389 return cricket::CF_NONE;
390 case PeerConnectionInterface::kRelay:
391 return cricket::CF_RELAY;
392 case PeerConnectionInterface::kNoHost:
393 return (cricket::CF_ALL & ~cricket::CF_HOST);
394 case PeerConnectionInterface::kAll:
395 return cricket::CF_ALL;
396 default:
397 ASSERT(false);
398 }
399 return cricket::CF_NONE;
400}
401
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700402// Helper method to set a voice/video channel on all applicable senders
403// and receivers when one is created/destroyed by WebRtcSession.
404//
405// Used by On(Voice|Video)Channel(Created|Destroyed)
406template <class SENDER,
407 class RECEIVER,
408 class CHANNEL,
409 class SENDERS,
410 class RECEIVERS>
411void SetChannelOnSendersAndReceivers(CHANNEL* channel,
412 SENDERS& senders,
413 RECEIVERS& receivers,
414 cricket::MediaType media_type) {
415 for (auto& sender : senders) {
416 if (sender->media_type() == media_type) {
417 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
418 }
419 }
420 for (auto& receiver : receivers) {
421 if (receiver->media_type() == media_type) {
422 if (!channel) {
423 receiver->internal()->Stop();
424 }
425 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
426 }
427 }
428}
429
deadbeef0a6c4ca2015-10-06 11:38:28 -0700430} // namespace
431
432namespace webrtc {
433
deadbeef3edec7c2016-12-10 11:44:26 -0800434static const char* const kRtcErrorNames[] = {
435 "NONE",
436 "UNSUPPORTED_PARAMETER",
437 "INVALID_PARAMETER",
438 "INVALID_RANGE",
439 "SYNTAX_ERROR",
440 "INVALID_STATE",
441 "INVALID_MODIFICATION",
442 "NETWORK_ERROR",
443 "INTERNAL_ERROR",
444};
445
446std::ostream& operator<<(std::ostream& stream, RtcError error) {
447 int index = static_cast<int>(error);
448 RTC_CHECK(index < static_cast<int>(sizeof(kRtcErrorNames) /
449 sizeof(kRtcErrorNames[0])));
450 return stream << kRtcErrorNames[index];
451}
452
zhihuang8f65cdf2016-05-06 18:40:30 -0700453// Generate a RTCP CNAME when a PeerConnection is created.
454std::string GenerateRtcpCname() {
455 std::string cname;
456 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
457 LOG(LS_ERROR) << "Failed to generate CNAME.";
458 RTC_DCHECK(false);
459 }
460 return cname;
461}
462
htaa2a49d92016-03-04 02:51:39 -0800463bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700464 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800465 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700466 cricket::MediaSessionOptions* session_options) {
467 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
468 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
469 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
470 return false;
471 }
472
htaaac2dea2016-03-10 13:35:55 -0800473 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700474 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700475 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800476 } else {
477 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700478 }
htaaac2dea2016-03-10 13:35:55 -0800479 // For offers, we only offer video if we have it or it's forced by options.
480 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700481 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700482 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800483 } else if (is_offer) {
484 session_options->recv_video = false;
485 } else {
486 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700487 }
488
489 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700490 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800491 for (auto& kv : session_options->transport_options) {
492 kv.second.ice_restart = rtc_options.ice_restart;
493 }
deadbeefab9b2d12015-10-14 11:33:11 -0700494
495 return true;
496}
497
498bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
499 cricket::MediaSessionOptions* session_options) {
500 bool value = false;
501 size_t mandatory_constraints_satisfied = 0;
502
503 // kOfferToReceiveAudio defaults to true according to spec.
504 if (!FindConstraint(constraints,
505 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
506 &mandatory_constraints_satisfied) ||
507 value) {
508 session_options->recv_audio = true;
509 }
510
511 // kOfferToReceiveVideo defaults to false according to spec. But
512 // if it is an answer and video is offered, we should still accept video
513 // per default.
514 value = false;
515 if (!FindConstraint(constraints,
516 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
517 &mandatory_constraints_satisfied) ||
518 value) {
519 session_options->recv_video = true;
520 }
521
522 if (FindConstraint(constraints,
523 MediaConstraintsInterface::kVoiceActivityDetection, &value,
524 &mandatory_constraints_satisfied)) {
525 session_options->vad_enabled = value;
526 }
527
528 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
529 &mandatory_constraints_satisfied)) {
530 session_options->bundle_enabled = value;
531 } else {
532 // kUseRtpMux defaults to true according to spec.
533 session_options->bundle_enabled = true;
534 }
deadbeefab9b2d12015-10-14 11:33:11 -0700535
deadbeef0ed85b22016-02-23 17:24:52 -0800536 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700537 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
538 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700539 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800540 ice_restart = true;
541 }
542 for (auto& kv : session_options->transport_options) {
543 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700544 }
545
546 if (!constraints) {
547 return true;
548 }
549 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
550}
551
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200552bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800553 cricket::ServerAddresses* stun_servers,
554 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200555 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
556 if (!server.urls.empty()) {
557 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200558 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700559 LOG(LS_ERROR) << "Empty uri.";
560 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200561 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800562 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200563 return false;
564 }
565 }
566 } else if (!server.uri.empty()) {
567 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800568 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000569 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200570 }
571 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700572 LOG(LS_ERROR) << "Empty uri.";
573 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000574 }
575 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800576 // Candidates must have unique priorities, so that connectivity checks
577 // are performed in a well-defined order.
578 int priority = static_cast<int>(turn_servers->size() - 1);
579 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
580 // First in the list gets highest priority.
581 turn_server.priority = priority--;
582 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000583 return true;
584}
585
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586PeerConnection::PeerConnection(PeerConnectionFactory* factory)
587 : factory_(factory),
588 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000589 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700592 ice_gathering_state_(kIceGatheringNew),
skvlad11a9cbf2016-10-07 11:53:05 -0700593 event_log_(RtcEventLog::Create(webrtc::Clock::GetRealTimeClock())),
zhihuang8f65cdf2016-05-06 18:40:30 -0700594 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700595 local_streams_(StreamCollection::Create()),
596 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597
598PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100599 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700600 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700601 // Need to detach RTP senders/receivers from WebRtcSession,
602 // since it's about to be destroyed.
603 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700604 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700605 }
606 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700607 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700608 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700609 // Destroy stats_ because it depends on session_.
610 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800611 if (stats_collector_) {
612 stats_collector_->WaitForPendingRequest();
613 stats_collector_ = nullptr;
614 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700615 // Now destroy session_ before destroying other members,
616 // because its destruction fires signals (such as VoiceChannelDestroyed)
617 // which will trigger some final actions in PeerConnection...
618 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700619 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700620 network_thread()->Invoke<void>(RTC_FROM_HERE,
621 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000622}
623
624bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000625 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700626 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200627 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800628 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100629 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800630 RTC_DCHECK(observer != nullptr);
631 if (!observer) {
632 return false;
633 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000634 observer_ = observer;
635
kwiberg0eb15ed2015-12-17 03:04:15 -0800636 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800637
deadbeef91dd5672016-05-18 16:55:30 -0700638 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700639 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700640 if (!network_thread()->Invoke<bool>(
641 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
642 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643 return false;
644 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645
skvlad11a9cbf2016-10-07 11:53:05 -0700646 media_controller_.reset(factory_->CreateMediaController(
647 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000648
zhihuang29ff8442016-07-27 11:07:25 -0700649 session_.reset(new WebRtcSession(
650 media_controller_.get(), factory_->network_thread(),
651 factory_->worker_thread(), factory_->signaling_thread(),
652 port_allocator_.get(),
653 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700654 factory_->CreateTransportController(
655 port_allocator_.get(),
656 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700657
deadbeefab9b2d12015-10-14 11:33:11 -0700658 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700659 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000660
661 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200662 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800663 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700665 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667 // Register PeerConnection as receiver of local ice candidates.
668 // All the callbacks will be posted to the application from PeerConnection.
669 session_->RegisterIceObserver(this);
670 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700671 session_->SignalVoiceChannelCreated.connect(
672 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700673 session_->SignalVoiceChannelDestroyed.connect(
674 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700675 session_->SignalVideoChannelCreated.connect(
676 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700677 session_->SignalVideoChannelDestroyed.connect(
678 this, &PeerConnection::OnVideoChannelDestroyed);
679 session_->SignalDataChannelCreated.connect(
680 this, &PeerConnection::OnDataChannelCreated);
681 session_->SignalDataChannelDestroyed.connect(
682 this, &PeerConnection::OnDataChannelDestroyed);
683 session_->SignalDataChannelOpenMessage.connect(
684 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800685
686 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000687 return true;
688}
689
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000690rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700692 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693}
694
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000695rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700697 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698}
699
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000700bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100701 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702 if (IsClosed()) {
703 return false;
704 }
deadbeefab9b2d12015-10-14 11:33:11 -0700705 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000706 return false;
707 }
deadbeefab9b2d12015-10-14 11:33:11 -0700708
709 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800710 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
711 observer->SignalAudioTrackAdded.connect(this,
712 &PeerConnection::OnAudioTrackAdded);
713 observer->SignalAudioTrackRemoved.connect(
714 this, &PeerConnection::OnAudioTrackRemoved);
715 observer->SignalVideoTrackAdded.connect(this,
716 &PeerConnection::OnVideoTrackAdded);
717 observer->SignalVideoTrackRemoved.connect(
718 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700719 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700720
deadbeefab9b2d12015-10-14 11:33:11 -0700721 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800722 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700723 }
724 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800725 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700726 }
727
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000728 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 observer_->OnRenegotiationNeeded();
730 return true;
731}
732
733void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100734 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700735 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800736 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700737 }
738 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800739 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700740 }
741
742 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800743 stream_observers_.erase(
744 std::remove_if(
745 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700746 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800747 return observer->stream()->label().compare(local_stream->label()) ==
748 0;
749 }),
750 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700751
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752 if (IsClosed()) {
753 return;
754 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000755 observer_->OnRenegotiationNeeded();
756}
757
deadbeefe1f9d832016-01-14 15:35:42 -0800758rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
759 MediaStreamTrackInterface* track,
760 std::vector<MediaStreamInterface*> streams) {
761 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
762 if (IsClosed()) {
763 return nullptr;
764 }
765 if (streams.size() >= 2) {
766 LOG(LS_ERROR)
767 << "Adding a track with two streams is not currently supported.";
768 return nullptr;
769 }
770 // TODO(deadbeef): Support adding a track to two different senders.
771 if (FindSenderForTrack(track) != senders_.end()) {
772 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
773 return nullptr;
774 }
775
776 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700777 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800778 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700779 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800780 signaling_thread(),
781 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700782 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800783 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700784 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800785 }
786 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700787 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800788 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700789 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800790 }
791 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700792 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800793 signaling_thread(),
794 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700795 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800796 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700797 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800798 }
799 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700800 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800801 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700802 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800803 }
804 } else {
805 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
806 return rtc::scoped_refptr<RtpSenderInterface>();
807 }
808
809 senders_.push_back(new_sender);
810 observer_->OnRenegotiationNeeded();
811 return new_sender;
812}
813
814bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
815 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
816 if (IsClosed()) {
817 return false;
818 }
819
820 auto it = std::find(senders_.begin(), senders_.end(), sender);
821 if (it == senders_.end()) {
822 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
823 return false;
824 }
deadbeefa601f5c2016-06-06 14:27:39 -0700825 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800826 senders_.erase(it);
827
828 observer_->OnRenegotiationNeeded();
829 return true;
830}
831
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000832rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100834 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700835 if (IsClosed()) {
836 return nullptr;
837 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 if (!track) {
839 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
840 return NULL;
841 }
deadbeefab9b2d12015-10-14 11:33:11 -0700842 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
844 return NULL;
845 }
846
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000847 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 DtmfSender::Create(track, signaling_thread(), session_.get()));
849 if (!sender.get()) {
850 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
851 return NULL;
852 }
853 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
854}
855
deadbeeffac06552015-11-25 11:26:01 -0800856rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800857 const std::string& kind,
858 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100859 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700860 if (IsClosed()) {
861 return nullptr;
862 }
deadbeefa601f5c2016-06-06 14:27:39 -0700863 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800864 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700865 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700866 signaling_thread(),
867 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800868 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700869 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700870 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800871 } else {
872 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800873 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800874 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800875 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700876 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800877 }
deadbeeffac06552015-11-25 11:26:01 -0800878 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800879 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800880}
881
deadbeef70ab1a12015-09-28 16:53:55 -0700882std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
883 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700884 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
885 for (const auto& sender : senders_) {
886 ret.push_back(sender.get());
887 }
888 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700889}
890
891std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
892PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700893 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
894 for (const auto& receiver : receivers_) {
895 ret.push_back(receiver.get());
896 }
897 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700898}
899
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000901 MediaStreamTrackInterface* track,
902 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100903 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700904 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905 if (!VERIFY(observer != NULL)) {
906 LOG(LS_ERROR) << "GetStats - observer is NULL.";
907 return false;
908 }
909
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000910 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700911 // The StatsCollector is used to tell if a track is valid because it may
912 // remember tracks that the PeerConnection previously removed.
913 if (track && !stats_->IsValidTrack(track->id())) {
914 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
915 << track->id();
916 return false;
917 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700918 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000919 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920 return true;
921}
922
hbos74e1a4f2016-09-15 23:33:01 -0700923void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
924 RTC_DCHECK(stats_collector_);
925 stats_collector_->GetStatsReport(callback);
926}
927
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
929 return signaling_state_;
930}
931
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932PeerConnectionInterface::IceConnectionState
933PeerConnection::ice_connection_state() {
934 return ice_connection_state_;
935}
936
937PeerConnectionInterface::IceGatheringState
938PeerConnection::ice_gathering_state() {
939 return ice_gathering_state_;
940}
941
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000942rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943PeerConnection::CreateDataChannel(
944 const std::string& label,
945 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100946 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700947#ifdef HAVE_QUIC
948 if (session_->data_channel_type() == cricket::DCT_QUIC) {
949 // TODO(zhihuang): Handle case when config is NULL.
950 if (!config) {
951 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
952 return nullptr;
953 }
954 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
955 if (!config->reliable || config->ordered) {
956 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
957 "ordered delivery.";
958 return nullptr;
959 }
960 return session_->quic_data_transport()->CreateDataChannel(label, config);
961 }
962#endif // HAVE_QUIC
963
deadbeefab9b2d12015-10-14 11:33:11 -0700964 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000965
kwibergd1fe2812016-04-27 06:47:29 -0700966 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000967 if (config) {
968 internal_config.reset(new InternalDataChannelInit(*config));
969 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000970 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700971 InternalCreateDataChannel(label, internal_config.get()));
972 if (!channel.get()) {
973 return nullptr;
974 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000975
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000976 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
977 // the first SCTP DataChannel.
978 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
979 observer_->OnRenegotiationNeeded();
980 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000981
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982 return DataChannelProxy::Create(signaling_thread(), channel.get());
983}
984
985void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
986 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100987 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700988 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
990 return;
991 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000992 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000993
994 bool value;
995 size_t mandatory_constraints = 0;
996
997 if (FindConstraint(constraints,
998 MediaConstraintsInterface::kOfferToReceiveAudio,
999 &value,
1000 &mandatory_constraints)) {
1001 options.offer_to_receive_audio =
1002 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1003 }
1004
1005 if (FindConstraint(constraints,
1006 MediaConstraintsInterface::kOfferToReceiveVideo,
1007 &value,
1008 &mandatory_constraints)) {
1009 options.offer_to_receive_video =
1010 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
1011 }
1012
1013 if (FindConstraint(constraints,
1014 MediaConstraintsInterface::kVoiceActivityDetection,
1015 &value,
1016 &mandatory_constraints)) {
1017 options.voice_activity_detection = value;
1018 }
1019
1020 if (FindConstraint(constraints,
1021 MediaConstraintsInterface::kIceRestart,
1022 &value,
1023 &mandatory_constraints)) {
1024 options.ice_restart = value;
1025 }
1026
1027 if (FindConstraint(constraints,
1028 MediaConstraintsInterface::kUseRtpMux,
1029 &value,
1030 &mandatory_constraints)) {
1031 options.use_rtp_mux = value;
1032 }
1033
1034 CreateOffer(observer, options);
1035}
1036
1037void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1038 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001039 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001040 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001041 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1042 return;
1043 }
deadbeefab9b2d12015-10-14 11:33:11 -07001044
1045 cricket::MediaSessionOptions session_options;
1046 if (!GetOptionsForOffer(options, &session_options)) {
1047 std::string error = "CreateOffer called with invalid options.";
1048 LOG(LS_ERROR) << error;
1049 PostCreateSessionDescriptionFailure(observer, error);
1050 return;
1051 }
1052
1053 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054}
1055
1056void PeerConnection::CreateAnswer(
1057 CreateSessionDescriptionObserver* observer,
1058 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001059 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001060 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1062 return;
1063 }
deadbeefab9b2d12015-10-14 11:33:11 -07001064
1065 cricket::MediaSessionOptions session_options;
1066 if (!GetOptionsForAnswer(constraints, &session_options)) {
1067 std::string error = "CreateAnswer called with invalid constraints.";
1068 LOG(LS_ERROR) << error;
1069 PostCreateSessionDescriptionFailure(observer, error);
1070 return;
1071 }
1072
htaa2a49d92016-03-04 02:51:39 -08001073 session_->CreateAnswer(observer, session_options);
1074}
1075
1076void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1077 const RTCOfferAnswerOptions& options) {
1078 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1079 if (!VERIFY(observer != nullptr)) {
1080 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1081 return;
1082 }
1083
1084 cricket::MediaSessionOptions session_options;
1085 if (!GetOptionsForAnswer(options, &session_options)) {
1086 std::string error = "CreateAnswer called with invalid options.";
1087 LOG(LS_ERROR) << error;
1088 PostCreateSessionDescriptionFailure(observer, error);
1089 return;
1090 }
1091
1092 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093}
1094
1095void PeerConnection::SetLocalDescription(
1096 SetSessionDescriptionObserver* observer,
1097 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001098 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001099 if (IsClosed()) {
1100 return;
1101 }
deadbeefab9b2d12015-10-14 11:33:11 -07001102 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001103 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1104 return;
1105 }
1106 if (!desc) {
1107 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1108 return;
1109 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 // Update stats here so that we have the most recent stats for tracks and
1111 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001112 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001113 std::string error;
1114 if (!session_->SetLocalDescription(desc, &error)) {
1115 PostSetSessionDescriptionFailure(observer, error);
1116 return;
1117 }
deadbeefab9b2d12015-10-14 11:33:11 -07001118
1119 // If setting the description decided our SSL role, allocate any necessary
1120 // SCTP sids.
1121 rtc::SSLRole role;
1122 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001123 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001124 AllocateSctpSids(role);
1125 }
1126
1127 // Update state and SSRC of local MediaStreams and DataChannels based on the
1128 // local session description.
1129 const cricket::ContentInfo* audio_content =
1130 GetFirstAudioContent(desc->description());
1131 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001132 if (audio_content->rejected) {
1133 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1134 } else {
1135 const cricket::AudioContentDescription* audio_desc =
1136 static_cast<const cricket::AudioContentDescription*>(
1137 audio_content->description);
1138 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1139 }
deadbeefab9b2d12015-10-14 11:33:11 -07001140 }
1141
1142 const cricket::ContentInfo* video_content =
1143 GetFirstVideoContent(desc->description());
1144 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001145 if (video_content->rejected) {
1146 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1147 } else {
1148 const cricket::VideoContentDescription* video_desc =
1149 static_cast<const cricket::VideoContentDescription*>(
1150 video_content->description);
1151 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1152 }
deadbeefab9b2d12015-10-14 11:33:11 -07001153 }
1154
1155 const cricket::ContentInfo* data_content =
1156 GetFirstDataContent(desc->description());
1157 if (data_content) {
1158 const cricket::DataContentDescription* data_desc =
1159 static_cast<const cricket::DataContentDescription*>(
1160 data_content->description);
1161 if (rtc::starts_with(data_desc->protocol().data(),
1162 cricket::kMediaProtocolRtpPrefix)) {
1163 UpdateLocalRtpDataChannels(data_desc->streams());
1164 }
1165 }
1166
1167 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001168 signaling_thread()->Post(RTC_FROM_HERE, this,
1169 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001170
deadbeefcbecd352015-09-23 11:50:27 -07001171 // MaybeStartGathering needs to be called after posting
1172 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1173 // before signaling that SetLocalDescription completed.
1174 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175}
1176
1177void PeerConnection::SetRemoteDescription(
1178 SetSessionDescriptionObserver* observer,
1179 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001180 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001181 if (IsClosed()) {
1182 return;
1183 }
deadbeefab9b2d12015-10-14 11:33:11 -07001184 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1186 return;
1187 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 if (!desc) {
1189 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1190 return;
1191 }
1192 // Update stats here so that we have the most recent stats for tracks and
1193 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001194 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001195 std::string error;
1196 if (!session_->SetRemoteDescription(desc, &error)) {
1197 PostSetSessionDescriptionFailure(observer, error);
1198 return;
1199 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200
deadbeefab9b2d12015-10-14 11:33:11 -07001201 // If setting the description decided our SSL role, allocate any necessary
1202 // SCTP sids.
1203 rtc::SSLRole role;
1204 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001205 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001206 AllocateSctpSids(role);
1207 }
1208
1209 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001210 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1211 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1212 const cricket::AudioContentDescription* audio_desc =
1213 GetFirstAudioContentDescription(remote_desc);
1214 const cricket::VideoContentDescription* video_desc =
1215 GetFirstVideoContentDescription(remote_desc);
1216 const cricket::DataContentDescription* data_desc =
1217 GetFirstDataContentDescription(remote_desc);
1218
1219 // Check if the descriptions include streams, just in case the peer supports
1220 // MSID, but doesn't indicate so with "a=msid-semantic".
1221 if (remote_desc->msid_supported() ||
1222 (audio_desc && !audio_desc->streams().empty()) ||
1223 (video_desc && !video_desc->streams().empty())) {
1224 remote_peer_supports_msid_ = true;
1225 }
deadbeefab9b2d12015-10-14 11:33:11 -07001226
1227 // We wait to signal new streams until we finish processing the description,
1228 // since only at that point will new streams have all their tracks.
1229 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1230
1231 // Find all audio rtp streams and create corresponding remote AudioTracks
1232 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001233 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001234 if (audio_content->rejected) {
1235 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1236 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001237 bool default_audio_track_needed =
1238 !remote_peer_supports_msid_ &&
1239 MediaContentDirectionHasSend(audio_desc->direction());
1240 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1241 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001242 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001243 }
deadbeefab9b2d12015-10-14 11:33:11 -07001244 }
1245
1246 // Find all video rtp streams and create corresponding remote VideoTracks
1247 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001248 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001249 if (video_content->rejected) {
1250 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1251 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001252 bool default_video_track_needed =
1253 !remote_peer_supports_msid_ &&
1254 MediaContentDirectionHasSend(video_desc->direction());
1255 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1256 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001257 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001258 }
deadbeefab9b2d12015-10-14 11:33:11 -07001259 }
1260
1261 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001262 if (data_desc) {
1263 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001264 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001265 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001266 }
1267 }
1268
1269 // Iterate new_streams and notify the observer about new MediaStreams.
1270 for (size_t i = 0; i < new_streams->count(); ++i) {
1271 MediaStreamInterface* new_stream = new_streams->at(i);
1272 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001273 // Call both the raw pointer and scoped_refptr versions of the method
1274 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001275 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001276 observer_->OnAddStream(
1277 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001278 }
1279
deadbeefbda7e0b2015-12-08 17:13:40 -08001280 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001281
1282 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001283 signaling_thread()->Post(RTC_FROM_HERE, this,
1284 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001285}
1286
deadbeef46c73892016-11-16 19:42:04 -08001287PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1288 return configuration_;
1289}
1290
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001291bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001292 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001293
1294 if (session_->local_description() &&
1295 configuration.ice_candidate_pool_size !=
1296 configuration_.ice_candidate_pool_size) {
1297 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1298 "SetLocalDescription.";
1299 return false;
1300 }
deadbeef46c73892016-11-16 19:42:04 -08001301 // TODO(deadbeef): Return false and log an error if there are any unsupported
1302 // modifications.
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001303 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001304 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001305 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001306 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001307 configuration))) {
deadbeef6de92f92016-12-12 18:49:32 -08001308 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001309 return false;
1310 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001311 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001312
deadbeefd1a38b52016-12-10 13:15:33 -08001313 // TODO(deadbeef): Shouldn't have to hop to the network thread twice...
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001314 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001315
deadbeefd1a38b52016-12-10 13:15:33 -08001316 // As described in JSEP, calling setConfiguration with new ICE servers or
1317 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1318 // triggers an ICE restart which will pick up the changes.
1319 if (configuration.servers != configuration_.servers ||
1320 configuration.type != configuration_.type) {
1321 session_->SetNeedsIceRestartFlag();
1322 }
deadbeef46c73892016-11-16 19:42:04 -08001323 configuration_ = configuration;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001324 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001325}
1326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327bool PeerConnection::AddIceCandidate(
1328 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001329 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001330 if (IsClosed()) {
1331 return false;
1332 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333 return session_->ProcessIceMessage(ice_candidate);
1334}
1335
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001336bool PeerConnection::RemoveIceCandidates(
1337 const std::vector<cricket::Candidate>& candidates) {
1338 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1339 return session_->RemoveRemoteIceCandidates(candidates);
1340}
1341
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001342void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001343 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001344 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001345
1346 if (session_) {
1347 session_->set_metrics_observer(uma_observer_);
1348 }
1349
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001350 // Send information about IPv4/IPv6 status.
1351 if (uma_observer_ && port_allocator_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001352 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001353 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001354 uma_observer_->IncrementEnumCounter(
1355 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1356 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001357 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001358 uma_observer_->IncrementEnumCounter(
1359 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1360 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001361 }
1362 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001363}
1364
ivoc14d5dbe2016-07-04 07:06:55 -07001365bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1366 int64_t max_size_bytes) {
1367 return factory_->worker_thread()->Invoke<bool>(
1368 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1369 max_size_bytes));
1370}
1371
1372void PeerConnection::StopRtcEventLog() {
1373 factory_->worker_thread()->Invoke<void>(
1374 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1375}
1376
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377const SessionDescriptionInterface* PeerConnection::local_description() const {
1378 return session_->local_description();
1379}
1380
1381const SessionDescriptionInterface* PeerConnection::remote_description() const {
1382 return session_->remote_description();
1383}
1384
1385void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001386 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 // Update stats here so that we have the most recent stats for tracks and
1388 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001389 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390
deadbeefd59daf82015-10-14 15:02:44 -07001391 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392}
1393
deadbeefd59daf82015-10-14 15:02:44 -07001394void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1395 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001397 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001399 break;
deadbeefd59daf82015-10-14 15:02:44 -07001400 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1402 break;
deadbeefd59daf82015-10-14 15:02:44 -07001403 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1405 break;
deadbeefd59daf82015-10-14 15:02:44 -07001406 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1408 break;
deadbeefd59daf82015-10-14 15:02:44 -07001409 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1411 break;
deadbeefd59daf82015-10-14 15:02:44 -07001412 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 ChangeSignalingState(PeerConnectionInterface::kStable);
1414 break;
deadbeefd59daf82015-10-14 15:02:44 -07001415 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 ChangeSignalingState(PeerConnectionInterface::kClosed);
1417 break;
1418 default:
1419 break;
1420 }
1421}
1422
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001423void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001424 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1426 SetSessionDescriptionMsg* param =
1427 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1428 param->observer->OnSuccess();
1429 delete param;
1430 break;
1431 }
1432 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1433 SetSessionDescriptionMsg* param =
1434 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1435 param->observer->OnFailure(param->error);
1436 delete param;
1437 break;
1438 }
deadbeefab9b2d12015-10-14 11:33:11 -07001439 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1440 CreateSessionDescriptionMsg* param =
1441 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1442 param->observer->OnFailure(param->error);
1443 delete param;
1444 break;
1445 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446 case MSG_GETSTATS: {
1447 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001448 StatsReports reports;
1449 stats_->GetStats(param->track, &reports);
1450 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451 delete param;
1452 break;
1453 }
deadbeefbd292462015-12-14 18:15:29 -08001454 case MSG_FREE_DATACHANNELS: {
1455 sctp_data_channels_to_free_.clear();
1456 break;
1457 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001459 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 break;
1461 }
1462}
1463
deadbeefab9b2d12015-10-14 11:33:11 -07001464void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001465 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001466 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001467 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1468 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001469 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
zhihuang81c3a032016-11-17 12:06:24 -08001470 session_->voice_channel()));
1471
1472 receivers_.push_back(receiver);
1473 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1474 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1475 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476}
1477
deadbeefab9b2d12015-10-14 11:33:11 -07001478void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001479 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001480 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001481 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1482 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001483 signaling_thread(),
1484 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
zhihuang81c3a032016-11-17 12:06:24 -08001485 ssrc, session_->video_channel()));
1486 receivers_.push_back(receiver);
1487 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1488 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1489 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490}
1491
deadbeef70ab1a12015-09-28 16:53:55 -07001492// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1493// description.
perkjd61bf802016-03-24 03:16:19 -07001494void PeerConnection::DestroyReceiver(const std::string& track_id) {
1495 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001496 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001497 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001498 << " doesn't exist.";
1499 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001500 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001501 receivers_.erase(it);
1502 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503}
1504
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505void PeerConnection::OnIceConnectionChange(
1506 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001507 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001508 // After transitioning to "closed", ignore any additional states from
1509 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001510 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001511 return;
1512 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001513 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001514 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001515}
1516
1517void PeerConnection::OnIceGatheringChange(
1518 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001519 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001520 if (IsClosed()) {
1521 return;
1522 }
1523 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001524 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001525}
1526
1527void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001528 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001529 if (IsClosed()) {
1530 return;
1531 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001532 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533}
1534
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001535void PeerConnection::OnIceCandidatesRemoved(
1536 const std::vector<cricket::Candidate>& candidates) {
1537 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001538 if (IsClosed()) {
1539 return;
1540 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001541 observer_->OnIceCandidatesRemoved(candidates);
1542}
1543
Peter Thatcher54360512015-07-08 11:08:35 -07001544void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001545 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001546 if (IsClosed()) {
1547 return;
1548 }
Peter Thatcher54360512015-07-08 11:08:35 -07001549 observer_->OnIceConnectionReceivingChange(receiving);
1550}
1551
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001552void PeerConnection::ChangeSignalingState(
1553 PeerConnectionInterface::SignalingState signaling_state) {
1554 signaling_state_ = signaling_state;
1555 if (signaling_state == kClosed) {
1556 ice_connection_state_ = kIceConnectionClosed;
1557 observer_->OnIceConnectionChange(ice_connection_state_);
1558 if (ice_gathering_state_ != kIceGatheringComplete) {
1559 ice_gathering_state_ = kIceGatheringComplete;
1560 observer_->OnIceGatheringChange(ice_gathering_state_);
1561 }
1562 }
1563 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001564}
1565
deadbeefeb459812015-12-15 19:24:43 -08001566void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1567 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001568 if (IsClosed()) {
1569 return;
1570 }
deadbeefeb459812015-12-15 19:24:43 -08001571 auto sender = FindSenderForTrack(track);
1572 if (sender != senders_.end()) {
1573 // We already have a sender for this track, so just change the stream_id
1574 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001575 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001576 return;
1577 }
1578
1579 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001580 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1581 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001582 signaling_thread(),
1583 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1584 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001585 senders_.push_back(new_sender);
1586 // If the sender has already been configured in SDP, we call SetSsrc,
1587 // which will connect the sender to the underlying transport. This can
1588 // occur if a local session description that contains the ID of the sender
1589 // is set before AddStream is called. It can also occur if the local
1590 // session description is not changed and RemoveStream is called, and
1591 // later AddStream is called again with the same stream.
1592 const TrackInfo* track_info =
1593 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1594 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001595 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001596 }
1597}
1598
1599// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1600// indefinitely, when we have unified plan SDP.
1601void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1602 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001603 if (IsClosed()) {
1604 return;
1605 }
deadbeefeb459812015-12-15 19:24:43 -08001606 auto sender = FindSenderForTrack(track);
1607 if (sender == senders_.end()) {
1608 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1609 << " doesn't exist.";
1610 return;
1611 }
deadbeefa601f5c2016-06-06 14:27:39 -07001612 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001613 senders_.erase(sender);
1614}
1615
1616void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1617 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001618 if (IsClosed()) {
1619 return;
1620 }
deadbeefeb459812015-12-15 19:24:43 -08001621 auto sender = FindSenderForTrack(track);
1622 if (sender != senders_.end()) {
1623 // We already have a sender for this track, so just change the stream_id
1624 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001625 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001626 return;
1627 }
1628
1629 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001630 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1631 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001632 signaling_thread(), new VideoRtpSender(track, stream->label(),
1633 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001634 senders_.push_back(new_sender);
1635 const TrackInfo* track_info =
1636 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1637 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001638 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001639 }
1640}
1641
1642void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1643 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001644 if (IsClosed()) {
1645 return;
1646 }
deadbeefeb459812015-12-15 19:24:43 -08001647 auto sender = FindSenderForTrack(track);
1648 if (sender == senders_.end()) {
1649 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1650 << " doesn't exist.";
1651 return;
1652 }
deadbeefa601f5c2016-06-06 14:27:39 -07001653 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001654 senders_.erase(sender);
1655}
1656
deadbeefab9b2d12015-10-14 11:33:11 -07001657void PeerConnection::PostSetSessionDescriptionFailure(
1658 SetSessionDescriptionObserver* observer,
1659 const std::string& error) {
1660 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1661 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001662 signaling_thread()->Post(RTC_FROM_HERE, this,
1663 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001664}
1665
1666void PeerConnection::PostCreateSessionDescriptionFailure(
1667 CreateSessionDescriptionObserver* observer,
1668 const std::string& error) {
1669 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1670 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001671 signaling_thread()->Post(RTC_FROM_HERE, this,
1672 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001673}
1674
1675bool PeerConnection::GetOptionsForOffer(
1676 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1677 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001678 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1679 // ContentInfos.
1680 if (session_->local_description()) {
1681 for (const cricket::ContentInfo& content :
1682 session_->local_description()->description()->contents()) {
1683 session_options->transport_options[content.name] =
1684 cricket::TransportOptions();
1685 }
1686 }
deadbeef46c73892016-11-16 19:42:04 -08001687 session_options->enable_ice_renomination =
1688 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001689
htaaac2dea2016-03-10 13:35:55 -08001690 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001691 return false;
1692 }
1693
deadbeeffac06552015-11-25 11:26:01 -08001694 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001695 // Offer to receive audio/video if the constraint is not set and there are
1696 // send streams, or we're currently receiving.
1697 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1698 session_options->recv_audio =
1699 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1700 !remote_audio_tracks_.empty();
1701 }
1702 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1703 session_options->recv_video =
1704 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1705 !remote_video_tracks_.empty();
1706 }
deadbeefc80741f2015-10-22 13:14:45 -07001707
zhihuang9763d562016-08-05 11:14:50 -07001708 // Intentionally unset the data channel type for RTP data channel with the
1709 // second condition. Otherwise the RTP data channels would be successfully
1710 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1711 // when building with chromium. We want to leave RTP data channels broken, so
1712 // people won't try to use them.
1713 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1714 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001715 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001716
zhihuangaf388472016-11-02 16:49:48 -07001717 session_options->bundle_enabled =
1718 session_options->bundle_enabled &&
1719 (session_options->has_audio() || session_options->has_video() ||
1720 session_options->has_data());
1721
zhihuang8f65cdf2016-05-06 18:40:30 -07001722 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001723 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001724 return true;
1725}
1726
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001727void PeerConnection::InitializeOptionsForAnswer(
1728 cricket::MediaSessionOptions* session_options) {
1729 session_options->recv_audio = false;
1730 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001731 session_options->enable_ice_renomination =
1732 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001733}
1734
htaa2a49d92016-03-04 02:51:39 -08001735void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001736 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001737 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1738 // ContentInfos.
1739 if (session_->remote_description()) {
1740 // Initialize the transport_options map.
1741 for (const cricket::ContentInfo& content :
1742 session_->remote_description()->description()->contents()) {
1743 session_options->transport_options[content.name] =
1744 cricket::TransportOptions();
1745 }
1746 }
deadbeeffac06552015-11-25 11:26:01 -08001747 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001748 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1749 // are not signaled in the SDP so does not go through that path and must be
1750 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001751 // Intentionally unset the data channel type for RTP data channel. Otherwise
1752 // the RTP data channels would be successfully negotiated by default and the
1753 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1754 // We want to leave RTP data channels broken, so people won't try to use them.
1755 if (session_->data_channel_type() != cricket::DCT_RTP) {
1756 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001757 }
zhihuangaf388472016-11-02 16:49:48 -07001758 session_options->bundle_enabled =
1759 session_options->bundle_enabled &&
1760 (session_options->has_audio() || session_options->has_video() ||
1761 session_options->has_data());
1762
jbauchcb560652016-08-04 05:20:32 -07001763 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001764}
1765
1766bool PeerConnection::GetOptionsForAnswer(
1767 const MediaConstraintsInterface* constraints,
1768 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001769 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001770 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1771 return false;
1772 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001773 session_options->rtcp_cname = rtcp_cname_;
1774
htaa2a49d92016-03-04 02:51:39 -08001775 FinishOptionsForAnswer(session_options);
1776 return true;
1777}
1778
1779bool PeerConnection::GetOptionsForAnswer(
1780 const RTCOfferAnswerOptions& options,
1781 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001782 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001783 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001784 return false;
1785 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001786 session_options->rtcp_cname = rtcp_cname_;
1787
htaa2a49d92016-03-04 02:51:39 -08001788 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001789 return true;
1790}
1791
deadbeeffaac4972015-11-12 15:33:07 -08001792void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1793 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001794 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1795 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001796}
1797
deadbeefab9b2d12015-10-14 11:33:11 -07001798void PeerConnection::UpdateRemoteStreamsList(
1799 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001800 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001801 cricket::MediaType media_type,
1802 StreamCollection* new_streams) {
1803 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1804
1805 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001806 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001807 auto track_it = current_tracks->begin();
1808 while (track_it != current_tracks->end()) {
1809 const TrackInfo& info = *track_it;
1810 const cricket::StreamParams* params =
1811 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001812 bool track_exists = params && params->id == info.track_id;
1813 // If this is a default track, and we still need it, don't remove it.
1814 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1815 track_exists) {
1816 ++track_it;
1817 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001818 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1819 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001820 }
1821 }
1822
1823 // Find new and active tracks.
1824 for (const cricket::StreamParams& params : streams) {
1825 // The sync_label is the MediaStream label and the |stream.id| is the
1826 // track id.
1827 const std::string& stream_label = params.sync_label;
1828 const std::string& track_id = params.id;
1829 uint32_t ssrc = params.first_ssrc();
1830
1831 rtc::scoped_refptr<MediaStreamInterface> stream =
1832 remote_streams_->find(stream_label);
1833 if (!stream) {
1834 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001835 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1836 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001837 remote_streams_->AddStream(stream);
1838 new_streams->AddStream(stream);
1839 }
1840
1841 const TrackInfo* track_info =
1842 FindTrackInfo(*current_tracks, stream_label, track_id);
1843 if (!track_info) {
1844 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1845 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1846 }
1847 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001848
1849 // Add default track if necessary.
1850 if (default_track_needed) {
1851 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1852 remote_streams_->find(kDefaultStreamLabel);
1853 if (!default_stream) {
1854 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001855 default_stream = MediaStreamProxy::Create(
1856 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001857 remote_streams_->AddStream(default_stream);
1858 new_streams->AddStream(default_stream);
1859 }
1860 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1861 ? kDefaultAudioTrackLabel
1862 : kDefaultVideoTrackLabel;
1863 const TrackInfo* default_track_info =
1864 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1865 if (!default_track_info) {
1866 current_tracks->push_back(
1867 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1868 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1869 }
1870 }
deadbeefab9b2d12015-10-14 11:33:11 -07001871}
1872
1873void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1874 const std::string& track_id,
1875 uint32_t ssrc,
1876 cricket::MediaType media_type) {
1877 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1878
1879 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001880 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001881 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001882 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001883 } else {
1884 RTC_DCHECK(false && "Invalid media type");
1885 }
1886}
1887
1888void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1889 const std::string& track_id,
1890 cricket::MediaType media_type) {
1891 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1892
1893 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001894 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1895 // will be notified which will end the AudioRtpReceiver::track().
1896 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001897 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1898 stream->FindAudioTrack(track_id);
1899 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001900 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001901 }
1902 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001903 // Stopping or destroying a VideoRtpReceiver will end the
1904 // VideoRtpReceiver::track().
1905 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001906 rtc::scoped_refptr<VideoTrackInterface> video_track =
1907 stream->FindVideoTrack(track_id);
1908 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001909 // There's no guarantee the track is still available, e.g. the track may
1910 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001911 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001912 }
1913 } else {
1914 ASSERT(false && "Invalid media type");
1915 }
1916}
1917
1918void PeerConnection::UpdateEndedRemoteMediaStreams() {
1919 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1920 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1921 MediaStreamInterface* stream = remote_streams_->at(i);
1922 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1923 streams_to_remove.push_back(stream);
1924 }
1925 }
1926
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001927 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001928 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001929 // Call both the raw pointer and scoped_refptr versions of the method
1930 // for compatibility.
1931 observer_->OnRemoveStream(stream.get());
1932 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001933 }
1934}
1935
deadbeefab9b2d12015-10-14 11:33:11 -07001936void PeerConnection::UpdateLocalTracks(
1937 const std::vector<cricket::StreamParams>& streams,
1938 cricket::MediaType media_type) {
1939 TrackInfos* current_tracks = GetLocalTracks(media_type);
1940
1941 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1942 // don't match the new StreamParam.
1943 TrackInfos::iterator track_it = current_tracks->begin();
1944 while (track_it != current_tracks->end()) {
1945 const TrackInfo& info = *track_it;
1946 const cricket::StreamParams* params =
1947 cricket::GetStreamBySsrc(streams, info.ssrc);
1948 if (!params || params->id != info.track_id ||
1949 params->sync_label != info.stream_label) {
1950 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1951 media_type);
1952 track_it = current_tracks->erase(track_it);
1953 } else {
1954 ++track_it;
1955 }
1956 }
1957
1958 // Find new and active tracks.
1959 for (const cricket::StreamParams& params : streams) {
1960 // The sync_label is the MediaStream label and the |stream.id| is the
1961 // track id.
1962 const std::string& stream_label = params.sync_label;
1963 const std::string& track_id = params.id;
1964 uint32_t ssrc = params.first_ssrc();
1965 const TrackInfo* track_info =
1966 FindTrackInfo(*current_tracks, stream_label, track_id);
1967 if (!track_info) {
1968 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1969 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1970 }
1971 }
1972}
1973
1974void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1975 const std::string& track_id,
1976 uint32_t ssrc,
1977 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001978 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001979 if (!sender) {
1980 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1981 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001982 return;
1983 }
1984
deadbeeffac06552015-11-25 11:26:01 -08001985 if (sender->media_type() != media_type) {
1986 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1987 << " description with an unexpected media type.";
1988 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001989 }
deadbeeffac06552015-11-25 11:26:01 -08001990
1991 sender->set_stream_id(stream_label);
1992 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001993}
1994
1995void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1996 const std::string& track_id,
1997 uint32_t ssrc,
1998 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001999 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002000 if (!sender) {
2001 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002002 // SessionDescriptions has been renegotiated.
2003 return;
2004 }
deadbeeffac06552015-11-25 11:26:01 -08002005
2006 // A sender has been removed from the SessionDescription but it's still
2007 // associated with the PeerConnection. This only occurs if the SDP doesn't
2008 // match with the calls to CreateSender, AddStream and RemoveStream.
2009 if (sender->media_type() != media_type) {
2010 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2011 << " description with an unexpected media type.";
2012 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002013 }
deadbeeffac06552015-11-25 11:26:01 -08002014
2015 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002016}
2017
2018void PeerConnection::UpdateLocalRtpDataChannels(
2019 const cricket::StreamParamsVec& streams) {
2020 std::vector<std::string> existing_channels;
2021
2022 // Find new and active data channels.
2023 for (const cricket::StreamParams& params : streams) {
2024 // |it->sync_label| is actually the data channel label. The reason is that
2025 // we use the same naming of data channels as we do for
2026 // MediaStreams and Tracks.
2027 // For MediaStreams, the sync_label is the MediaStream label and the
2028 // track label is the same as |streamid|.
2029 const std::string& channel_label = params.sync_label;
2030 auto data_channel_it = rtp_data_channels_.find(channel_label);
2031 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
2032 continue;
2033 }
2034 // Set the SSRC the data channel should use for sending.
2035 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2036 existing_channels.push_back(data_channel_it->first);
2037 }
2038
2039 UpdateClosingRtpDataChannels(existing_channels, true);
2040}
2041
2042void PeerConnection::UpdateRemoteRtpDataChannels(
2043 const cricket::StreamParamsVec& streams) {
2044 std::vector<std::string> existing_channels;
2045
2046 // Find new and active data channels.
2047 for (const cricket::StreamParams& params : streams) {
2048 // The data channel label is either the mslabel or the SSRC if the mslabel
2049 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2050 std::string label = params.sync_label.empty()
2051 ? rtc::ToString(params.first_ssrc())
2052 : params.sync_label;
2053 auto data_channel_it = rtp_data_channels_.find(label);
2054 if (data_channel_it == rtp_data_channels_.end()) {
2055 // This is a new data channel.
2056 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2057 } else {
2058 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2059 }
2060 existing_channels.push_back(label);
2061 }
2062
2063 UpdateClosingRtpDataChannels(existing_channels, false);
2064}
2065
2066void PeerConnection::UpdateClosingRtpDataChannels(
2067 const std::vector<std::string>& active_channels,
2068 bool is_local_update) {
2069 auto it = rtp_data_channels_.begin();
2070 while (it != rtp_data_channels_.end()) {
2071 DataChannel* data_channel = it->second;
2072 if (std::find(active_channels.begin(), active_channels.end(),
2073 data_channel->label()) != active_channels.end()) {
2074 ++it;
2075 continue;
2076 }
2077
2078 if (is_local_update) {
2079 data_channel->SetSendSsrc(0);
2080 } else {
2081 data_channel->RemotePeerRequestClose();
2082 }
2083
2084 if (data_channel->state() == DataChannel::kClosed) {
2085 rtp_data_channels_.erase(it);
2086 it = rtp_data_channels_.begin();
2087 } else {
2088 ++it;
2089 }
2090 }
2091}
2092
2093void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2094 uint32_t remote_ssrc) {
2095 rtc::scoped_refptr<DataChannel> channel(
2096 InternalCreateDataChannel(label, nullptr));
2097 if (!channel.get()) {
2098 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2099 << "CreateDataChannel failed.";
2100 return;
2101 }
2102 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002103 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2104 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002105 // Call both the raw pointer and scoped_refptr versions of the method
2106 // for compatibility.
2107 observer_->OnDataChannel(proxy_channel.get());
2108 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002109}
2110
2111rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2112 const std::string& label,
2113 const InternalDataChannelInit* config) {
2114 if (IsClosed()) {
2115 return nullptr;
2116 }
2117 if (session_->data_channel_type() == cricket::DCT_NONE) {
2118 LOG(LS_ERROR)
2119 << "InternalCreateDataChannel: Data is not supported in this call.";
2120 return nullptr;
2121 }
2122 InternalDataChannelInit new_config =
2123 config ? (*config) : InternalDataChannelInit();
2124 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2125 if (new_config.id < 0) {
2126 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002127 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002128 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2129 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2130 return nullptr;
2131 }
2132 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2133 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2134 << "because the id is already in use or out of range.";
2135 return nullptr;
2136 }
2137 }
2138
2139 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2140 session_.get(), session_->data_channel_type(), label, new_config));
2141 if (!channel) {
2142 sid_allocator_.ReleaseSid(new_config.id);
2143 return nullptr;
2144 }
2145
2146 if (channel->data_channel_type() == cricket::DCT_RTP) {
2147 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2148 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2149 << " already exists.";
2150 return nullptr;
2151 }
2152 rtp_data_channels_[channel->label()] = channel;
2153 } else {
2154 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2155 sctp_data_channels_.push_back(channel);
2156 channel->SignalClosed.connect(this,
2157 &PeerConnection::OnSctpDataChannelClosed);
2158 }
2159
hbos82ebe022016-11-14 01:41:09 -08002160 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002161 return channel;
2162}
2163
2164bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002165#ifdef HAVE_QUIC
2166 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2167 (session_->quic_data_transport() &&
2168 session_->quic_data_transport()->HasDataChannels());
2169#else
deadbeefab9b2d12015-10-14 11:33:11 -07002170 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002171#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002172}
2173
2174void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2175 for (const auto& channel : sctp_data_channels_) {
2176 if (channel->id() < 0) {
2177 int sid;
2178 if (!sid_allocator_.AllocateSid(role, &sid)) {
2179 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2180 continue;
2181 }
2182 channel->SetSctpSid(sid);
2183 }
2184 }
2185}
2186
2187void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002188 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002189 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2190 ++it) {
2191 if (it->get() == channel) {
2192 if (channel->id() >= 0) {
2193 sid_allocator_.ReleaseSid(channel->id());
2194 }
deadbeefbd292462015-12-14 18:15:29 -08002195 // Since this method is triggered by a signal from the DataChannel,
2196 // we can't free it directly here; we need to free it asynchronously.
2197 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002198 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002199 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2200 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002201 return;
2202 }
2203 }
2204}
2205
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002206void PeerConnection::OnVoiceChannelCreated() {
2207 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2208 session_->voice_channel(), senders_, receivers_,
2209 cricket::MEDIA_TYPE_AUDIO);
2210}
2211
deadbeefab9b2d12015-10-14 11:33:11 -07002212void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002213 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2214 cricket::VoiceChannel>(
2215 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2216}
2217
2218void PeerConnection::OnVideoChannelCreated() {
2219 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2220 session_->video_channel(), senders_, receivers_,
2221 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002222}
2223
2224void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002225 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2226 cricket::VideoChannel>(
2227 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002228}
2229
2230void PeerConnection::OnDataChannelCreated() {
2231 for (const auto& channel : sctp_data_channels_) {
2232 channel->OnTransportChannelCreated();
2233 }
2234}
2235
2236void PeerConnection::OnDataChannelDestroyed() {
2237 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2238 // DataChannel may callback to us and try to modify the list.
2239 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2240 temp_rtp_dcs.swap(rtp_data_channels_);
2241 for (const auto& kv : temp_rtp_dcs) {
2242 kv.second->OnTransportChannelDestroyed();
2243 }
2244
2245 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2246 temp_sctp_dcs.swap(sctp_data_channels_);
2247 for (const auto& channel : temp_sctp_dcs) {
2248 channel->OnTransportChannelDestroyed();
2249 }
2250}
2251
2252void PeerConnection::OnDataChannelOpenMessage(
2253 const std::string& label,
2254 const InternalDataChannelInit& config) {
2255 rtc::scoped_refptr<DataChannel> channel(
2256 InternalCreateDataChannel(label, &config));
2257 if (!channel.get()) {
2258 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2259 return;
2260 }
2261
deadbeefa601f5c2016-06-06 14:27:39 -07002262 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2263 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002264 // Call both the raw pointer and scoped_refptr versions of the method
2265 // for compatibility.
2266 observer_->OnDataChannel(proxy_channel.get());
2267 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002268}
2269
deadbeefa601f5c2016-06-06 14:27:39 -07002270RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2271 auto it = std::find_if(
2272 senders_.begin(), senders_.end(),
2273 [id](const rtc::scoped_refptr<
2274 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2275 return sender->id() == id;
2276 });
2277 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002278}
2279
deadbeefa601f5c2016-06-06 14:27:39 -07002280std::vector<
2281 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002282PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2283 return std::find_if(
2284 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002285 [track](const rtc::scoped_refptr<
2286 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002287 return sender->track() == track;
2288 });
2289}
2290
deadbeefa601f5c2016-06-06 14:27:39 -07002291std::vector<rtc::scoped_refptr<
2292 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002293PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002294 return std::find_if(
2295 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002296 [track_id](const rtc::scoped_refptr<
2297 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002298 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002299 });
2300}
2301
deadbeefab9b2d12015-10-14 11:33:11 -07002302PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2303 cricket::MediaType media_type) {
2304 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2305 media_type == cricket::MEDIA_TYPE_VIDEO);
2306 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2307 : &remote_video_tracks_;
2308}
2309
2310PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2311 cricket::MediaType media_type) {
2312 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2313 media_type == cricket::MEDIA_TYPE_VIDEO);
2314 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2315 : &local_video_tracks_;
2316}
2317
2318const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2319 const PeerConnection::TrackInfos& infos,
2320 const std::string& stream_label,
2321 const std::string track_id) const {
2322 for (const TrackInfo& track_info : infos) {
2323 if (track_info.stream_label == stream_label &&
2324 track_info.track_id == track_id) {
2325 return &track_info;
2326 }
2327 }
2328 return nullptr;
2329}
2330
2331DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2332 for (const auto& channel : sctp_data_channels_) {
2333 if (channel->id() == sid) {
2334 return channel;
2335 }
2336 }
2337 return nullptr;
2338}
2339
deadbeef91dd5672016-05-18 16:55:30 -07002340bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002341 const RTCConfiguration& configuration) {
2342 cricket::ServerAddresses stun_servers;
2343 std::vector<cricket::RelayServerConfig> turn_servers;
2344 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2345 return false;
2346 }
2347
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002348 port_allocator_->Initialize();
2349
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002350 // To handle both internal and externally created port allocator, we will
2351 // enable BUNDLE here.
2352 int portallocator_flags = port_allocator_->flags();
2353 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2354 cricket::PORTALLOCATOR_ENABLE_IPV6;
2355 // If the disable-IPv6 flag was specified, we'll not override it
2356 // by experiment.
2357 if (configuration.disable_ipv6) {
2358 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2359 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2360 "Disabled") {
2361 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2362 }
2363
2364 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2365 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2366 LOG(LS_INFO) << "TCP candidates are disabled.";
2367 }
2368
honghaiz60347052016-05-31 18:29:12 -07002369 if (configuration.candidate_network_policy ==
2370 kCandidateNetworkPolicyLowCost) {
2371 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2372 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2373 }
2374
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002375 port_allocator_->set_flags(portallocator_flags);
2376 // No step delay is used while allocating ports.
2377 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2378 port_allocator_->set_candidate_filter(
2379 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2380
2381 // Call this last since it may create pooled allocator sessions using the
2382 // properties set above.
2383 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002384 configuration.ice_candidate_pool_size,
2385 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002386 return true;
2387}
2388
deadbeef91dd5672016-05-18 16:55:30 -07002389bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002390 const RTCConfiguration& configuration) {
2391 cricket::ServerAddresses stun_servers;
2392 std::vector<cricket::RelayServerConfig> turn_servers;
2393 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2394 return false;
2395 }
2396 port_allocator_->set_candidate_filter(
2397 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2398 // Call this last since it may create pooled allocator sessions using the
2399 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002400 return port_allocator_->SetConfiguration(
2401 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
2402 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002403}
2404
ivoc14d5dbe2016-07-04 07:06:55 -07002405bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2406 int64_t max_size_bytes) {
skvlad11a9cbf2016-10-07 11:53:05 -07002407 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002408}
2409
2410void PeerConnection::StopRtcEventLog_w() {
skvlad11a9cbf2016-10-07 11:53:05 -07002411 event_log_->StopLogging();
ivoc14d5dbe2016-07-04 07:06:55 -07002412}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413} // namespace webrtc