blob: b9cb83e724de78db6683bd0dc242afb6d80a928a [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.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700566 network_thread()->Invoke<void>(RTC_FROM_HERE,
567 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568}
569
570bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000571 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700572 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200573 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800574 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100575 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800576 RTC_DCHECK(observer != nullptr);
577 if (!observer) {
578 return false;
579 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000580 observer_ = observer;
581
kwiberg0eb15ed2015-12-17 03:04:15 -0800582 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800583
deadbeef91dd5672016-05-18 16:55:30 -0700584 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700585 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700586 if (!network_thread()->Invoke<bool>(
587 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
588 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 return false;
590 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591
nissec36b31b2016-04-11 23:25:29 -0700592 media_controller_.reset(
593 factory_->CreateMediaController(configuration.media_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000594
stefanc1aeaf02015-10-15 07:26:07 -0700595 session_.reset(
danilchape9021a32016-05-17 01:52:02 -0700596 new WebRtcSession(media_controller_.get(), factory_->network_thread(),
597 factory_->worker_thread(), factory_->signaling_thread(),
598 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700599 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000600
601 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200602 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800603 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000604 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700605 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000606
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 // Register PeerConnection as receiver of local ice candidates.
608 // All the callbacks will be posted to the application from PeerConnection.
609 session_->RegisterIceObserver(this);
610 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700611 session_->SignalVoiceChannelDestroyed.connect(
612 this, &PeerConnection::OnVoiceChannelDestroyed);
613 session_->SignalVideoChannelDestroyed.connect(
614 this, &PeerConnection::OnVideoChannelDestroyed);
615 session_->SignalDataChannelCreated.connect(
616 this, &PeerConnection::OnDataChannelCreated);
617 session_->SignalDataChannelDestroyed.connect(
618 this, &PeerConnection::OnDataChannelDestroyed);
619 session_->SignalDataChannelOpenMessage.connect(
620 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621 return true;
622}
623
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000624rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000625PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700626 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000627}
628
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000629rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000630PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700631 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000632}
633
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000634bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100635 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636 if (IsClosed()) {
637 return false;
638 }
deadbeefab9b2d12015-10-14 11:33:11 -0700639 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 return false;
641 }
deadbeefab9b2d12015-10-14 11:33:11 -0700642
643 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800644 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
645 observer->SignalAudioTrackAdded.connect(this,
646 &PeerConnection::OnAudioTrackAdded);
647 observer->SignalAudioTrackRemoved.connect(
648 this, &PeerConnection::OnAudioTrackRemoved);
649 observer->SignalVideoTrackAdded.connect(this,
650 &PeerConnection::OnVideoTrackAdded);
651 observer->SignalVideoTrackRemoved.connect(
652 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700653 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700654
deadbeefab9b2d12015-10-14 11:33:11 -0700655 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800656 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700657 }
658 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800659 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700660 }
661
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000662 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663 observer_->OnRenegotiationNeeded();
664 return true;
665}
666
667void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100668 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700669 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800670 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700671 }
672 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800673 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700674 }
675
676 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800677 stream_observers_.erase(
678 std::remove_if(
679 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700680 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800681 return observer->stream()->label().compare(local_stream->label()) ==
682 0;
683 }),
684 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700685
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000686 if (IsClosed()) {
687 return;
688 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 observer_->OnRenegotiationNeeded();
690}
691
deadbeefe1f9d832016-01-14 15:35:42 -0800692rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
693 MediaStreamTrackInterface* track,
694 std::vector<MediaStreamInterface*> streams) {
695 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
696 if (IsClosed()) {
697 return nullptr;
698 }
699 if (streams.size() >= 2) {
700 LOG(LS_ERROR)
701 << "Adding a track with two streams is not currently supported.";
702 return nullptr;
703 }
704 // TODO(deadbeef): Support adding a track to two different senders.
705 if (FindSenderForTrack(track) != senders_.end()) {
706 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
707 return nullptr;
708 }
709
710 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700711 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800712 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700713 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800714 signaling_thread(),
715 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
716 session_.get(), stats_.get()));
717 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700718 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800719 }
720 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700721 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800722 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700723 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800724 }
725 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700726 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800727 signaling_thread(),
728 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
729 session_.get()));
730 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700731 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800732 }
733 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700734 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800735 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700736 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800737 }
738 } else {
739 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
740 return rtc::scoped_refptr<RtpSenderInterface>();
741 }
742
743 senders_.push_back(new_sender);
744 observer_->OnRenegotiationNeeded();
745 return new_sender;
746}
747
748bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
749 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
750 if (IsClosed()) {
751 return false;
752 }
753
754 auto it = std::find(senders_.begin(), senders_.end(), sender);
755 if (it == senders_.end()) {
756 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
757 return false;
758 }
deadbeefa601f5c2016-06-06 14:27:39 -0700759 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800760 senders_.erase(it);
761
762 observer_->OnRenegotiationNeeded();
763 return true;
764}
765
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000766rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000767 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100768 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769 if (!track) {
770 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
771 return NULL;
772 }
deadbeefab9b2d12015-10-14 11:33:11 -0700773 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000774 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
775 return NULL;
776 }
777
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000778 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779 DtmfSender::Create(track, signaling_thread(), session_.get()));
780 if (!sender.get()) {
781 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
782 return NULL;
783 }
784 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
785}
786
deadbeeffac06552015-11-25 11:26:01 -0800787rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800788 const std::string& kind,
789 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100790 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeefa601f5c2016-06-06 14:27:39 -0700791 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800792 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700793 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800794 signaling_thread(), new AudioRtpSender(session_.get(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800795 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700796 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
797 signaling_thread(), new VideoRtpSender(session_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800798 } else {
799 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800800 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800801 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800802 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700803 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800804 }
deadbeeffac06552015-11-25 11:26:01 -0800805 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800806 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800807}
808
deadbeef70ab1a12015-09-28 16:53:55 -0700809std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
810 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700811 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
812 for (const auto& sender : senders_) {
813 ret.push_back(sender.get());
814 }
815 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700816}
817
818std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
819PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700820 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
821 for (const auto& receiver : receivers_) {
822 ret.push_back(receiver.get());
823 }
824 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700825}
826
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000828 MediaStreamTrackInterface* track,
829 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700831 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 if (!VERIFY(observer != NULL)) {
833 LOG(LS_ERROR) << "GetStats - observer is NULL.";
834 return false;
835 }
836
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000837 stats_->UpdateStats(level);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700838 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000839 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 return true;
841}
842
843PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
844 return signaling_state_;
845}
846
847PeerConnectionInterface::IceState PeerConnection::ice_state() {
848 return ice_state_;
849}
850
851PeerConnectionInterface::IceConnectionState
852PeerConnection::ice_connection_state() {
853 return ice_connection_state_;
854}
855
856PeerConnectionInterface::IceGatheringState
857PeerConnection::ice_gathering_state() {
858 return ice_gathering_state_;
859}
860
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000861rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862PeerConnection::CreateDataChannel(
863 const std::string& label,
864 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100865 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700866 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000867
kwibergd1fe2812016-04-27 06:47:29 -0700868 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000869 if (config) {
870 internal_config.reset(new InternalDataChannelInit(*config));
871 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000872 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700873 InternalCreateDataChannel(label, internal_config.get()));
874 if (!channel.get()) {
875 return nullptr;
876 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000878 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
879 // the first SCTP DataChannel.
880 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
881 observer_->OnRenegotiationNeeded();
882 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000883
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884 return DataChannelProxy::Create(signaling_thread(), channel.get());
885}
886
887void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
888 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100889 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700890 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
892 return;
893 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000894 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000895
896 bool value;
897 size_t mandatory_constraints = 0;
898
899 if (FindConstraint(constraints,
900 MediaConstraintsInterface::kOfferToReceiveAudio,
901 &value,
902 &mandatory_constraints)) {
903 options.offer_to_receive_audio =
904 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
905 }
906
907 if (FindConstraint(constraints,
908 MediaConstraintsInterface::kOfferToReceiveVideo,
909 &value,
910 &mandatory_constraints)) {
911 options.offer_to_receive_video =
912 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
913 }
914
915 if (FindConstraint(constraints,
916 MediaConstraintsInterface::kVoiceActivityDetection,
917 &value,
918 &mandatory_constraints)) {
919 options.voice_activity_detection = value;
920 }
921
922 if (FindConstraint(constraints,
923 MediaConstraintsInterface::kIceRestart,
924 &value,
925 &mandatory_constraints)) {
926 options.ice_restart = value;
927 }
928
929 if (FindConstraint(constraints,
930 MediaConstraintsInterface::kUseRtpMux,
931 &value,
932 &mandatory_constraints)) {
933 options.use_rtp_mux = value;
934 }
935
936 CreateOffer(observer, options);
937}
938
939void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
940 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100941 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700942 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000943 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
944 return;
945 }
deadbeefab9b2d12015-10-14 11:33:11 -0700946
947 cricket::MediaSessionOptions session_options;
948 if (!GetOptionsForOffer(options, &session_options)) {
949 std::string error = "CreateOffer called with invalid options.";
950 LOG(LS_ERROR) << error;
951 PostCreateSessionDescriptionFailure(observer, error);
952 return;
953 }
954
955 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956}
957
958void PeerConnection::CreateAnswer(
959 CreateSessionDescriptionObserver* observer,
960 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100961 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -0700962 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
964 return;
965 }
deadbeefab9b2d12015-10-14 11:33:11 -0700966
967 cricket::MediaSessionOptions session_options;
968 if (!GetOptionsForAnswer(constraints, &session_options)) {
969 std::string error = "CreateAnswer called with invalid constraints.";
970 LOG(LS_ERROR) << error;
971 PostCreateSessionDescriptionFailure(observer, error);
972 return;
973 }
974
htaa2a49d92016-03-04 02:51:39 -0800975 session_->CreateAnswer(observer, session_options);
976}
977
978void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
979 const RTCOfferAnswerOptions& options) {
980 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
981 if (!VERIFY(observer != nullptr)) {
982 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
983 return;
984 }
985
986 cricket::MediaSessionOptions session_options;
987 if (!GetOptionsForAnswer(options, &session_options)) {
988 std::string error = "CreateAnswer called with invalid options.";
989 LOG(LS_ERROR) << error;
990 PostCreateSessionDescriptionFailure(observer, error);
991 return;
992 }
993
994 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995}
996
997void PeerConnection::SetLocalDescription(
998 SetSessionDescriptionObserver* observer,
999 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001000 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001001 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1003 return;
1004 }
1005 if (!desc) {
1006 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1007 return;
1008 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 // Update stats here so that we have the most recent stats for tracks and
1010 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001011 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 std::string error;
1013 if (!session_->SetLocalDescription(desc, &error)) {
1014 PostSetSessionDescriptionFailure(observer, error);
1015 return;
1016 }
deadbeefab9b2d12015-10-14 11:33:11 -07001017
1018 // If setting the description decided our SSL role, allocate any necessary
1019 // SCTP sids.
1020 rtc::SSLRole role;
1021 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001022 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001023 AllocateSctpSids(role);
1024 }
1025
1026 // Update state and SSRC of local MediaStreams and DataChannels based on the
1027 // local session description.
1028 const cricket::ContentInfo* audio_content =
1029 GetFirstAudioContent(desc->description());
1030 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001031 if (audio_content->rejected) {
1032 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1033 } else {
1034 const cricket::AudioContentDescription* audio_desc =
1035 static_cast<const cricket::AudioContentDescription*>(
1036 audio_content->description);
1037 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1038 }
deadbeefab9b2d12015-10-14 11:33:11 -07001039 }
1040
1041 const cricket::ContentInfo* video_content =
1042 GetFirstVideoContent(desc->description());
1043 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001044 if (video_content->rejected) {
1045 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1046 } else {
1047 const cricket::VideoContentDescription* video_desc =
1048 static_cast<const cricket::VideoContentDescription*>(
1049 video_content->description);
1050 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1051 }
deadbeefab9b2d12015-10-14 11:33:11 -07001052 }
1053
1054 const cricket::ContentInfo* data_content =
1055 GetFirstDataContent(desc->description());
1056 if (data_content) {
1057 const cricket::DataContentDescription* data_desc =
1058 static_cast<const cricket::DataContentDescription*>(
1059 data_content->description);
1060 if (rtc::starts_with(data_desc->protocol().data(),
1061 cricket::kMediaProtocolRtpPrefix)) {
1062 UpdateLocalRtpDataChannels(data_desc->streams());
1063 }
1064 }
1065
1066 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001067 signaling_thread()->Post(RTC_FROM_HERE, this,
1068 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001069
deadbeefcbecd352015-09-23 11:50:27 -07001070 // MaybeStartGathering needs to be called after posting
1071 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1072 // before signaling that SetLocalDescription completed.
1073 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001074}
1075
1076void PeerConnection::SetRemoteDescription(
1077 SetSessionDescriptionObserver* observer,
1078 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001079 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001080 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1082 return;
1083 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001084 if (!desc) {
1085 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1086 return;
1087 }
1088 // Update stats here so that we have the most recent stats for tracks and
1089 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001090 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 std::string error;
1092 if (!session_->SetRemoteDescription(desc, &error)) {
1093 PostSetSessionDescriptionFailure(observer, error);
1094 return;
1095 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096
deadbeefab9b2d12015-10-14 11:33:11 -07001097 // If setting the description decided our SSL role, allocate any necessary
1098 // SCTP sids.
1099 rtc::SSLRole role;
1100 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001101 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001102 AllocateSctpSids(role);
1103 }
1104
1105 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001106 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1107 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1108 const cricket::AudioContentDescription* audio_desc =
1109 GetFirstAudioContentDescription(remote_desc);
1110 const cricket::VideoContentDescription* video_desc =
1111 GetFirstVideoContentDescription(remote_desc);
1112 const cricket::DataContentDescription* data_desc =
1113 GetFirstDataContentDescription(remote_desc);
1114
1115 // Check if the descriptions include streams, just in case the peer supports
1116 // MSID, but doesn't indicate so with "a=msid-semantic".
1117 if (remote_desc->msid_supported() ||
1118 (audio_desc && !audio_desc->streams().empty()) ||
1119 (video_desc && !video_desc->streams().empty())) {
1120 remote_peer_supports_msid_ = true;
1121 }
deadbeefab9b2d12015-10-14 11:33:11 -07001122
1123 // We wait to signal new streams until we finish processing the description,
1124 // since only at that point will new streams have all their tracks.
1125 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1126
1127 // Find all audio rtp streams and create corresponding remote AudioTracks
1128 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001129 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001130 if (audio_content->rejected) {
1131 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1132 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001133 bool default_audio_track_needed =
1134 !remote_peer_supports_msid_ &&
1135 MediaContentDirectionHasSend(audio_desc->direction());
1136 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1137 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001138 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001139 }
deadbeefab9b2d12015-10-14 11:33:11 -07001140 }
1141
1142 // Find all video rtp streams and create corresponding remote VideoTracks
1143 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001144 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001145 if (video_content->rejected) {
1146 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1147 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001148 bool default_video_track_needed =
1149 !remote_peer_supports_msid_ &&
1150 MediaContentDirectionHasSend(video_desc->direction());
1151 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1152 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001153 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001154 }
deadbeefab9b2d12015-10-14 11:33:11 -07001155 }
1156
1157 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001158 if (data_desc) {
1159 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001160 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001161 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001162 }
1163 }
1164
1165 // Iterate new_streams and notify the observer about new MediaStreams.
1166 for (size_t i = 0; i < new_streams->count(); ++i) {
1167 MediaStreamInterface* new_stream = new_streams->at(i);
1168 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001169 // Call both the raw pointer and scoped_refptr versions of the method
1170 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001171 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001172 observer_->OnAddStream(
1173 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001174 }
1175
deadbeefbda7e0b2015-12-08 17:13:40 -08001176 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001177
1178 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001179 signaling_thread()->Post(RTC_FROM_HERE, this,
1180 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001181}
1182
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001183bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001184 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001185 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001186 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001187 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001188 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001189 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001190 return false;
1191 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001192 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001193
1194 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1195 session_->SetIceConfig(session_->ParseIceConfig(configuration));
1196 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001197}
1198
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199bool PeerConnection::AddIceCandidate(
1200 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001201 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202 return session_->ProcessIceMessage(ice_candidate);
1203}
1204
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001205bool PeerConnection::RemoveIceCandidates(
1206 const std::vector<cricket::Candidate>& candidates) {
1207 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1208 return session_->RemoveRemoteIceCandidates(candidates);
1209}
1210
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001211void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001212 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001213 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001214
1215 if (session_) {
1216 session_->set_metrics_observer(uma_observer_);
1217 }
1218
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001219 // Send information about IPv4/IPv6 status.
1220 if (uma_observer_ && port_allocator_) {
1221 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001222 uma_observer_->IncrementEnumCounter(
1223 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1224 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001225 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001226 uma_observer_->IncrementEnumCounter(
1227 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1228 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001229 }
1230 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001231}
1232
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233const SessionDescriptionInterface* PeerConnection::local_description() const {
1234 return session_->local_description();
1235}
1236
1237const SessionDescriptionInterface* PeerConnection::remote_description() const {
1238 return session_->remote_description();
1239}
1240
1241void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001242 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243 // Update stats here so that we have the most recent stats for tracks and
1244 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001245 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246
deadbeefd59daf82015-10-14 15:02:44 -07001247 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001248}
1249
deadbeefd59daf82015-10-14 15:02:44 -07001250void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1251 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001252 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001253 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001254 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001255 break;
deadbeefd59daf82015-10-14 15:02:44 -07001256 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001257 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1258 break;
deadbeefd59daf82015-10-14 15:02:44 -07001259 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1261 break;
deadbeefd59daf82015-10-14 15:02:44 -07001262 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1264 break;
deadbeefd59daf82015-10-14 15:02:44 -07001265 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1267 break;
deadbeefd59daf82015-10-14 15:02:44 -07001268 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001269 ChangeSignalingState(PeerConnectionInterface::kStable);
1270 break;
deadbeefd59daf82015-10-14 15:02:44 -07001271 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272 ChangeSignalingState(PeerConnectionInterface::kClosed);
1273 break;
1274 default:
1275 break;
1276 }
1277}
1278
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001279void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1282 SetSessionDescriptionMsg* param =
1283 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1284 param->observer->OnSuccess();
1285 delete param;
1286 break;
1287 }
1288 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1289 SetSessionDescriptionMsg* param =
1290 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1291 param->observer->OnFailure(param->error);
1292 delete param;
1293 break;
1294 }
deadbeefab9b2d12015-10-14 11:33:11 -07001295 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1296 CreateSessionDescriptionMsg* param =
1297 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1298 param->observer->OnFailure(param->error);
1299 delete param;
1300 break;
1301 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 case MSG_GETSTATS: {
1303 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001304 StatsReports reports;
1305 stats_->GetStats(param->track, &reports);
1306 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 delete param;
1308 break;
1309 }
deadbeefbd292462015-12-14 18:15:29 -08001310 case MSG_FREE_DATACHANNELS: {
1311 sctp_data_channels_to_free_.clear();
1312 break;
1313 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001315 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 break;
1317 }
1318}
1319
deadbeefab9b2d12015-10-14 11:33:11 -07001320void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001321 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001322 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001323 receivers_.push_back(
1324 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1325 signaling_thread(),
1326 new AudioRtpReceiver(stream, track_id, ssrc, session_.get())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327}
1328
deadbeefab9b2d12015-10-14 11:33:11 -07001329void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001330 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001331 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001332 receivers_.push_back(
1333 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1334 signaling_thread(),
1335 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
1336 ssrc, session_.get())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337}
1338
deadbeef70ab1a12015-09-28 16:53:55 -07001339// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1340// description.
perkjd61bf802016-03-24 03:16:19 -07001341void PeerConnection::DestroyReceiver(const std::string& track_id) {
1342 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001343 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001344 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001345 << " doesn't exist.";
1346 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001347 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001348 receivers_.erase(it);
1349 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001350}
1351
perkjd61bf802016-03-24 03:16:19 -07001352void PeerConnection::StopReceivers(cricket::MediaType media_type) {
1353 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1354 for (const auto& track_info : *current_tracks) {
1355 auto it = FindReceiverForTrack(track_info.track_id);
1356 if (it == receivers_.end()) {
1357 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_info.track_id
1358 << " doesn't exist.";
1359 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001360 (*it)->internal()->Stop();
perkjd61bf802016-03-24 03:16:19 -07001361 }
deadbeef70ab1a12015-09-28 16:53:55 -07001362 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363}
deadbeef70ab1a12015-09-28 16:53:55 -07001364
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365void PeerConnection::OnIceConnectionChange(
1366 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001367 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001368 // After transitioning to "closed", ignore any additional states from
1369 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001370 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001371 return;
1372 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001374 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375}
1376
1377void PeerConnection::OnIceGatheringChange(
1378 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001379 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380 if (IsClosed()) {
1381 return;
1382 }
1383 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001384 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385}
1386
1387void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001388 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001389 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390}
1391
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001392void PeerConnection::OnIceCandidatesRemoved(
1393 const std::vector<cricket::Candidate>& candidates) {
1394 RTC_DCHECK(signaling_thread()->IsCurrent());
1395 observer_->OnIceCandidatesRemoved(candidates);
1396}
1397
Peter Thatcher54360512015-07-08 11:08:35 -07001398void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001399 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001400 observer_->OnIceConnectionReceivingChange(receiving);
1401}
1402
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403void PeerConnection::ChangeSignalingState(
1404 PeerConnectionInterface::SignalingState signaling_state) {
1405 signaling_state_ = signaling_state;
1406 if (signaling_state == kClosed) {
1407 ice_connection_state_ = kIceConnectionClosed;
1408 observer_->OnIceConnectionChange(ice_connection_state_);
1409 if (ice_gathering_state_ != kIceGatheringComplete) {
1410 ice_gathering_state_ = kIceGatheringComplete;
1411 observer_->OnIceGatheringChange(ice_gathering_state_);
1412 }
1413 }
1414 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415}
1416
deadbeefeb459812015-12-15 19:24:43 -08001417void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1418 MediaStreamInterface* stream) {
1419 auto sender = FindSenderForTrack(track);
1420 if (sender != senders_.end()) {
1421 // We already have a sender for this track, so just change the stream_id
1422 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001423 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001424 return;
1425 }
1426
1427 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001428 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1429 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1430 signaling_thread(), new AudioRtpSender(track, stream->label(),
1431 session_.get(), stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001432 senders_.push_back(new_sender);
1433 // If the sender has already been configured in SDP, we call SetSsrc,
1434 // which will connect the sender to the underlying transport. This can
1435 // occur if a local session description that contains the ID of the sender
1436 // is set before AddStream is called. It can also occur if the local
1437 // session description is not changed and RemoveStream is called, and
1438 // later AddStream is called again with the same stream.
1439 const TrackInfo* track_info =
1440 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1441 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001442 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001443 }
1444}
1445
1446// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1447// indefinitely, when we have unified plan SDP.
1448void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1449 MediaStreamInterface* stream) {
1450 auto sender = FindSenderForTrack(track);
1451 if (sender == senders_.end()) {
1452 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1453 << " doesn't exist.";
1454 return;
1455 }
deadbeefa601f5c2016-06-06 14:27:39 -07001456 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001457 senders_.erase(sender);
1458}
1459
1460void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1461 MediaStreamInterface* stream) {
1462 auto sender = FindSenderForTrack(track);
1463 if (sender != senders_.end()) {
1464 // We already have a sender for this track, so just change the stream_id
1465 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001466 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001467 return;
1468 }
1469
1470 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001471 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1472 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1473 signaling_thread(),
1474 new VideoRtpSender(track, stream->label(), session_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001475 senders_.push_back(new_sender);
1476 const TrackInfo* track_info =
1477 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1478 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001479 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001480 }
1481}
1482
1483void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1484 MediaStreamInterface* stream) {
1485 auto sender = FindSenderForTrack(track);
1486 if (sender == senders_.end()) {
1487 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1488 << " doesn't exist.";
1489 return;
1490 }
deadbeefa601f5c2016-06-06 14:27:39 -07001491 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001492 senders_.erase(sender);
1493}
1494
deadbeefab9b2d12015-10-14 11:33:11 -07001495void PeerConnection::PostSetSessionDescriptionFailure(
1496 SetSessionDescriptionObserver* observer,
1497 const std::string& error) {
1498 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1499 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001500 signaling_thread()->Post(RTC_FROM_HERE, this,
1501 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001502}
1503
1504void PeerConnection::PostCreateSessionDescriptionFailure(
1505 CreateSessionDescriptionObserver* observer,
1506 const std::string& error) {
1507 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1508 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001509 signaling_thread()->Post(RTC_FROM_HERE, this,
1510 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001511}
1512
1513bool PeerConnection::GetOptionsForOffer(
1514 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1515 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001516 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1517 // ContentInfos.
1518 if (session_->local_description()) {
1519 for (const cricket::ContentInfo& content :
1520 session_->local_description()->description()->contents()) {
1521 session_options->transport_options[content.name] =
1522 cricket::TransportOptions();
1523 }
1524 }
htaaac2dea2016-03-10 13:35:55 -08001525 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001526 return false;
1527 }
1528
deadbeeffac06552015-11-25 11:26:01 -08001529 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001530 // Offer to receive audio/video if the constraint is not set and there are
1531 // send streams, or we're currently receiving.
1532 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1533 session_options->recv_audio =
1534 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1535 !remote_audio_tracks_.empty();
1536 }
1537 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1538 session_options->recv_video =
1539 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1540 !remote_video_tracks_.empty();
1541 }
1542 session_options->bundle_enabled =
1543 session_options->bundle_enabled &&
1544 (session_options->has_audio() || session_options->has_video() ||
1545 session_options->has_data());
1546
deadbeefab9b2d12015-10-14 11:33:11 -07001547 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1548 session_options->data_channel_type = cricket::DCT_SCTP;
1549 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001550
1551 session_options->rtcp_cname = rtcp_cname_;
deadbeefab9b2d12015-10-14 11:33:11 -07001552 return true;
1553}
1554
htaa2a49d92016-03-04 02:51:39 -08001555void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001556 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001557 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1558 // ContentInfos.
1559 if (session_->remote_description()) {
1560 // Initialize the transport_options map.
1561 for (const cricket::ContentInfo& content :
1562 session_->remote_description()->description()->contents()) {
1563 session_options->transport_options[content.name] =
1564 cricket::TransportOptions();
1565 }
1566 }
deadbeeffac06552015-11-25 11:26:01 -08001567 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001568 session_options->bundle_enabled =
1569 session_options->bundle_enabled &&
1570 (session_options->has_audio() || session_options->has_video() ||
1571 session_options->has_data());
1572
deadbeefab9b2d12015-10-14 11:33:11 -07001573 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1574 // are not signaled in the SDP so does not go through that path and must be
1575 // handled here.
1576 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1577 session_options->data_channel_type = cricket::DCT_SCTP;
1578 }
htaa2a49d92016-03-04 02:51:39 -08001579}
1580
1581bool PeerConnection::GetOptionsForAnswer(
1582 const MediaConstraintsInterface* constraints,
1583 cricket::MediaSessionOptions* session_options) {
1584 session_options->recv_audio = false;
1585 session_options->recv_video = false;
1586 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1587 return false;
1588 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001589 session_options->rtcp_cname = rtcp_cname_;
1590
htaa2a49d92016-03-04 02:51:39 -08001591 FinishOptionsForAnswer(session_options);
1592 return true;
1593}
1594
1595bool PeerConnection::GetOptionsForAnswer(
1596 const RTCOfferAnswerOptions& options,
1597 cricket::MediaSessionOptions* session_options) {
1598 session_options->recv_audio = false;
1599 session_options->recv_video = false;
htaaac2dea2016-03-10 13:35:55 -08001600 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001601 return false;
1602 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001603 session_options->rtcp_cname = rtcp_cname_;
1604
htaa2a49d92016-03-04 02:51:39 -08001605 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001606 return true;
1607}
1608
deadbeeffaac4972015-11-12 15:33:07 -08001609void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1610 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001611 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1612 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001613}
1614
deadbeefab9b2d12015-10-14 11:33:11 -07001615void PeerConnection::UpdateRemoteStreamsList(
1616 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001617 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001618 cricket::MediaType media_type,
1619 StreamCollection* new_streams) {
1620 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1621
1622 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001623 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001624 auto track_it = current_tracks->begin();
1625 while (track_it != current_tracks->end()) {
1626 const TrackInfo& info = *track_it;
1627 const cricket::StreamParams* params =
1628 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001629 bool track_exists = params && params->id == info.track_id;
1630 // If this is a default track, and we still need it, don't remove it.
1631 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1632 track_exists) {
1633 ++track_it;
1634 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001635 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1636 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001637 }
1638 }
1639
1640 // Find new and active tracks.
1641 for (const cricket::StreamParams& params : streams) {
1642 // The sync_label is the MediaStream label and the |stream.id| is the
1643 // track id.
1644 const std::string& stream_label = params.sync_label;
1645 const std::string& track_id = params.id;
1646 uint32_t ssrc = params.first_ssrc();
1647
1648 rtc::scoped_refptr<MediaStreamInterface> stream =
1649 remote_streams_->find(stream_label);
1650 if (!stream) {
1651 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001652 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1653 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001654 remote_streams_->AddStream(stream);
1655 new_streams->AddStream(stream);
1656 }
1657
1658 const TrackInfo* track_info =
1659 FindTrackInfo(*current_tracks, stream_label, track_id);
1660 if (!track_info) {
1661 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1662 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1663 }
1664 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001665
1666 // Add default track if necessary.
1667 if (default_track_needed) {
1668 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1669 remote_streams_->find(kDefaultStreamLabel);
1670 if (!default_stream) {
1671 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001672 default_stream = MediaStreamProxy::Create(
1673 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001674 remote_streams_->AddStream(default_stream);
1675 new_streams->AddStream(default_stream);
1676 }
1677 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1678 ? kDefaultAudioTrackLabel
1679 : kDefaultVideoTrackLabel;
1680 const TrackInfo* default_track_info =
1681 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1682 if (!default_track_info) {
1683 current_tracks->push_back(
1684 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1685 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1686 }
1687 }
deadbeefab9b2d12015-10-14 11:33:11 -07001688}
1689
1690void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1691 const std::string& track_id,
1692 uint32_t ssrc,
1693 cricket::MediaType media_type) {
1694 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1695
1696 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001697 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001698 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001699 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001700 } else {
1701 RTC_DCHECK(false && "Invalid media type");
1702 }
1703}
1704
1705void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1706 const std::string& track_id,
1707 cricket::MediaType media_type) {
1708 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1709
1710 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001711 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1712 // will be notified which will end the AudioRtpReceiver::track().
1713 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001714 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1715 stream->FindAudioTrack(track_id);
1716 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001717 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001718 }
1719 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001720 // Stopping or destroying a VideoRtpReceiver will end the
1721 // VideoRtpReceiver::track().
1722 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001723 rtc::scoped_refptr<VideoTrackInterface> video_track =
1724 stream->FindVideoTrack(track_id);
1725 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001726 // There's no guarantee the track is still available, e.g. the track may
1727 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001728 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001729 }
1730 } else {
1731 ASSERT(false && "Invalid media type");
1732 }
1733}
1734
1735void PeerConnection::UpdateEndedRemoteMediaStreams() {
1736 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1737 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1738 MediaStreamInterface* stream = remote_streams_->at(i);
1739 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1740 streams_to_remove.push_back(stream);
1741 }
1742 }
1743
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001744 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001745 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001746 // Call both the raw pointer and scoped_refptr versions of the method
1747 // for compatibility.
1748 observer_->OnRemoveStream(stream.get());
1749 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001750 }
1751}
1752
deadbeefab9b2d12015-10-14 11:33:11 -07001753void PeerConnection::UpdateLocalTracks(
1754 const std::vector<cricket::StreamParams>& streams,
1755 cricket::MediaType media_type) {
1756 TrackInfos* current_tracks = GetLocalTracks(media_type);
1757
1758 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1759 // don't match the new StreamParam.
1760 TrackInfos::iterator track_it = current_tracks->begin();
1761 while (track_it != current_tracks->end()) {
1762 const TrackInfo& info = *track_it;
1763 const cricket::StreamParams* params =
1764 cricket::GetStreamBySsrc(streams, info.ssrc);
1765 if (!params || params->id != info.track_id ||
1766 params->sync_label != info.stream_label) {
1767 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1768 media_type);
1769 track_it = current_tracks->erase(track_it);
1770 } else {
1771 ++track_it;
1772 }
1773 }
1774
1775 // Find new and active tracks.
1776 for (const cricket::StreamParams& params : streams) {
1777 // The sync_label is the MediaStream label and the |stream.id| is the
1778 // track id.
1779 const std::string& stream_label = params.sync_label;
1780 const std::string& track_id = params.id;
1781 uint32_t ssrc = params.first_ssrc();
1782 const TrackInfo* track_info =
1783 FindTrackInfo(*current_tracks, stream_label, track_id);
1784 if (!track_info) {
1785 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1786 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1787 }
1788 }
1789}
1790
1791void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1792 const std::string& track_id,
1793 uint32_t ssrc,
1794 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001795 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001796 if (!sender) {
1797 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1798 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001799 return;
1800 }
1801
deadbeeffac06552015-11-25 11:26:01 -08001802 if (sender->media_type() != media_type) {
1803 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1804 << " description with an unexpected media type.";
1805 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001806 }
deadbeeffac06552015-11-25 11:26:01 -08001807
1808 sender->set_stream_id(stream_label);
1809 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001810}
1811
1812void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1813 const std::string& track_id,
1814 uint32_t ssrc,
1815 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001816 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001817 if (!sender) {
1818 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001819 // SessionDescriptions has been renegotiated.
1820 return;
1821 }
deadbeeffac06552015-11-25 11:26:01 -08001822
1823 // A sender has been removed from the SessionDescription but it's still
1824 // associated with the PeerConnection. This only occurs if the SDP doesn't
1825 // match with the calls to CreateSender, AddStream and RemoveStream.
1826 if (sender->media_type() != media_type) {
1827 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1828 << " description with an unexpected media type.";
1829 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001830 }
deadbeeffac06552015-11-25 11:26:01 -08001831
1832 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001833}
1834
1835void PeerConnection::UpdateLocalRtpDataChannels(
1836 const cricket::StreamParamsVec& streams) {
1837 std::vector<std::string> existing_channels;
1838
1839 // Find new and active data channels.
1840 for (const cricket::StreamParams& params : streams) {
1841 // |it->sync_label| is actually the data channel label. The reason is that
1842 // we use the same naming of data channels as we do for
1843 // MediaStreams and Tracks.
1844 // For MediaStreams, the sync_label is the MediaStream label and the
1845 // track label is the same as |streamid|.
1846 const std::string& channel_label = params.sync_label;
1847 auto data_channel_it = rtp_data_channels_.find(channel_label);
1848 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1849 continue;
1850 }
1851 // Set the SSRC the data channel should use for sending.
1852 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1853 existing_channels.push_back(data_channel_it->first);
1854 }
1855
1856 UpdateClosingRtpDataChannels(existing_channels, true);
1857}
1858
1859void PeerConnection::UpdateRemoteRtpDataChannels(
1860 const cricket::StreamParamsVec& streams) {
1861 std::vector<std::string> existing_channels;
1862
1863 // Find new and active data channels.
1864 for (const cricket::StreamParams& params : streams) {
1865 // The data channel label is either the mslabel or the SSRC if the mslabel
1866 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1867 std::string label = params.sync_label.empty()
1868 ? rtc::ToString(params.first_ssrc())
1869 : params.sync_label;
1870 auto data_channel_it = rtp_data_channels_.find(label);
1871 if (data_channel_it == rtp_data_channels_.end()) {
1872 // This is a new data channel.
1873 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1874 } else {
1875 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1876 }
1877 existing_channels.push_back(label);
1878 }
1879
1880 UpdateClosingRtpDataChannels(existing_channels, false);
1881}
1882
1883void PeerConnection::UpdateClosingRtpDataChannels(
1884 const std::vector<std::string>& active_channels,
1885 bool is_local_update) {
1886 auto it = rtp_data_channels_.begin();
1887 while (it != rtp_data_channels_.end()) {
1888 DataChannel* data_channel = it->second;
1889 if (std::find(active_channels.begin(), active_channels.end(),
1890 data_channel->label()) != active_channels.end()) {
1891 ++it;
1892 continue;
1893 }
1894
1895 if (is_local_update) {
1896 data_channel->SetSendSsrc(0);
1897 } else {
1898 data_channel->RemotePeerRequestClose();
1899 }
1900
1901 if (data_channel->state() == DataChannel::kClosed) {
1902 rtp_data_channels_.erase(it);
1903 it = rtp_data_channels_.begin();
1904 } else {
1905 ++it;
1906 }
1907 }
1908}
1909
1910void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1911 uint32_t remote_ssrc) {
1912 rtc::scoped_refptr<DataChannel> channel(
1913 InternalCreateDataChannel(label, nullptr));
1914 if (!channel.get()) {
1915 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1916 << "CreateDataChannel failed.";
1917 return;
1918 }
1919 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07001920 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
1921 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001922 // Call both the raw pointer and scoped_refptr versions of the method
1923 // for compatibility.
1924 observer_->OnDataChannel(proxy_channel.get());
1925 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07001926}
1927
1928rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1929 const std::string& label,
1930 const InternalDataChannelInit* config) {
1931 if (IsClosed()) {
1932 return nullptr;
1933 }
1934 if (session_->data_channel_type() == cricket::DCT_NONE) {
1935 LOG(LS_ERROR)
1936 << "InternalCreateDataChannel: Data is not supported in this call.";
1937 return nullptr;
1938 }
1939 InternalDataChannelInit new_config =
1940 config ? (*config) : InternalDataChannelInit();
1941 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1942 if (new_config.id < 0) {
1943 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001944 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07001945 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1946 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1947 return nullptr;
1948 }
1949 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1950 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1951 << "because the id is already in use or out of range.";
1952 return nullptr;
1953 }
1954 }
1955
1956 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1957 session_.get(), session_->data_channel_type(), label, new_config));
1958 if (!channel) {
1959 sid_allocator_.ReleaseSid(new_config.id);
1960 return nullptr;
1961 }
1962
1963 if (channel->data_channel_type() == cricket::DCT_RTP) {
1964 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1965 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1966 << " already exists.";
1967 return nullptr;
1968 }
1969 rtp_data_channels_[channel->label()] = channel;
1970 } else {
1971 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1972 sctp_data_channels_.push_back(channel);
1973 channel->SignalClosed.connect(this,
1974 &PeerConnection::OnSctpDataChannelClosed);
1975 }
1976
1977 return channel;
1978}
1979
1980bool PeerConnection::HasDataChannels() const {
1981 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1982}
1983
1984void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1985 for (const auto& channel : sctp_data_channels_) {
1986 if (channel->id() < 0) {
1987 int sid;
1988 if (!sid_allocator_.AllocateSid(role, &sid)) {
1989 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1990 continue;
1991 }
1992 channel->SetSctpSid(sid);
1993 }
1994 }
1995}
1996
1997void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08001998 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07001999 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2000 ++it) {
2001 if (it->get() == channel) {
2002 if (channel->id() >= 0) {
2003 sid_allocator_.ReleaseSid(channel->id());
2004 }
deadbeefbd292462015-12-14 18:15:29 -08002005 // Since this method is triggered by a signal from the DataChannel,
2006 // we can't free it directly here; we need to free it asynchronously.
2007 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002008 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002009 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2010 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002011 return;
2012 }
2013 }
2014}
2015
2016void PeerConnection::OnVoiceChannelDestroyed() {
perkjd61bf802016-03-24 03:16:19 -07002017 StopReceivers(cricket::MEDIA_TYPE_AUDIO);
deadbeefab9b2d12015-10-14 11:33:11 -07002018}
2019
2020void PeerConnection::OnVideoChannelDestroyed() {
perkjd61bf802016-03-24 03:16:19 -07002021 StopReceivers(cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002022}
2023
2024void PeerConnection::OnDataChannelCreated() {
2025 for (const auto& channel : sctp_data_channels_) {
2026 channel->OnTransportChannelCreated();
2027 }
2028}
2029
2030void PeerConnection::OnDataChannelDestroyed() {
2031 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2032 // DataChannel may callback to us and try to modify the list.
2033 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2034 temp_rtp_dcs.swap(rtp_data_channels_);
2035 for (const auto& kv : temp_rtp_dcs) {
2036 kv.second->OnTransportChannelDestroyed();
2037 }
2038
2039 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2040 temp_sctp_dcs.swap(sctp_data_channels_);
2041 for (const auto& channel : temp_sctp_dcs) {
2042 channel->OnTransportChannelDestroyed();
2043 }
2044}
2045
2046void PeerConnection::OnDataChannelOpenMessage(
2047 const std::string& label,
2048 const InternalDataChannelInit& config) {
2049 rtc::scoped_refptr<DataChannel> channel(
2050 InternalCreateDataChannel(label, &config));
2051 if (!channel.get()) {
2052 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2053 return;
2054 }
2055
deadbeefa601f5c2016-06-06 14:27:39 -07002056 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2057 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002058 // Call both the raw pointer and scoped_refptr versions of the method
2059 // for compatibility.
2060 observer_->OnDataChannel(proxy_channel.get());
2061 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002062}
2063
deadbeefa601f5c2016-06-06 14:27:39 -07002064RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2065 auto it = std::find_if(
2066 senders_.begin(), senders_.end(),
2067 [id](const rtc::scoped_refptr<
2068 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2069 return sender->id() == id;
2070 });
2071 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002072}
2073
deadbeefa601f5c2016-06-06 14:27:39 -07002074std::vector<
2075 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002076PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2077 return std::find_if(
2078 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002079 [track](const rtc::scoped_refptr<
2080 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002081 return sender->track() == track;
2082 });
2083}
2084
deadbeefa601f5c2016-06-06 14:27:39 -07002085std::vector<rtc::scoped_refptr<
2086 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002087PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002088 return std::find_if(
2089 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002090 [track_id](const rtc::scoped_refptr<
2091 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002092 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002093 });
2094}
2095
deadbeefab9b2d12015-10-14 11:33:11 -07002096PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
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) ? &remote_audio_tracks_
2101 : &remote_video_tracks_;
2102}
2103
2104PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2105 cricket::MediaType media_type) {
2106 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2107 media_type == cricket::MEDIA_TYPE_VIDEO);
2108 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2109 : &local_video_tracks_;
2110}
2111
2112const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2113 const PeerConnection::TrackInfos& infos,
2114 const std::string& stream_label,
2115 const std::string track_id) const {
2116 for (const TrackInfo& track_info : infos) {
2117 if (track_info.stream_label == stream_label &&
2118 track_info.track_id == track_id) {
2119 return &track_info;
2120 }
2121 }
2122 return nullptr;
2123}
2124
2125DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2126 for (const auto& channel : sctp_data_channels_) {
2127 if (channel->id() == sid) {
2128 return channel;
2129 }
2130 }
2131 return nullptr;
2132}
2133
deadbeef91dd5672016-05-18 16:55:30 -07002134bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002135 const RTCConfiguration& configuration) {
2136 cricket::ServerAddresses stun_servers;
2137 std::vector<cricket::RelayServerConfig> turn_servers;
2138 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2139 return false;
2140 }
2141
2142 // To handle both internal and externally created port allocator, we will
2143 // enable BUNDLE here.
2144 int portallocator_flags = port_allocator_->flags();
2145 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2146 cricket::PORTALLOCATOR_ENABLE_IPV6;
2147 // If the disable-IPv6 flag was specified, we'll not override it
2148 // by experiment.
2149 if (configuration.disable_ipv6) {
2150 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2151 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2152 "Disabled") {
2153 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2154 }
2155
2156 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2157 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2158 LOG(LS_INFO) << "TCP candidates are disabled.";
2159 }
2160
honghaiz60347052016-05-31 18:29:12 -07002161 if (configuration.candidate_network_policy ==
2162 kCandidateNetworkPolicyLowCost) {
2163 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2164 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2165 }
2166
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002167 port_allocator_->set_flags(portallocator_flags);
2168 // No step delay is used while allocating ports.
2169 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2170 port_allocator_->set_candidate_filter(
2171 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2172
2173 // Call this last since it may create pooled allocator sessions using the
2174 // properties set above.
2175 port_allocator_->SetConfiguration(stun_servers, turn_servers,
2176 configuration.ice_candidate_pool_size);
2177 return true;
2178}
2179
deadbeef91dd5672016-05-18 16:55:30 -07002180bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002181 const RTCConfiguration& configuration) {
2182 cricket::ServerAddresses stun_servers;
2183 std::vector<cricket::RelayServerConfig> turn_servers;
2184 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2185 return false;
2186 }
2187 port_allocator_->set_candidate_filter(
2188 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2189 // Call this last since it may create pooled allocator sessions using the
2190 // candidate filter set above.
2191 port_allocator_->SetConfiguration(stun_servers, turn_servers,
2192 configuration.ice_candidate_pool_size);
2193 return true;
2194}
2195
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196} // namespace webrtc