blob: 6b5cc69b955a832810cfd8e8dd0053c899028b4b [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"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000034#include "webrtc/base/logging.h"
35#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070036#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010037#include "webrtc/base/trace_event.h"
kjellandera96e2d72016-02-04 23:52:28 -080038#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010039#include "webrtc/pc/channelmanager.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010040#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000041
42namespace {
43
deadbeefab9b2d12015-10-14 11:33:11 -070044using webrtc::DataChannel;
45using webrtc::MediaConstraintsInterface;
46using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000047using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070048using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080049using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070050using webrtc::RtpSenderProxy;
51using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070052using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
deadbeefab9b2d12015-10-14 11:33:11 -070054static const char kDefaultStreamLabel[] = "default";
55static const char kDefaultAudioTrackLabel[] = "defaulta0";
56static const char kDefaultVideoTrackLabel[] = "defaultv0";
57
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058// The min number of tokens must present in Turn host uri.
59// e.g. user@turn.example.org
60static const size_t kTurnHostTokensNum = 2;
61// Number of tokens must be preset when TURN uri has transport param.
62static const size_t kTurnTransportTokensNum = 2;
63// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000064static const int kDefaultStunPort = 3478;
65static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000067
68// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070069static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070
zhihuang8f65cdf2016-05-06 18:40:30 -070071// The length of RTCP CNAMEs.
72static const int kRtcpCnameLength = 16;
73
deadbeef0a6c4ca2015-10-06 11:38:28 -070074// NOTE: A loop below assumes that the first value of this enum is 0 and all
75// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070077 STUN = 0, // Indicates a STUN server.
78 STUNS, // Indicates a STUN server used with a TLS session.
79 TURN, // Indicates a TURN server
80 TURNS, // Indicates a TURN server used with a TLS session.
81 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082};
tfarina5237aaf2015-11-10 23:44:30 -080083static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070084 "kValidIceServiceTypes must have as many strings as ServiceType "
85 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086
87enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000088 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070090 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080092 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093};
94
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000095struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096 explicit SetSessionDescriptionMsg(
97 webrtc::SetSessionDescriptionObserver* observer)
98 : observer(observer) {
99 }
100
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000101 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102 std::string error;
103};
104
deadbeefab9b2d12015-10-14 11:33:11 -0700105struct CreateSessionDescriptionMsg : public rtc::MessageData {
106 explicit CreateSessionDescriptionMsg(
107 webrtc::CreateSessionDescriptionObserver* observer)
108 : observer(observer) {}
109
110 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
111 std::string error;
112};
113
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000115 GetStatsMsg(webrtc::StatsObserver* observer,
116 webrtc::MediaStreamTrackInterface* track)
117 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000119 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000120 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121};
122
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000123// |in_str| should be of format
124// stunURI = scheme ":" stun-host [ ":" stun-port ]
125// scheme = "stun" / "stuns"
126// stun-host = IP-literal / IPv4address / reg-name
127// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700128//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000129// draft-petithuguenin-behave-turn-uris-01
130// turnURI = scheme ":" turn-host [ ":" turn-port ]
131// turn-host = username@IP-literal / IPv4address / reg-name
132bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
133 ServiceType* service_type,
134 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200135 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700136 if (colonpos == std::string::npos) {
137 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000138 return false;
139 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700140 if ((colonpos + 1) == in_str.length()) {
141 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
142 return false;
143 }
144 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800145 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700146 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000147 *service_type = static_cast<ServiceType>(i);
148 break;
149 }
150 }
151 if (*service_type == INVALID) {
152 return false;
153 }
154 *hostname = in_str.substr(colonpos + 1, std::string::npos);
155 return true;
156}
157
deadbeef0a6c4ca2015-10-06 11:38:28 -0700158bool ParsePort(const std::string& in_str, int* port) {
159 // Make sure port only contains digits. FromString doesn't check this.
160 for (const char& c : in_str) {
161 if (!std::isdigit(c)) {
162 return false;
163 }
164 }
165 return rtc::FromString(in_str, port);
166}
167
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000168// This method parses IPv6 and IPv4 literal strings, along with hostnames in
169// standard hostname:port format.
170// Consider following formats as correct.
171// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700172// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000173bool ParseHostnameAndPortFromString(const std::string& in_str,
174 std::string* host,
175 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700176 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000177 if (in_str.at(0) == '[') {
178 std::string::size_type closebracket = in_str.rfind(']');
179 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000180 std::string::size_type colonpos = in_str.find(':', closebracket);
181 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700182 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
183 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 return false;
185 }
186 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700187 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000188 } else {
189 return false;
190 }
191 } else {
192 std::string::size_type colonpos = in_str.find(':');
193 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700194 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000195 return false;
196 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700197 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000198 } else {
199 *host = in_str;
200 }
201 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700202 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000203}
204
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800205// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700206// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200207bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
208 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800209 cricket::ServerAddresses* stun_servers,
210 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000211 // draft-nandakumar-rtcweb-stun-uri-01
212 // stunURI = scheme ":" stun-host [ ":" stun-port ]
213 // scheme = "stun" / "stuns"
214 // stun-host = IP-literal / IPv4address / reg-name
215 // stun-port = *DIGIT
216
217 // draft-petithuguenin-behave-turn-uris-01
218 // turnURI = scheme ":" turn-host [ ":" turn-port ]
219 // [ "?transport=" transport ]
220 // scheme = "turn" / "turns"
221 // transport = "udp" / "tcp" / transport-ext
222 // transport-ext = 1*unreserved
223 // turn-host = IP-literal / IPv4address / reg-name
224 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800225 RTC_DCHECK(stun_servers != nullptr);
226 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200227 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800228 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700229 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200230 rtc::tokenize(url, '?', &tokens);
231 std::string uri_without_transport = tokens[0];
232 // Let's look into transport= param, if it exists.
233 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
234 std::string uri_transport_param = tokens[1];
235 rtc::tokenize(uri_transport_param, '=', &tokens);
236 if (tokens[0] == kTransport) {
237 // As per above grammar transport param will be consist of lower case
238 // letters.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800239 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
240 (turn_transport_type != cricket::PROTO_UDP &&
241 turn_transport_type != cricket::PROTO_TCP)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200242 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700243 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000244 }
245 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200246 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200248 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700249 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200250 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
251 &service_type,
252 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700253 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
254 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200255 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000256
deadbeef0a6c4ca2015-10-06 11:38:28 -0700257 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
258 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200259
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 // Let's break hostname.
261 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
263
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200264 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265 if (tokens.size() > kTurnHostTokensNum) {
266 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
267 return false;
268 }
269 if (tokens.size() == kTurnHostTokensNum) {
270 if (tokens[0].empty() || tokens[1].empty()) {
271 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
272 return false;
273 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200274 username.assign(rtc::s_url_decode(tokens[0]));
275 hoststring = tokens[1];
276 } else {
277 hoststring = tokens[0];
278 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000279
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200280 int port = kDefaultStunPort;
281 if (service_type == TURNS) {
282 port = kDefaultStunTlsPort;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800283 turn_transport_type = cricket::PROTO_TCP;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200284 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000285
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200286 std::string address;
287 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700288 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
289 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200290 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000291
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200292 if (port <= 0 || port > 0xffff) {
293 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700294 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200295 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000296
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 switch (service_type) {
298 case STUN:
299 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800300 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200301 break;
302 case TURN:
303 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200304 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800305 turn_servers->push_back(
306 cricket::RelayServerConfig(address, port, username, server.password,
307 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200308 break;
309 }
310 case INVALID:
311 default:
312 LOG(WARNING) << "Configuration not supported: " << url;
313 return false;
314 }
315 return true;
316}
317
deadbeefab9b2d12015-10-14 11:33:11 -0700318// Check if we can send |new_stream| on a PeerConnection.
319bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
320 webrtc::MediaStreamInterface* new_stream) {
321 if (!new_stream || !current_streams) {
322 return false;
323 }
324 if (current_streams->find(new_stream->label()) != nullptr) {
325 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
326 << " is already added.";
327 return false;
328 }
329 return true;
330}
331
332bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
333 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
334}
335
deadbeef5e97fb52015-10-15 12:49:08 -0700336// If the direction is "recvonly" or "inactive", treat the description
337// as containing no streams.
338// See: https://code.google.com/p/webrtc/issues/detail?id=5054
339std::vector<cricket::StreamParams> GetActiveStreams(
340 const cricket::MediaContentDescription* desc) {
341 return MediaContentDirectionHasSend(desc->direction())
342 ? desc->streams()
343 : std::vector<cricket::StreamParams>();
344}
345
deadbeefab9b2d12015-10-14 11:33:11 -0700346bool IsValidOfferToReceiveMedia(int value) {
347 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
348 return (value >= Options::kUndefined) &&
349 (value <= Options::kMaxOfferToReceiveMedia);
350}
351
352// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800353void AddSendStreams(
354 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700355 const std::vector<rtc::scoped_refptr<
356 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800357 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
358 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700359 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800360 for (const auto& sender : senders) {
361 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700362 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700363 }
364
365 // Check for data channels.
366 for (const auto& kv : rtp_data_channels) {
367 const DataChannel* channel = kv.second;
368 if (channel->state() == DataChannel::kConnecting ||
369 channel->state() == DataChannel::kOpen) {
370 // |streamid| and |sync_label| are both set to the DataChannel label
371 // here so they can be signaled the same way as MediaStreams and Tracks.
372 // For MediaStreams, the sync_label is the MediaStream label and the
373 // track label is the same as |streamid|.
374 const std::string& streamid = channel->label();
375 const std::string& sync_label = channel->label();
376 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
377 sync_label);
378 }
379 }
380}
381
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700382uint32_t ConvertIceTransportTypeToCandidateFilter(
383 PeerConnectionInterface::IceTransportsType type) {
384 switch (type) {
385 case PeerConnectionInterface::kNone:
386 return cricket::CF_NONE;
387 case PeerConnectionInterface::kRelay:
388 return cricket::CF_RELAY;
389 case PeerConnectionInterface::kNoHost:
390 return (cricket::CF_ALL & ~cricket::CF_HOST);
391 case PeerConnectionInterface::kAll:
392 return cricket::CF_ALL;
393 default:
394 ASSERT(false);
395 }
396 return cricket::CF_NONE;
397}
398
deadbeef0a6c4ca2015-10-06 11:38:28 -0700399} // namespace
400
401namespace webrtc {
402
zhihuang8f65cdf2016-05-06 18:40:30 -0700403// Generate a RTCP CNAME when a PeerConnection is created.
404std::string GenerateRtcpCname() {
405 std::string cname;
406 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
407 LOG(LS_ERROR) << "Failed to generate CNAME.";
408 RTC_DCHECK(false);
409 }
410 return cname;
411}
412
htaa2a49d92016-03-04 02:51:39 -0800413bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700414 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800415 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700416 cricket::MediaSessionOptions* session_options) {
417 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
418 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
419 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
420 return false;
421 }
422
htaaac2dea2016-03-10 13:35:55 -0800423 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700424 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700425 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800426 } else {
427 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700428 }
htaaac2dea2016-03-10 13:35:55 -0800429 // For offers, we only offer video if we have it or it's forced by options.
430 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700431 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700432 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800433 } else if (is_offer) {
434 session_options->recv_video = false;
435 } else {
436 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700437 }
438
439 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700440 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800441 for (auto& kv : session_options->transport_options) {
442 kv.second.ice_restart = rtc_options.ice_restart;
443 }
deadbeefab9b2d12015-10-14 11:33:11 -0700444
445 return true;
446}
447
448bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
449 cricket::MediaSessionOptions* session_options) {
450 bool value = false;
451 size_t mandatory_constraints_satisfied = 0;
452
453 // kOfferToReceiveAudio defaults to true according to spec.
454 if (!FindConstraint(constraints,
455 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
456 &mandatory_constraints_satisfied) ||
457 value) {
458 session_options->recv_audio = true;
459 }
460
461 // kOfferToReceiveVideo defaults to false according to spec. But
462 // if it is an answer and video is offered, we should still accept video
463 // per default.
464 value = false;
465 if (!FindConstraint(constraints,
466 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
467 &mandatory_constraints_satisfied) ||
468 value) {
469 session_options->recv_video = true;
470 }
471
472 if (FindConstraint(constraints,
473 MediaConstraintsInterface::kVoiceActivityDetection, &value,
474 &mandatory_constraints_satisfied)) {
475 session_options->vad_enabled = value;
476 }
477
478 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
479 &mandatory_constraints_satisfied)) {
480 session_options->bundle_enabled = value;
481 } else {
482 // kUseRtpMux defaults to true according to spec.
483 session_options->bundle_enabled = true;
484 }
deadbeefab9b2d12015-10-14 11:33:11 -0700485
deadbeef0ed85b22016-02-23 17:24:52 -0800486 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700487 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
488 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700489 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800490 ice_restart = true;
491 }
492 for (auto& kv : session_options->transport_options) {
493 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700494 }
495
496 if (!constraints) {
497 return true;
498 }
499 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
500}
501
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200502bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800503 cricket::ServerAddresses* stun_servers,
504 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200505 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
506 if (!server.urls.empty()) {
507 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200508 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700509 LOG(LS_ERROR) << "Empty uri.";
510 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200511 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800512 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200513 return false;
514 }
515 }
516 } else if (!server.uri.empty()) {
517 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800518 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000519 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200520 }
521 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700522 LOG(LS_ERROR) << "Empty uri.";
523 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000524 }
525 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800526 // Candidates must have unique priorities, so that connectivity checks
527 // are performed in a well-defined order.
528 int priority = static_cast<int>(turn_servers->size() - 1);
529 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
530 // First in the list gets highest priority.
531 turn_server.priority = priority--;
532 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533 return true;
534}
535
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000536PeerConnection::PeerConnection(PeerConnectionFactory* factory)
537 : factory_(factory),
538 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000539 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540 signaling_state_(kStable),
541 ice_state_(kIceNew),
542 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700543 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700544 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700545 local_streams_(StreamCollection::Create()),
546 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547
548PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100549 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700550 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700551 // Need to detach RTP senders/receivers from WebRtcSession,
552 // since it's about to be destroyed.
553 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700554 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700555 }
556 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700557 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700558 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700559 // Destroy stats_ because it depends on session_.
560 stats_.reset(nullptr);
561 // Now destroy session_ before destroying other members,
562 // because its destruction fires signals (such as VoiceChannelDestroyed)
563 // which will trigger some final actions in PeerConnection...
564 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700565 // port_allocator_ lives on the network thread and should be destroyed there.
566 network_thread()->Invoke<void>([this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000567}
568
569bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000570 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700571 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200572 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800573 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100574 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800575 RTC_DCHECK(observer != nullptr);
576 if (!observer) {
577 return false;
578 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000579 observer_ = observer;
580
kwiberg0eb15ed2015-12-17 03:04:15 -0800581 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800582
deadbeef91dd5672016-05-18 16:55:30 -0700583 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700584 // there.
deadbeef91dd5672016-05-18 16:55:30 -0700585 if (!network_thread()->Invoke<bool>(rtc::Bind(
586 &PeerConnection::InitializePortAllocator_n, this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587 return false;
588 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589
nissec36b31b2016-04-11 23:25:29 -0700590 media_controller_.reset(
591 factory_->CreateMediaController(configuration.media_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592
stefanc1aeaf02015-10-15 07:26:07 -0700593 session_.reset(
danilchape9021a32016-05-17 01:52:02 -0700594 new WebRtcSession(media_controller_.get(), factory_->network_thread(),
595 factory_->worker_thread(), factory_->signaling_thread(),
596 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700597 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598
599 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200600 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800601 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700603 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000604
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 // Register PeerConnection as receiver of local ice candidates.
606 // All the callbacks will be posted to the application from PeerConnection.
607 session_->RegisterIceObserver(this);
608 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700609 session_->SignalVoiceChannelDestroyed.connect(
610 this, &PeerConnection::OnVoiceChannelDestroyed);
611 session_->SignalVideoChannelDestroyed.connect(
612 this, &PeerConnection::OnVideoChannelDestroyed);
613 session_->SignalDataChannelCreated.connect(
614 this, &PeerConnection::OnDataChannelCreated);
615 session_->SignalDataChannelDestroyed.connect(
616 this, &PeerConnection::OnDataChannelDestroyed);
617 session_->SignalDataChannelOpenMessage.connect(
618 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619 return true;
620}
621
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000622rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000623PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700624 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000625}
626
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000627rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000628PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700629 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000630}
631
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000632bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100633 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000634 if (IsClosed()) {
635 return false;
636 }
deadbeefab9b2d12015-10-14 11:33:11 -0700637 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638 return false;
639 }
deadbeefab9b2d12015-10-14 11:33:11 -0700640
641 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800642 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
643 observer->SignalAudioTrackAdded.connect(this,
644 &PeerConnection::OnAudioTrackAdded);
645 observer->SignalAudioTrackRemoved.connect(
646 this, &PeerConnection::OnAudioTrackRemoved);
647 observer->SignalVideoTrackAdded.connect(this,
648 &PeerConnection::OnVideoTrackAdded);
649 observer->SignalVideoTrackRemoved.connect(
650 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700651 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700652
deadbeefab9b2d12015-10-14 11:33:11 -0700653 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800654 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700655 }
656 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800657 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700658 }
659
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000660 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000661 observer_->OnRenegotiationNeeded();
662 return true;
663}
664
665void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100666 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700667 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800668 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700669 }
670 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800671 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700672 }
673
674 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800675 stream_observers_.erase(
676 std::remove_if(
677 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700678 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800679 return observer->stream()->label().compare(local_stream->label()) ==
680 0;
681 }),
682 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700683
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 if (IsClosed()) {
685 return;
686 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000687 observer_->OnRenegotiationNeeded();
688}
689
deadbeefe1f9d832016-01-14 15:35:42 -0800690rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
691 MediaStreamTrackInterface* track,
692 std::vector<MediaStreamInterface*> streams) {
693 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
694 if (IsClosed()) {
695 return nullptr;
696 }
697 if (streams.size() >= 2) {
698 LOG(LS_ERROR)
699 << "Adding a track with two streams is not currently supported.";
700 return nullptr;
701 }
702 // TODO(deadbeef): Support adding a track to two different senders.
703 if (FindSenderForTrack(track) != senders_.end()) {
704 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
705 return nullptr;
706 }
707
708 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700709 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800710 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700711 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800712 signaling_thread(),
713 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
714 session_.get(), stats_.get()));
715 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700716 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800717 }
718 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700719 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800720 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700721 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800722 }
723 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700724 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800725 signaling_thread(),
726 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
727 session_.get()));
728 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700729 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800730 }
731 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700732 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800733 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700734 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800735 }
736 } else {
737 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
738 return rtc::scoped_refptr<RtpSenderInterface>();
739 }
740
741 senders_.push_back(new_sender);
742 observer_->OnRenegotiationNeeded();
743 return new_sender;
744}
745
746bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
747 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
748 if (IsClosed()) {
749 return false;
750 }
751
752 auto it = std::find(senders_.begin(), senders_.end(), sender);
753 if (it == senders_.end()) {
754 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
755 return false;
756 }
deadbeefa601f5c2016-06-06 14:27:39 -0700757 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800758 senders_.erase(it);
759
760 observer_->OnRenegotiationNeeded();
761 return true;
762}
763
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000764rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100766 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000767 if (!track) {
768 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
769 return NULL;
770 }
deadbeefab9b2d12015-10-14 11:33:11 -0700771 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000772 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
773 return NULL;
774 }
775
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000776 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000777 DtmfSender::Create(track, signaling_thread(), session_.get()));
778 if (!sender.get()) {
779 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
780 return NULL;
781 }
782 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
783}
784
deadbeeffac06552015-11-25 11:26:01 -0800785rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800786 const std::string& kind,
787 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100788 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeefa601f5c2016-06-06 14:27:39 -0700789 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800790 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700791 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800792 signaling_thread(), new AudioRtpSender(session_.get(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800793 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700794 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
795 signaling_thread(), new VideoRtpSender(session_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800796 } else {
797 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800798 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800799 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800800 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700801 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800802 }
deadbeeffac06552015-11-25 11:26:01 -0800803 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800804 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800805}
806
deadbeef70ab1a12015-09-28 16:53:55 -0700807std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
808 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700809 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
810 for (const auto& sender : senders_) {
811 ret.push_back(sender.get());
812 }
813 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700814}
815
816std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
817PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700818 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
819 for (const auto& receiver : receivers_) {
820 ret.push_back(receiver.get());
821 }
822 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700823}
824
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000826 MediaStreamTrackInterface* track,
827 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100828 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700829 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000830 if (!VERIFY(observer != NULL)) {
831 LOG(LS_ERROR) << "GetStats - observer is NULL.";
832 return false;
833 }
834
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000835 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000836 signaling_thread()->Post(this, MSG_GETSTATS,
837 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 return true;
839}
840
841PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
842 return signaling_state_;
843}
844
845PeerConnectionInterface::IceState PeerConnection::ice_state() {
846 return ice_state_;
847}
848
849PeerConnectionInterface::IceConnectionState
850PeerConnection::ice_connection_state() {
851 return ice_connection_state_;
852}
853
854PeerConnectionInterface::IceGatheringState
855PeerConnection::ice_gathering_state() {
856 return ice_gathering_state_;
857}
858
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000859rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860PeerConnection::CreateDataChannel(
861 const std::string& label,
862 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100863 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700864 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000865
kwibergd1fe2812016-04-27 06:47:29 -0700866 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000867 if (config) {
868 internal_config.reset(new InternalDataChannelInit(*config));
869 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000870 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700871 InternalCreateDataChannel(label, internal_config.get()));
872 if (!channel.get()) {
873 return nullptr;
874 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000876 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
877 // the first SCTP DataChannel.
878 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
879 observer_->OnRenegotiationNeeded();
880 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000881
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000882 return DataChannelProxy::Create(signaling_thread(), channel.get());
883}
884
885void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
886 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100887 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700888 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
890 return;
891 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000892 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000893
894 bool value;
895 size_t mandatory_constraints = 0;
896
897 if (FindConstraint(constraints,
898 MediaConstraintsInterface::kOfferToReceiveAudio,
899 &value,
900 &mandatory_constraints)) {
901 options.offer_to_receive_audio =
902 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
903 }
904
905 if (FindConstraint(constraints,
906 MediaConstraintsInterface::kOfferToReceiveVideo,
907 &value,
908 &mandatory_constraints)) {
909 options.offer_to_receive_video =
910 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
911 }
912
913 if (FindConstraint(constraints,
914 MediaConstraintsInterface::kVoiceActivityDetection,
915 &value,
916 &mandatory_constraints)) {
917 options.voice_activity_detection = value;
918 }
919
920 if (FindConstraint(constraints,
921 MediaConstraintsInterface::kIceRestart,
922 &value,
923 &mandatory_constraints)) {
924 options.ice_restart = value;
925 }
926
927 if (FindConstraint(constraints,
928 MediaConstraintsInterface::kUseRtpMux,
929 &value,
930 &mandatory_constraints)) {
931 options.use_rtp_mux = value;
932 }
933
934 CreateOffer(observer, options);
935}
936
937void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
938 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100939 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700940 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000941 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
942 return;
943 }
deadbeefab9b2d12015-10-14 11:33:11 -0700944
945 cricket::MediaSessionOptions session_options;
946 if (!GetOptionsForOffer(options, &session_options)) {
947 std::string error = "CreateOffer called with invalid options.";
948 LOG(LS_ERROR) << error;
949 PostCreateSessionDescriptionFailure(observer, error);
950 return;
951 }
952
953 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954}
955
956void PeerConnection::CreateAnswer(
957 CreateSessionDescriptionObserver* observer,
958 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100959 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -0700960 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
962 return;
963 }
deadbeefab9b2d12015-10-14 11:33:11 -0700964
965 cricket::MediaSessionOptions session_options;
966 if (!GetOptionsForAnswer(constraints, &session_options)) {
967 std::string error = "CreateAnswer called with invalid constraints.";
968 LOG(LS_ERROR) << error;
969 PostCreateSessionDescriptionFailure(observer, error);
970 return;
971 }
972
htaa2a49d92016-03-04 02:51:39 -0800973 session_->CreateAnswer(observer, session_options);
974}
975
976void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
977 const RTCOfferAnswerOptions& options) {
978 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
979 if (!VERIFY(observer != nullptr)) {
980 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
981 return;
982 }
983
984 cricket::MediaSessionOptions session_options;
985 if (!GetOptionsForAnswer(options, &session_options)) {
986 std::string error = "CreateAnswer called with invalid options.";
987 LOG(LS_ERROR) << error;
988 PostCreateSessionDescriptionFailure(observer, error);
989 return;
990 }
991
992 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993}
994
995void PeerConnection::SetLocalDescription(
996 SetSessionDescriptionObserver* observer,
997 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100998 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -0700999 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1001 return;
1002 }
1003 if (!desc) {
1004 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1005 return;
1006 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007 // Update stats here so that we have the most recent stats for tracks and
1008 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001009 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 std::string error;
1011 if (!session_->SetLocalDescription(desc, &error)) {
1012 PostSetSessionDescriptionFailure(observer, error);
1013 return;
1014 }
deadbeefab9b2d12015-10-14 11:33:11 -07001015
1016 // If setting the description decided our SSL role, allocate any necessary
1017 // SCTP sids.
1018 rtc::SSLRole role;
1019 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001020 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001021 AllocateSctpSids(role);
1022 }
1023
1024 // Update state and SSRC of local MediaStreams and DataChannels based on the
1025 // local session description.
1026 const cricket::ContentInfo* audio_content =
1027 GetFirstAudioContent(desc->description());
1028 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001029 if (audio_content->rejected) {
1030 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1031 } else {
1032 const cricket::AudioContentDescription* audio_desc =
1033 static_cast<const cricket::AudioContentDescription*>(
1034 audio_content->description);
1035 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1036 }
deadbeefab9b2d12015-10-14 11:33:11 -07001037 }
1038
1039 const cricket::ContentInfo* video_content =
1040 GetFirstVideoContent(desc->description());
1041 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001042 if (video_content->rejected) {
1043 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1044 } else {
1045 const cricket::VideoContentDescription* video_desc =
1046 static_cast<const cricket::VideoContentDescription*>(
1047 video_content->description);
1048 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1049 }
deadbeefab9b2d12015-10-14 11:33:11 -07001050 }
1051
1052 const cricket::ContentInfo* data_content =
1053 GetFirstDataContent(desc->description());
1054 if (data_content) {
1055 const cricket::DataContentDescription* data_desc =
1056 static_cast<const cricket::DataContentDescription*>(
1057 data_content->description);
1058 if (rtc::starts_with(data_desc->protocol().data(),
1059 cricket::kMediaProtocolRtpPrefix)) {
1060 UpdateLocalRtpDataChannels(data_desc->streams());
1061 }
1062 }
1063
1064 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001066
deadbeefcbecd352015-09-23 11:50:27 -07001067 // MaybeStartGathering needs to be called after posting
1068 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1069 // before signaling that SetLocalDescription completed.
1070 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071}
1072
1073void PeerConnection::SetRemoteDescription(
1074 SetSessionDescriptionObserver* observer,
1075 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001076 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001077 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1079 return;
1080 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 if (!desc) {
1082 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1083 return;
1084 }
1085 // Update stats here so that we have the most recent stats for tracks and
1086 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001087 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 std::string error;
1089 if (!session_->SetRemoteDescription(desc, &error)) {
1090 PostSetSessionDescriptionFailure(observer, error);
1091 return;
1092 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093
deadbeefab9b2d12015-10-14 11:33:11 -07001094 // If setting the description decided our SSL role, allocate any necessary
1095 // SCTP sids.
1096 rtc::SSLRole role;
1097 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001098 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001099 AllocateSctpSids(role);
1100 }
1101
1102 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001103 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1104 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1105 const cricket::AudioContentDescription* audio_desc =
1106 GetFirstAudioContentDescription(remote_desc);
1107 const cricket::VideoContentDescription* video_desc =
1108 GetFirstVideoContentDescription(remote_desc);
1109 const cricket::DataContentDescription* data_desc =
1110 GetFirstDataContentDescription(remote_desc);
1111
1112 // Check if the descriptions include streams, just in case the peer supports
1113 // MSID, but doesn't indicate so with "a=msid-semantic".
1114 if (remote_desc->msid_supported() ||
1115 (audio_desc && !audio_desc->streams().empty()) ||
1116 (video_desc && !video_desc->streams().empty())) {
1117 remote_peer_supports_msid_ = true;
1118 }
deadbeefab9b2d12015-10-14 11:33:11 -07001119
1120 // We wait to signal new streams until we finish processing the description,
1121 // since only at that point will new streams have all their tracks.
1122 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1123
1124 // Find all audio rtp streams and create corresponding remote AudioTracks
1125 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001126 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001127 if (audio_content->rejected) {
1128 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1129 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001130 bool default_audio_track_needed =
1131 !remote_peer_supports_msid_ &&
1132 MediaContentDirectionHasSend(audio_desc->direction());
1133 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1134 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001135 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001136 }
deadbeefab9b2d12015-10-14 11:33:11 -07001137 }
1138
1139 // Find all video rtp streams and create corresponding remote VideoTracks
1140 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001141 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001142 if (video_content->rejected) {
1143 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1144 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001145 bool default_video_track_needed =
1146 !remote_peer_supports_msid_ &&
1147 MediaContentDirectionHasSend(video_desc->direction());
1148 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1149 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001150 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001151 }
deadbeefab9b2d12015-10-14 11:33:11 -07001152 }
1153
1154 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001155 if (data_desc) {
1156 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001157 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001158 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001159 }
1160 }
1161
1162 // Iterate new_streams and notify the observer about new MediaStreams.
1163 for (size_t i = 0; i < new_streams->count(); ++i) {
1164 MediaStreamInterface* new_stream = new_streams->at(i);
1165 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001166 // Call both the raw pointer and scoped_refptr versions of the method
1167 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001168 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001169 observer_->OnAddStream(
1170 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001171 }
1172
deadbeefbda7e0b2015-12-08 17:13:40 -08001173 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001174
1175 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1176 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001177}
1178
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001179bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001180 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001181 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001182 if (!network_thread()->Invoke<bool>(
1183 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001184 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001185 return false;
1186 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001187 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001188
1189 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1190 session_->SetIceConfig(session_->ParseIceConfig(configuration));
1191 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001192}
1193
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194bool PeerConnection::AddIceCandidate(
1195 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001196 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 return session_->ProcessIceMessage(ice_candidate);
1198}
1199
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001200bool PeerConnection::RemoveIceCandidates(
1201 const std::vector<cricket::Candidate>& candidates) {
1202 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1203 return session_->RemoveRemoteIceCandidates(candidates);
1204}
1205
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001206void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001207 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001208 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001209
1210 if (session_) {
1211 session_->set_metrics_observer(uma_observer_);
1212 }
1213
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001214 // Send information about IPv4/IPv6 status.
1215 if (uma_observer_ && port_allocator_) {
1216 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001217 uma_observer_->IncrementEnumCounter(
1218 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1219 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001220 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001221 uma_observer_->IncrementEnumCounter(
1222 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1223 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001224 }
1225 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001226}
1227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228const SessionDescriptionInterface* PeerConnection::local_description() const {
1229 return session_->local_description();
1230}
1231
1232const SessionDescriptionInterface* PeerConnection::remote_description() const {
1233 return session_->remote_description();
1234}
1235
1236void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001237 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001238 // Update stats here so that we have the most recent stats for tracks and
1239 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001240 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241
deadbeefd59daf82015-10-14 15:02:44 -07001242 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243}
1244
deadbeefd59daf82015-10-14 15:02:44 -07001245void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1246 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001248 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001249 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001250 break;
deadbeefd59daf82015-10-14 15:02:44 -07001251 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001252 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1253 break;
deadbeefd59daf82015-10-14 15:02:44 -07001254 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001255 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1256 break;
deadbeefd59daf82015-10-14 15:02:44 -07001257 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1259 break;
deadbeefd59daf82015-10-14 15:02:44 -07001260 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1262 break;
deadbeefd59daf82015-10-14 15:02:44 -07001263 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264 ChangeSignalingState(PeerConnectionInterface::kStable);
1265 break;
deadbeefd59daf82015-10-14 15:02:44 -07001266 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 ChangeSignalingState(PeerConnectionInterface::kClosed);
1268 break;
1269 default:
1270 break;
1271 }
1272}
1273
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001274void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001275 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1277 SetSessionDescriptionMsg* param =
1278 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1279 param->observer->OnSuccess();
1280 delete param;
1281 break;
1282 }
1283 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1284 SetSessionDescriptionMsg* param =
1285 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1286 param->observer->OnFailure(param->error);
1287 delete param;
1288 break;
1289 }
deadbeefab9b2d12015-10-14 11:33:11 -07001290 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1291 CreateSessionDescriptionMsg* param =
1292 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1293 param->observer->OnFailure(param->error);
1294 delete param;
1295 break;
1296 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 case MSG_GETSTATS: {
1298 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001299 StatsReports reports;
1300 stats_->GetStats(param->track, &reports);
1301 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 delete param;
1303 break;
1304 }
deadbeefbd292462015-12-14 18:15:29 -08001305 case MSG_FREE_DATACHANNELS: {
1306 sctp_data_channels_to_free_.clear();
1307 break;
1308 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001310 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 break;
1312 }
1313}
1314
deadbeefab9b2d12015-10-14 11:33:11 -07001315void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001316 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001317 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001318 receivers_.push_back(
1319 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1320 signaling_thread(),
1321 new AudioRtpReceiver(stream, track_id, ssrc, session_.get())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322}
1323
deadbeefab9b2d12015-10-14 11:33:11 -07001324void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001325 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001326 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001327 receivers_.push_back(
1328 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1329 signaling_thread(),
1330 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
1331 ssrc, session_.get())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332}
1333
deadbeef70ab1a12015-09-28 16:53:55 -07001334// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1335// description.
perkjd61bf802016-03-24 03:16:19 -07001336void PeerConnection::DestroyReceiver(const std::string& track_id) {
1337 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001338 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001339 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001340 << " doesn't exist.";
1341 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001342 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001343 receivers_.erase(it);
1344 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345}
1346
perkjd61bf802016-03-24 03:16:19 -07001347void PeerConnection::StopReceivers(cricket::MediaType media_type) {
1348 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1349 for (const auto& track_info : *current_tracks) {
1350 auto it = FindReceiverForTrack(track_info.track_id);
1351 if (it == receivers_.end()) {
1352 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_info.track_id
1353 << " doesn't exist.";
1354 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001355 (*it)->internal()->Stop();
perkjd61bf802016-03-24 03:16:19 -07001356 }
deadbeef70ab1a12015-09-28 16:53:55 -07001357 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358}
deadbeef70ab1a12015-09-28 16:53:55 -07001359
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360void PeerConnection::OnIceConnectionChange(
1361 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001362 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001363 // After transitioning to "closed", ignore any additional states from
1364 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001365 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001366 return;
1367 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001369 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
1372void PeerConnection::OnIceGatheringChange(
1373 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001374 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 if (IsClosed()) {
1376 return;
1377 }
1378 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001379 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380}
1381
1382void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001383 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001384 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385}
1386
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001387void PeerConnection::OnIceCandidatesRemoved(
1388 const std::vector<cricket::Candidate>& candidates) {
1389 RTC_DCHECK(signaling_thread()->IsCurrent());
1390 observer_->OnIceCandidatesRemoved(candidates);
1391}
1392
Peter Thatcher54360512015-07-08 11:08:35 -07001393void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001394 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001395 observer_->OnIceConnectionReceivingChange(receiving);
1396}
1397
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398void PeerConnection::ChangeSignalingState(
1399 PeerConnectionInterface::SignalingState signaling_state) {
1400 signaling_state_ = signaling_state;
1401 if (signaling_state == kClosed) {
1402 ice_connection_state_ = kIceConnectionClosed;
1403 observer_->OnIceConnectionChange(ice_connection_state_);
1404 if (ice_gathering_state_ != kIceGatheringComplete) {
1405 ice_gathering_state_ = kIceGatheringComplete;
1406 observer_->OnIceGatheringChange(ice_gathering_state_);
1407 }
1408 }
1409 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410}
1411
deadbeefeb459812015-12-15 19:24:43 -08001412void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1413 MediaStreamInterface* stream) {
1414 auto sender = FindSenderForTrack(track);
1415 if (sender != senders_.end()) {
1416 // We already have a sender for this track, so just change the stream_id
1417 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001418 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001419 return;
1420 }
1421
1422 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001423 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1424 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1425 signaling_thread(), new AudioRtpSender(track, stream->label(),
1426 session_.get(), stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001427 senders_.push_back(new_sender);
1428 // If the sender has already been configured in SDP, we call SetSsrc,
1429 // which will connect the sender to the underlying transport. This can
1430 // occur if a local session description that contains the ID of the sender
1431 // is set before AddStream is called. It can also occur if the local
1432 // session description is not changed and RemoveStream is called, and
1433 // later AddStream is called again with the same stream.
1434 const TrackInfo* track_info =
1435 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1436 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001437 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001438 }
1439}
1440
1441// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1442// indefinitely, when we have unified plan SDP.
1443void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1444 MediaStreamInterface* stream) {
1445 auto sender = FindSenderForTrack(track);
1446 if (sender == senders_.end()) {
1447 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1448 << " doesn't exist.";
1449 return;
1450 }
deadbeefa601f5c2016-06-06 14:27:39 -07001451 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001452 senders_.erase(sender);
1453}
1454
1455void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1456 MediaStreamInterface* stream) {
1457 auto sender = FindSenderForTrack(track);
1458 if (sender != senders_.end()) {
1459 // We already have a sender for this track, so just change the stream_id
1460 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001461 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001462 return;
1463 }
1464
1465 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001466 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1467 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1468 signaling_thread(),
1469 new VideoRtpSender(track, stream->label(), session_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001470 senders_.push_back(new_sender);
1471 const TrackInfo* track_info =
1472 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1473 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001474 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001475 }
1476}
1477
1478void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1479 MediaStreamInterface* stream) {
1480 auto sender = FindSenderForTrack(track);
1481 if (sender == senders_.end()) {
1482 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1483 << " doesn't exist.";
1484 return;
1485 }
deadbeefa601f5c2016-06-06 14:27:39 -07001486 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001487 senders_.erase(sender);
1488}
1489
deadbeefab9b2d12015-10-14 11:33:11 -07001490void PeerConnection::PostSetSessionDescriptionFailure(
1491 SetSessionDescriptionObserver* observer,
1492 const std::string& error) {
1493 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1494 msg->error = error;
1495 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1496}
1497
1498void PeerConnection::PostCreateSessionDescriptionFailure(
1499 CreateSessionDescriptionObserver* observer,
1500 const std::string& error) {
1501 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1502 msg->error = error;
1503 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1504}
1505
1506bool PeerConnection::GetOptionsForOffer(
1507 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1508 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001509 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1510 // ContentInfos.
1511 if (session_->local_description()) {
1512 for (const cricket::ContentInfo& content :
1513 session_->local_description()->description()->contents()) {
1514 session_options->transport_options[content.name] =
1515 cricket::TransportOptions();
1516 }
1517 }
htaaac2dea2016-03-10 13:35:55 -08001518 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001519 return false;
1520 }
1521
deadbeeffac06552015-11-25 11:26:01 -08001522 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001523 // Offer to receive audio/video if the constraint is not set and there are
1524 // send streams, or we're currently receiving.
1525 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1526 session_options->recv_audio =
1527 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1528 !remote_audio_tracks_.empty();
1529 }
1530 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1531 session_options->recv_video =
1532 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1533 !remote_video_tracks_.empty();
1534 }
1535 session_options->bundle_enabled =
1536 session_options->bundle_enabled &&
1537 (session_options->has_audio() || session_options->has_video() ||
1538 session_options->has_data());
1539
deadbeefab9b2d12015-10-14 11:33:11 -07001540 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1541 session_options->data_channel_type = cricket::DCT_SCTP;
1542 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001543
1544 session_options->rtcp_cname = rtcp_cname_;
deadbeefab9b2d12015-10-14 11:33:11 -07001545 return true;
1546}
1547
htaa2a49d92016-03-04 02:51:39 -08001548void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001549 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001550 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1551 // ContentInfos.
1552 if (session_->remote_description()) {
1553 // Initialize the transport_options map.
1554 for (const cricket::ContentInfo& content :
1555 session_->remote_description()->description()->contents()) {
1556 session_options->transport_options[content.name] =
1557 cricket::TransportOptions();
1558 }
1559 }
deadbeeffac06552015-11-25 11:26:01 -08001560 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001561 session_options->bundle_enabled =
1562 session_options->bundle_enabled &&
1563 (session_options->has_audio() || session_options->has_video() ||
1564 session_options->has_data());
1565
deadbeefab9b2d12015-10-14 11:33:11 -07001566 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1567 // are not signaled in the SDP so does not go through that path and must be
1568 // handled here.
1569 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1570 session_options->data_channel_type = cricket::DCT_SCTP;
1571 }
htaa2a49d92016-03-04 02:51:39 -08001572}
1573
1574bool PeerConnection::GetOptionsForAnswer(
1575 const MediaConstraintsInterface* constraints,
1576 cricket::MediaSessionOptions* session_options) {
1577 session_options->recv_audio = false;
1578 session_options->recv_video = false;
1579 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1580 return false;
1581 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001582 session_options->rtcp_cname = rtcp_cname_;
1583
htaa2a49d92016-03-04 02:51:39 -08001584 FinishOptionsForAnswer(session_options);
1585 return true;
1586}
1587
1588bool PeerConnection::GetOptionsForAnswer(
1589 const RTCOfferAnswerOptions& options,
1590 cricket::MediaSessionOptions* session_options) {
1591 session_options->recv_audio = false;
1592 session_options->recv_video = false;
htaaac2dea2016-03-10 13:35:55 -08001593 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001594 return false;
1595 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001596 session_options->rtcp_cname = rtcp_cname_;
1597
htaa2a49d92016-03-04 02:51:39 -08001598 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001599 return true;
1600}
1601
deadbeeffaac4972015-11-12 15:33:07 -08001602void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1603 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001604 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1605 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001606}
1607
deadbeefab9b2d12015-10-14 11:33:11 -07001608void PeerConnection::UpdateRemoteStreamsList(
1609 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001610 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001611 cricket::MediaType media_type,
1612 StreamCollection* new_streams) {
1613 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1614
1615 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001616 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001617 auto track_it = current_tracks->begin();
1618 while (track_it != current_tracks->end()) {
1619 const TrackInfo& info = *track_it;
1620 const cricket::StreamParams* params =
1621 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001622 bool track_exists = params && params->id == info.track_id;
1623 // If this is a default track, and we still need it, don't remove it.
1624 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1625 track_exists) {
1626 ++track_it;
1627 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001628 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1629 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001630 }
1631 }
1632
1633 // Find new and active tracks.
1634 for (const cricket::StreamParams& params : streams) {
1635 // The sync_label is the MediaStream label and the |stream.id| is the
1636 // track id.
1637 const std::string& stream_label = params.sync_label;
1638 const std::string& track_id = params.id;
1639 uint32_t ssrc = params.first_ssrc();
1640
1641 rtc::scoped_refptr<MediaStreamInterface> stream =
1642 remote_streams_->find(stream_label);
1643 if (!stream) {
1644 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001645 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1646 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001647 remote_streams_->AddStream(stream);
1648 new_streams->AddStream(stream);
1649 }
1650
1651 const TrackInfo* track_info =
1652 FindTrackInfo(*current_tracks, stream_label, track_id);
1653 if (!track_info) {
1654 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1655 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1656 }
1657 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001658
1659 // Add default track if necessary.
1660 if (default_track_needed) {
1661 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1662 remote_streams_->find(kDefaultStreamLabel);
1663 if (!default_stream) {
1664 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001665 default_stream = MediaStreamProxy::Create(
1666 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001667 remote_streams_->AddStream(default_stream);
1668 new_streams->AddStream(default_stream);
1669 }
1670 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1671 ? kDefaultAudioTrackLabel
1672 : kDefaultVideoTrackLabel;
1673 const TrackInfo* default_track_info =
1674 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1675 if (!default_track_info) {
1676 current_tracks->push_back(
1677 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1678 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1679 }
1680 }
deadbeefab9b2d12015-10-14 11:33:11 -07001681}
1682
1683void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1684 const std::string& track_id,
1685 uint32_t ssrc,
1686 cricket::MediaType media_type) {
1687 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1688
1689 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001690 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001691 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001692 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001693 } else {
1694 RTC_DCHECK(false && "Invalid media type");
1695 }
1696}
1697
1698void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1699 const std::string& track_id,
1700 cricket::MediaType media_type) {
1701 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1702
1703 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001704 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1705 // will be notified which will end the AudioRtpReceiver::track().
1706 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001707 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1708 stream->FindAudioTrack(track_id);
1709 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001710 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001711 }
1712 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001713 // Stopping or destroying a VideoRtpReceiver will end the
1714 // VideoRtpReceiver::track().
1715 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001716 rtc::scoped_refptr<VideoTrackInterface> video_track =
1717 stream->FindVideoTrack(track_id);
1718 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001719 // There's no guarantee the track is still available, e.g. the track may
1720 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001721 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001722 }
1723 } else {
1724 ASSERT(false && "Invalid media type");
1725 }
1726}
1727
1728void PeerConnection::UpdateEndedRemoteMediaStreams() {
1729 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1730 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1731 MediaStreamInterface* stream = remote_streams_->at(i);
1732 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1733 streams_to_remove.push_back(stream);
1734 }
1735 }
1736
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001737 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001738 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001739 // Call both the raw pointer and scoped_refptr versions of the method
1740 // for compatibility.
1741 observer_->OnRemoveStream(stream.get());
1742 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001743 }
1744}
1745
deadbeefab9b2d12015-10-14 11:33:11 -07001746void PeerConnection::UpdateLocalTracks(
1747 const std::vector<cricket::StreamParams>& streams,
1748 cricket::MediaType media_type) {
1749 TrackInfos* current_tracks = GetLocalTracks(media_type);
1750
1751 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1752 // don't match the new StreamParam.
1753 TrackInfos::iterator track_it = current_tracks->begin();
1754 while (track_it != current_tracks->end()) {
1755 const TrackInfo& info = *track_it;
1756 const cricket::StreamParams* params =
1757 cricket::GetStreamBySsrc(streams, info.ssrc);
1758 if (!params || params->id != info.track_id ||
1759 params->sync_label != info.stream_label) {
1760 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1761 media_type);
1762 track_it = current_tracks->erase(track_it);
1763 } else {
1764 ++track_it;
1765 }
1766 }
1767
1768 // Find new and active tracks.
1769 for (const cricket::StreamParams& params : streams) {
1770 // The sync_label is the MediaStream label and the |stream.id| is the
1771 // track id.
1772 const std::string& stream_label = params.sync_label;
1773 const std::string& track_id = params.id;
1774 uint32_t ssrc = params.first_ssrc();
1775 const TrackInfo* track_info =
1776 FindTrackInfo(*current_tracks, stream_label, track_id);
1777 if (!track_info) {
1778 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1779 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1780 }
1781 }
1782}
1783
1784void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1785 const std::string& track_id,
1786 uint32_t ssrc,
1787 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001788 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001789 if (!sender) {
1790 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1791 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001792 return;
1793 }
1794
deadbeeffac06552015-11-25 11:26:01 -08001795 if (sender->media_type() != media_type) {
1796 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1797 << " description with an unexpected media type.";
1798 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001799 }
deadbeeffac06552015-11-25 11:26:01 -08001800
1801 sender->set_stream_id(stream_label);
1802 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001803}
1804
1805void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1806 const std::string& track_id,
1807 uint32_t ssrc,
1808 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001809 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001810 if (!sender) {
1811 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001812 // SessionDescriptions has been renegotiated.
1813 return;
1814 }
deadbeeffac06552015-11-25 11:26:01 -08001815
1816 // A sender has been removed from the SessionDescription but it's still
1817 // associated with the PeerConnection. This only occurs if the SDP doesn't
1818 // match with the calls to CreateSender, AddStream and RemoveStream.
1819 if (sender->media_type() != media_type) {
1820 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1821 << " description with an unexpected media type.";
1822 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001823 }
deadbeeffac06552015-11-25 11:26:01 -08001824
1825 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001826}
1827
1828void PeerConnection::UpdateLocalRtpDataChannels(
1829 const cricket::StreamParamsVec& streams) {
1830 std::vector<std::string> existing_channels;
1831
1832 // Find new and active data channels.
1833 for (const cricket::StreamParams& params : streams) {
1834 // |it->sync_label| is actually the data channel label. The reason is that
1835 // we use the same naming of data channels as we do for
1836 // MediaStreams and Tracks.
1837 // For MediaStreams, the sync_label is the MediaStream label and the
1838 // track label is the same as |streamid|.
1839 const std::string& channel_label = params.sync_label;
1840 auto data_channel_it = rtp_data_channels_.find(channel_label);
1841 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1842 continue;
1843 }
1844 // Set the SSRC the data channel should use for sending.
1845 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1846 existing_channels.push_back(data_channel_it->first);
1847 }
1848
1849 UpdateClosingRtpDataChannels(existing_channels, true);
1850}
1851
1852void PeerConnection::UpdateRemoteRtpDataChannels(
1853 const cricket::StreamParamsVec& streams) {
1854 std::vector<std::string> existing_channels;
1855
1856 // Find new and active data channels.
1857 for (const cricket::StreamParams& params : streams) {
1858 // The data channel label is either the mslabel or the SSRC if the mslabel
1859 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1860 std::string label = params.sync_label.empty()
1861 ? rtc::ToString(params.first_ssrc())
1862 : params.sync_label;
1863 auto data_channel_it = rtp_data_channels_.find(label);
1864 if (data_channel_it == rtp_data_channels_.end()) {
1865 // This is a new data channel.
1866 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1867 } else {
1868 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1869 }
1870 existing_channels.push_back(label);
1871 }
1872
1873 UpdateClosingRtpDataChannels(existing_channels, false);
1874}
1875
1876void PeerConnection::UpdateClosingRtpDataChannels(
1877 const std::vector<std::string>& active_channels,
1878 bool is_local_update) {
1879 auto it = rtp_data_channels_.begin();
1880 while (it != rtp_data_channels_.end()) {
1881 DataChannel* data_channel = it->second;
1882 if (std::find(active_channels.begin(), active_channels.end(),
1883 data_channel->label()) != active_channels.end()) {
1884 ++it;
1885 continue;
1886 }
1887
1888 if (is_local_update) {
1889 data_channel->SetSendSsrc(0);
1890 } else {
1891 data_channel->RemotePeerRequestClose();
1892 }
1893
1894 if (data_channel->state() == DataChannel::kClosed) {
1895 rtp_data_channels_.erase(it);
1896 it = rtp_data_channels_.begin();
1897 } else {
1898 ++it;
1899 }
1900 }
1901}
1902
1903void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1904 uint32_t remote_ssrc) {
1905 rtc::scoped_refptr<DataChannel> channel(
1906 InternalCreateDataChannel(label, nullptr));
1907 if (!channel.get()) {
1908 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1909 << "CreateDataChannel failed.";
1910 return;
1911 }
1912 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07001913 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
1914 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001915 // Call both the raw pointer and scoped_refptr versions of the method
1916 // for compatibility.
1917 observer_->OnDataChannel(proxy_channel.get());
1918 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07001919}
1920
1921rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1922 const std::string& label,
1923 const InternalDataChannelInit* config) {
1924 if (IsClosed()) {
1925 return nullptr;
1926 }
1927 if (session_->data_channel_type() == cricket::DCT_NONE) {
1928 LOG(LS_ERROR)
1929 << "InternalCreateDataChannel: Data is not supported in this call.";
1930 return nullptr;
1931 }
1932 InternalDataChannelInit new_config =
1933 config ? (*config) : InternalDataChannelInit();
1934 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1935 if (new_config.id < 0) {
1936 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001937 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07001938 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1939 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1940 return nullptr;
1941 }
1942 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1943 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1944 << "because the id is already in use or out of range.";
1945 return nullptr;
1946 }
1947 }
1948
1949 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1950 session_.get(), session_->data_channel_type(), label, new_config));
1951 if (!channel) {
1952 sid_allocator_.ReleaseSid(new_config.id);
1953 return nullptr;
1954 }
1955
1956 if (channel->data_channel_type() == cricket::DCT_RTP) {
1957 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1958 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1959 << " already exists.";
1960 return nullptr;
1961 }
1962 rtp_data_channels_[channel->label()] = channel;
1963 } else {
1964 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1965 sctp_data_channels_.push_back(channel);
1966 channel->SignalClosed.connect(this,
1967 &PeerConnection::OnSctpDataChannelClosed);
1968 }
1969
1970 return channel;
1971}
1972
1973bool PeerConnection::HasDataChannels() const {
1974 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1975}
1976
1977void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1978 for (const auto& channel : sctp_data_channels_) {
1979 if (channel->id() < 0) {
1980 int sid;
1981 if (!sid_allocator_.AllocateSid(role, &sid)) {
1982 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1983 continue;
1984 }
1985 channel->SetSctpSid(sid);
1986 }
1987 }
1988}
1989
1990void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08001991 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07001992 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1993 ++it) {
1994 if (it->get() == channel) {
1995 if (channel->id() >= 0) {
1996 sid_allocator_.ReleaseSid(channel->id());
1997 }
deadbeefbd292462015-12-14 18:15:29 -08001998 // Since this method is triggered by a signal from the DataChannel,
1999 // we can't free it directly here; we need to free it asynchronously.
2000 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002001 sctp_data_channels_.erase(it);
deadbeefbd292462015-12-14 18:15:29 -08002002 signaling_thread()->Post(this, MSG_FREE_DATACHANNELS, nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002003 return;
2004 }
2005 }
2006}
2007
2008void PeerConnection::OnVoiceChannelDestroyed() {
perkjd61bf802016-03-24 03:16:19 -07002009 StopReceivers(cricket::MEDIA_TYPE_AUDIO);
deadbeefab9b2d12015-10-14 11:33:11 -07002010}
2011
2012void PeerConnection::OnVideoChannelDestroyed() {
perkjd61bf802016-03-24 03:16:19 -07002013 StopReceivers(cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002014}
2015
2016void PeerConnection::OnDataChannelCreated() {
2017 for (const auto& channel : sctp_data_channels_) {
2018 channel->OnTransportChannelCreated();
2019 }
2020}
2021
2022void PeerConnection::OnDataChannelDestroyed() {
2023 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2024 // DataChannel may callback to us and try to modify the list.
2025 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2026 temp_rtp_dcs.swap(rtp_data_channels_);
2027 for (const auto& kv : temp_rtp_dcs) {
2028 kv.second->OnTransportChannelDestroyed();
2029 }
2030
2031 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2032 temp_sctp_dcs.swap(sctp_data_channels_);
2033 for (const auto& channel : temp_sctp_dcs) {
2034 channel->OnTransportChannelDestroyed();
2035 }
2036}
2037
2038void PeerConnection::OnDataChannelOpenMessage(
2039 const std::string& label,
2040 const InternalDataChannelInit& config) {
2041 rtc::scoped_refptr<DataChannel> channel(
2042 InternalCreateDataChannel(label, &config));
2043 if (!channel.get()) {
2044 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2045 return;
2046 }
2047
deadbeefa601f5c2016-06-06 14:27:39 -07002048 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2049 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002050 // Call both the raw pointer and scoped_refptr versions of the method
2051 // for compatibility.
2052 observer_->OnDataChannel(proxy_channel.get());
2053 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002054}
2055
deadbeefa601f5c2016-06-06 14:27:39 -07002056RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2057 auto it = std::find_if(
2058 senders_.begin(), senders_.end(),
2059 [id](const rtc::scoped_refptr<
2060 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2061 return sender->id() == id;
2062 });
2063 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002064}
2065
deadbeefa601f5c2016-06-06 14:27:39 -07002066std::vector<
2067 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002068PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2069 return std::find_if(
2070 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002071 [track](const rtc::scoped_refptr<
2072 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002073 return sender->track() == track;
2074 });
2075}
2076
deadbeefa601f5c2016-06-06 14:27:39 -07002077std::vector<rtc::scoped_refptr<
2078 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002079PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002080 return std::find_if(
2081 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002082 [track_id](const rtc::scoped_refptr<
2083 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002084 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002085 });
2086}
2087
deadbeefab9b2d12015-10-14 11:33:11 -07002088PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2089 cricket::MediaType media_type) {
2090 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2091 media_type == cricket::MEDIA_TYPE_VIDEO);
2092 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2093 : &remote_video_tracks_;
2094}
2095
2096PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2097 cricket::MediaType media_type) {
2098 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2099 media_type == cricket::MEDIA_TYPE_VIDEO);
2100 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2101 : &local_video_tracks_;
2102}
2103
2104const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2105 const PeerConnection::TrackInfos& infos,
2106 const std::string& stream_label,
2107 const std::string track_id) const {
2108 for (const TrackInfo& track_info : infos) {
2109 if (track_info.stream_label == stream_label &&
2110 track_info.track_id == track_id) {
2111 return &track_info;
2112 }
2113 }
2114 return nullptr;
2115}
2116
2117DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2118 for (const auto& channel : sctp_data_channels_) {
2119 if (channel->id() == sid) {
2120 return channel;
2121 }
2122 }
2123 return nullptr;
2124}
2125
deadbeef91dd5672016-05-18 16:55:30 -07002126bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002127 const RTCConfiguration& configuration) {
2128 cricket::ServerAddresses stun_servers;
2129 std::vector<cricket::RelayServerConfig> turn_servers;
2130 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2131 return false;
2132 }
2133
2134 // To handle both internal and externally created port allocator, we will
2135 // enable BUNDLE here.
2136 int portallocator_flags = port_allocator_->flags();
2137 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2138 cricket::PORTALLOCATOR_ENABLE_IPV6;
2139 // If the disable-IPv6 flag was specified, we'll not override it
2140 // by experiment.
2141 if (configuration.disable_ipv6) {
2142 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2143 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2144 "Disabled") {
2145 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2146 }
2147
2148 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2149 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2150 LOG(LS_INFO) << "TCP candidates are disabled.";
2151 }
2152
honghaiz60347052016-05-31 18:29:12 -07002153 if (configuration.candidate_network_policy ==
2154 kCandidateNetworkPolicyLowCost) {
2155 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2156 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2157 }
2158
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002159 port_allocator_->set_flags(portallocator_flags);
2160 // No step delay is used while allocating ports.
2161 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2162 port_allocator_->set_candidate_filter(
2163 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2164
2165 // Call this last since it may create pooled allocator sessions using the
2166 // properties set above.
2167 port_allocator_->SetConfiguration(stun_servers, turn_servers,
2168 configuration.ice_candidate_pool_size);
2169 return true;
2170}
2171
deadbeef91dd5672016-05-18 16:55:30 -07002172bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002173 const RTCConfiguration& configuration) {
2174 cricket::ServerAddresses stun_servers;
2175 std::vector<cricket::RelayServerConfig> turn_servers;
2176 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2177 return false;
2178 }
2179 port_allocator_->set_candidate_filter(
2180 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2181 // Call this last since it may create pooled allocator sessions using the
2182 // candidate filter set above.
2183 port_allocator_->SetConfiguration(stun_servers, turn_servers,
2184 configuration.ice_candidate_pool_size);
2185 return true;
2186}
2187
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188} // namespace webrtc