blob: cc33aa88cebb6ce1473009115db4bdf711d51058 [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
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700399// Helper method to set a voice/video channel on all applicable senders
400// and receivers when one is created/destroyed by WebRtcSession.
401//
402// Used by On(Voice|Video)Channel(Created|Destroyed)
403template <class SENDER,
404 class RECEIVER,
405 class CHANNEL,
406 class SENDERS,
407 class RECEIVERS>
408void SetChannelOnSendersAndReceivers(CHANNEL* channel,
409 SENDERS& senders,
410 RECEIVERS& receivers,
411 cricket::MediaType media_type) {
412 for (auto& sender : senders) {
413 if (sender->media_type() == media_type) {
414 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
415 }
416 }
417 for (auto& receiver : receivers) {
418 if (receiver->media_type() == media_type) {
419 if (!channel) {
420 receiver->internal()->Stop();
421 }
422 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
423 }
424 }
425}
426
deadbeef0a6c4ca2015-10-06 11:38:28 -0700427} // namespace
428
429namespace webrtc {
430
zhihuang8f65cdf2016-05-06 18:40:30 -0700431// Generate a RTCP CNAME when a PeerConnection is created.
432std::string GenerateRtcpCname() {
433 std::string cname;
434 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
435 LOG(LS_ERROR) << "Failed to generate CNAME.";
436 RTC_DCHECK(false);
437 }
438 return cname;
439}
440
htaa2a49d92016-03-04 02:51:39 -0800441bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700442 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800443 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700444 cricket::MediaSessionOptions* session_options) {
445 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
446 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
447 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
448 return false;
449 }
450
htaaac2dea2016-03-10 13:35:55 -0800451 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700452 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700453 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800454 } else {
455 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700456 }
htaaac2dea2016-03-10 13:35:55 -0800457 // For offers, we only offer video if we have it or it's forced by options.
458 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700459 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700460 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800461 } else if (is_offer) {
462 session_options->recv_video = false;
463 } else {
464 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700465 }
466
467 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700468 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800469 for (auto& kv : session_options->transport_options) {
470 kv.second.ice_restart = rtc_options.ice_restart;
471 }
deadbeefab9b2d12015-10-14 11:33:11 -0700472
473 return true;
474}
475
476bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
477 cricket::MediaSessionOptions* session_options) {
478 bool value = false;
479 size_t mandatory_constraints_satisfied = 0;
480
481 // kOfferToReceiveAudio defaults to true according to spec.
482 if (!FindConstraint(constraints,
483 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
484 &mandatory_constraints_satisfied) ||
485 value) {
486 session_options->recv_audio = true;
487 }
488
489 // kOfferToReceiveVideo defaults to false according to spec. But
490 // if it is an answer and video is offered, we should still accept video
491 // per default.
492 value = false;
493 if (!FindConstraint(constraints,
494 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
495 &mandatory_constraints_satisfied) ||
496 value) {
497 session_options->recv_video = true;
498 }
499
500 if (FindConstraint(constraints,
501 MediaConstraintsInterface::kVoiceActivityDetection, &value,
502 &mandatory_constraints_satisfied)) {
503 session_options->vad_enabled = value;
504 }
505
506 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
507 &mandatory_constraints_satisfied)) {
508 session_options->bundle_enabled = value;
509 } else {
510 // kUseRtpMux defaults to true according to spec.
511 session_options->bundle_enabled = true;
512 }
deadbeefab9b2d12015-10-14 11:33:11 -0700513
deadbeef0ed85b22016-02-23 17:24:52 -0800514 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700515 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
516 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700517 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800518 ice_restart = true;
519 }
520 for (auto& kv : session_options->transport_options) {
521 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700522 }
523
524 if (!constraints) {
525 return true;
526 }
527 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
528}
529
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200530bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800531 cricket::ServerAddresses* stun_servers,
532 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200533 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
534 if (!server.urls.empty()) {
535 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200536 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700537 LOG(LS_ERROR) << "Empty uri.";
538 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200539 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800540 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200541 return false;
542 }
543 }
544 } else if (!server.uri.empty()) {
545 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800546 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200548 }
549 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700550 LOG(LS_ERROR) << "Empty uri.";
551 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000552 }
553 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800554 // Candidates must have unique priorities, so that connectivity checks
555 // are performed in a well-defined order.
556 int priority = static_cast<int>(turn_servers->size() - 1);
557 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
558 // First in the list gets highest priority.
559 turn_server.priority = priority--;
560 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000561 return true;
562}
563
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000564PeerConnection::PeerConnection(PeerConnectionFactory* factory)
565 : factory_(factory),
566 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000567 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568 signaling_state_(kStable),
569 ice_state_(kIceNew),
570 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700571 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700572 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700573 local_streams_(StreamCollection::Create()),
574 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575
576PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100577 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700578 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700579 // Need to detach RTP senders/receivers from WebRtcSession,
580 // since it's about to be destroyed.
581 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700582 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700583 }
584 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700585 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700586 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700587 // Destroy stats_ because it depends on session_.
588 stats_.reset(nullptr);
589 // Now destroy session_ before destroying other members,
590 // because its destruction fires signals (such as VoiceChannelDestroyed)
591 // which will trigger some final actions in PeerConnection...
592 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700593 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700594 network_thread()->Invoke<void>(RTC_FROM_HERE,
595 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000596}
597
598bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000599 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700600 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200601 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800602 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100603 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800604 RTC_DCHECK(observer != nullptr);
605 if (!observer) {
606 return false;
607 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000608 observer_ = observer;
609
kwiberg0eb15ed2015-12-17 03:04:15 -0800610 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800611
deadbeef91dd5672016-05-18 16:55:30 -0700612 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700613 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700614 if (!network_thread()->Invoke<bool>(
615 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
616 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000617 return false;
618 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619
nissec36b31b2016-04-11 23:25:29 -0700620 media_controller_.reset(
621 factory_->CreateMediaController(configuration.media_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000622
stefanc1aeaf02015-10-15 07:26:07 -0700623 session_.reset(
danilchape9021a32016-05-17 01:52:02 -0700624 new WebRtcSession(media_controller_.get(), factory_->network_thread(),
625 factory_->worker_thread(), factory_->signaling_thread(),
626 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700627 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000628
629 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200630 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800631 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000632 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700633 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000634
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000635 // Register PeerConnection as receiver of local ice candidates.
636 // All the callbacks will be posted to the application from PeerConnection.
637 session_->RegisterIceObserver(this);
638 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700639 session_->SignalVoiceChannelCreated.connect(
640 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700641 session_->SignalVoiceChannelDestroyed.connect(
642 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700643 session_->SignalVideoChannelCreated.connect(
644 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700645 session_->SignalVideoChannelDestroyed.connect(
646 this, &PeerConnection::OnVideoChannelDestroyed);
647 session_->SignalDataChannelCreated.connect(
648 this, &PeerConnection::OnDataChannelCreated);
649 session_->SignalDataChannelDestroyed.connect(
650 this, &PeerConnection::OnDataChannelDestroyed);
651 session_->SignalDataChannelOpenMessage.connect(
652 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000653 return true;
654}
655
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000656rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700658 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659}
660
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000661rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700663 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664}
665
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000666bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100667 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668 if (IsClosed()) {
669 return false;
670 }
deadbeefab9b2d12015-10-14 11:33:11 -0700671 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672 return false;
673 }
deadbeefab9b2d12015-10-14 11:33:11 -0700674
675 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800676 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
677 observer->SignalAudioTrackAdded.connect(this,
678 &PeerConnection::OnAudioTrackAdded);
679 observer->SignalAudioTrackRemoved.connect(
680 this, &PeerConnection::OnAudioTrackRemoved);
681 observer->SignalVideoTrackAdded.connect(this,
682 &PeerConnection::OnVideoTrackAdded);
683 observer->SignalVideoTrackRemoved.connect(
684 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700685 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700686
deadbeefab9b2d12015-10-14 11:33:11 -0700687 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800688 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700689 }
690 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800691 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700692 }
693
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000694 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 observer_->OnRenegotiationNeeded();
696 return true;
697}
698
699void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100700 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700701 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800702 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700703 }
704 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800705 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700706 }
707
708 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800709 stream_observers_.erase(
710 std::remove_if(
711 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700712 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800713 return observer->stream()->label().compare(local_stream->label()) ==
714 0;
715 }),
716 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700717
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 if (IsClosed()) {
719 return;
720 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721 observer_->OnRenegotiationNeeded();
722}
723
deadbeefe1f9d832016-01-14 15:35:42 -0800724rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
725 MediaStreamTrackInterface* track,
726 std::vector<MediaStreamInterface*> streams) {
727 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
728 if (IsClosed()) {
729 return nullptr;
730 }
731 if (streams.size() >= 2) {
732 LOG(LS_ERROR)
733 << "Adding a track with two streams is not currently supported.";
734 return nullptr;
735 }
736 // TODO(deadbeef): Support adding a track to two different senders.
737 if (FindSenderForTrack(track) != senders_.end()) {
738 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
739 return nullptr;
740 }
741
742 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700743 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800744 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700745 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800746 signaling_thread(),
747 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700748 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800749 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700750 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800751 }
752 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700753 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800754 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700755 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800756 }
757 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700758 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800759 signaling_thread(),
760 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700761 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800762 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700763 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800764 }
765 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700766 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800767 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700768 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800769 }
770 } else {
771 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
772 return rtc::scoped_refptr<RtpSenderInterface>();
773 }
774
775 senders_.push_back(new_sender);
776 observer_->OnRenegotiationNeeded();
777 return new_sender;
778}
779
780bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
781 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
782 if (IsClosed()) {
783 return false;
784 }
785
786 auto it = std::find(senders_.begin(), senders_.end(), sender);
787 if (it == senders_.end()) {
788 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
789 return false;
790 }
deadbeefa601f5c2016-06-06 14:27:39 -0700791 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800792 senders_.erase(it);
793
794 observer_->OnRenegotiationNeeded();
795 return true;
796}
797
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000798rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100800 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801 if (!track) {
802 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
803 return NULL;
804 }
deadbeefab9b2d12015-10-14 11:33:11 -0700805 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
807 return NULL;
808 }
809
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000810 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 DtmfSender::Create(track, signaling_thread(), session_.get()));
812 if (!sender.get()) {
813 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
814 return NULL;
815 }
816 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
817}
818
deadbeeffac06552015-11-25 11:26:01 -0800819rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800820 const std::string& kind,
821 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100822 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeefa601f5c2016-06-06 14:27:39 -0700823 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800824 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700825 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700826 signaling_thread(),
827 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800828 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700829 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700830 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800831 } else {
832 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800833 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800834 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800835 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700836 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800837 }
deadbeeffac06552015-11-25 11:26:01 -0800838 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800839 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800840}
841
deadbeef70ab1a12015-09-28 16:53:55 -0700842std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
843 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700844 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
845 for (const auto& sender : senders_) {
846 ret.push_back(sender.get());
847 }
848 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700849}
850
851std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
852PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700853 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
854 for (const auto& receiver : receivers_) {
855 ret.push_back(receiver.get());
856 }
857 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700858}
859
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000861 MediaStreamTrackInterface* track,
862 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100863 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700864 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000865 if (!VERIFY(observer != NULL)) {
866 LOG(LS_ERROR) << "GetStats - observer is NULL.";
867 return false;
868 }
869
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000870 stats_->UpdateStats(level);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700871 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000872 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873 return true;
874}
875
876PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
877 return signaling_state_;
878}
879
880PeerConnectionInterface::IceState PeerConnection::ice_state() {
881 return ice_state_;
882}
883
884PeerConnectionInterface::IceConnectionState
885PeerConnection::ice_connection_state() {
886 return ice_connection_state_;
887}
888
889PeerConnectionInterface::IceGatheringState
890PeerConnection::ice_gathering_state() {
891 return ice_gathering_state_;
892}
893
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000894rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895PeerConnection::CreateDataChannel(
896 const std::string& label,
897 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100898 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700899 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000900
kwibergd1fe2812016-04-27 06:47:29 -0700901 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000902 if (config) {
903 internal_config.reset(new InternalDataChannelInit(*config));
904 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000905 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700906 InternalCreateDataChannel(label, internal_config.get()));
907 if (!channel.get()) {
908 return nullptr;
909 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000911 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
912 // the first SCTP DataChannel.
913 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
914 observer_->OnRenegotiationNeeded();
915 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000916
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return DataChannelProxy::Create(signaling_thread(), channel.get());
918}
919
920void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
921 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100922 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700923 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
925 return;
926 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000927 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000928
929 bool value;
930 size_t mandatory_constraints = 0;
931
932 if (FindConstraint(constraints,
933 MediaConstraintsInterface::kOfferToReceiveAudio,
934 &value,
935 &mandatory_constraints)) {
936 options.offer_to_receive_audio =
937 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
938 }
939
940 if (FindConstraint(constraints,
941 MediaConstraintsInterface::kOfferToReceiveVideo,
942 &value,
943 &mandatory_constraints)) {
944 options.offer_to_receive_video =
945 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
946 }
947
948 if (FindConstraint(constraints,
949 MediaConstraintsInterface::kVoiceActivityDetection,
950 &value,
951 &mandatory_constraints)) {
952 options.voice_activity_detection = value;
953 }
954
955 if (FindConstraint(constraints,
956 MediaConstraintsInterface::kIceRestart,
957 &value,
958 &mandatory_constraints)) {
959 options.ice_restart = value;
960 }
961
962 if (FindConstraint(constraints,
963 MediaConstraintsInterface::kUseRtpMux,
964 &value,
965 &mandatory_constraints)) {
966 options.use_rtp_mux = value;
967 }
968
969 CreateOffer(observer, options);
970}
971
972void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
973 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100974 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700975 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000976 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
977 return;
978 }
deadbeefab9b2d12015-10-14 11:33:11 -0700979
980 cricket::MediaSessionOptions session_options;
981 if (!GetOptionsForOffer(options, &session_options)) {
982 std::string error = "CreateOffer called with invalid options.";
983 LOG(LS_ERROR) << error;
984 PostCreateSessionDescriptionFailure(observer, error);
985 return;
986 }
987
988 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989}
990
991void PeerConnection::CreateAnswer(
992 CreateSessionDescriptionObserver* observer,
993 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100994 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -0700995 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
997 return;
998 }
deadbeefab9b2d12015-10-14 11:33:11 -0700999
1000 cricket::MediaSessionOptions session_options;
1001 if (!GetOptionsForAnswer(constraints, &session_options)) {
1002 std::string error = "CreateAnswer called with invalid constraints.";
1003 LOG(LS_ERROR) << error;
1004 PostCreateSessionDescriptionFailure(observer, error);
1005 return;
1006 }
1007
htaa2a49d92016-03-04 02:51:39 -08001008 session_->CreateAnswer(observer, session_options);
1009}
1010
1011void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1012 const RTCOfferAnswerOptions& options) {
1013 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1014 if (!VERIFY(observer != nullptr)) {
1015 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1016 return;
1017 }
1018
1019 cricket::MediaSessionOptions session_options;
1020 if (!GetOptionsForAnswer(options, &session_options)) {
1021 std::string error = "CreateAnswer called with invalid options.";
1022 LOG(LS_ERROR) << error;
1023 PostCreateSessionDescriptionFailure(observer, error);
1024 return;
1025 }
1026
1027 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028}
1029
1030void PeerConnection::SetLocalDescription(
1031 SetSessionDescriptionObserver* observer,
1032 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001033 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001034 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1036 return;
1037 }
1038 if (!desc) {
1039 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1040 return;
1041 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042 // Update stats here so that we have the most recent stats for tracks and
1043 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001044 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 std::string error;
1046 if (!session_->SetLocalDescription(desc, &error)) {
1047 PostSetSessionDescriptionFailure(observer, error);
1048 return;
1049 }
deadbeefab9b2d12015-10-14 11:33:11 -07001050
1051 // If setting the description decided our SSL role, allocate any necessary
1052 // SCTP sids.
1053 rtc::SSLRole role;
1054 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001055 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001056 AllocateSctpSids(role);
1057 }
1058
1059 // Update state and SSRC of local MediaStreams and DataChannels based on the
1060 // local session description.
1061 const cricket::ContentInfo* audio_content =
1062 GetFirstAudioContent(desc->description());
1063 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001064 if (audio_content->rejected) {
1065 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1066 } else {
1067 const cricket::AudioContentDescription* audio_desc =
1068 static_cast<const cricket::AudioContentDescription*>(
1069 audio_content->description);
1070 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1071 }
deadbeefab9b2d12015-10-14 11:33:11 -07001072 }
1073
1074 const cricket::ContentInfo* video_content =
1075 GetFirstVideoContent(desc->description());
1076 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001077 if (video_content->rejected) {
1078 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1079 } else {
1080 const cricket::VideoContentDescription* video_desc =
1081 static_cast<const cricket::VideoContentDescription*>(
1082 video_content->description);
1083 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1084 }
deadbeefab9b2d12015-10-14 11:33:11 -07001085 }
1086
1087 const cricket::ContentInfo* data_content =
1088 GetFirstDataContent(desc->description());
1089 if (data_content) {
1090 const cricket::DataContentDescription* data_desc =
1091 static_cast<const cricket::DataContentDescription*>(
1092 data_content->description);
1093 if (rtc::starts_with(data_desc->protocol().data(),
1094 cricket::kMediaProtocolRtpPrefix)) {
1095 UpdateLocalRtpDataChannels(data_desc->streams());
1096 }
1097 }
1098
1099 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001100 signaling_thread()->Post(RTC_FROM_HERE, this,
1101 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001102
deadbeefcbecd352015-09-23 11:50:27 -07001103 // MaybeStartGathering needs to be called after posting
1104 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1105 // before signaling that SetLocalDescription completed.
1106 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001107}
1108
1109void PeerConnection::SetRemoteDescription(
1110 SetSessionDescriptionObserver* observer,
1111 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001112 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001113 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001114 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1115 return;
1116 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001117 if (!desc) {
1118 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1119 return;
1120 }
1121 // Update stats here so that we have the most recent stats for tracks and
1122 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001123 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001124 std::string error;
1125 if (!session_->SetRemoteDescription(desc, &error)) {
1126 PostSetSessionDescriptionFailure(observer, error);
1127 return;
1128 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129
deadbeefab9b2d12015-10-14 11:33:11 -07001130 // If setting the description decided our SSL role, allocate any necessary
1131 // SCTP sids.
1132 rtc::SSLRole role;
1133 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001134 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001135 AllocateSctpSids(role);
1136 }
1137
1138 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001139 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1140 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1141 const cricket::AudioContentDescription* audio_desc =
1142 GetFirstAudioContentDescription(remote_desc);
1143 const cricket::VideoContentDescription* video_desc =
1144 GetFirstVideoContentDescription(remote_desc);
1145 const cricket::DataContentDescription* data_desc =
1146 GetFirstDataContentDescription(remote_desc);
1147
1148 // Check if the descriptions include streams, just in case the peer supports
1149 // MSID, but doesn't indicate so with "a=msid-semantic".
1150 if (remote_desc->msid_supported() ||
1151 (audio_desc && !audio_desc->streams().empty()) ||
1152 (video_desc && !video_desc->streams().empty())) {
1153 remote_peer_supports_msid_ = true;
1154 }
deadbeefab9b2d12015-10-14 11:33:11 -07001155
1156 // We wait to signal new streams until we finish processing the description,
1157 // since only at that point will new streams have all their tracks.
1158 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1159
1160 // Find all audio rtp streams and create corresponding remote AudioTracks
1161 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001162 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001163 if (audio_content->rejected) {
1164 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1165 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001166 bool default_audio_track_needed =
1167 !remote_peer_supports_msid_ &&
1168 MediaContentDirectionHasSend(audio_desc->direction());
1169 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1170 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001171 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001172 }
deadbeefab9b2d12015-10-14 11:33:11 -07001173 }
1174
1175 // Find all video rtp streams and create corresponding remote VideoTracks
1176 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001177 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001178 if (video_content->rejected) {
1179 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1180 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001181 bool default_video_track_needed =
1182 !remote_peer_supports_msid_ &&
1183 MediaContentDirectionHasSend(video_desc->direction());
1184 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1185 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001186 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001187 }
deadbeefab9b2d12015-10-14 11:33:11 -07001188 }
1189
1190 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001191 if (data_desc) {
1192 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001193 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001194 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001195 }
1196 }
1197
1198 // Iterate new_streams and notify the observer about new MediaStreams.
1199 for (size_t i = 0; i < new_streams->count(); ++i) {
1200 MediaStreamInterface* new_stream = new_streams->at(i);
1201 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001202 // Call both the raw pointer and scoped_refptr versions of the method
1203 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001204 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001205 observer_->OnAddStream(
1206 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001207 }
1208
deadbeefbda7e0b2015-12-08 17:13:40 -08001209 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001210
1211 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001212 signaling_thread()->Post(RTC_FROM_HERE, this,
1213 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001214}
1215
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001216bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001217 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001218 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001219 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001220 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001221 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001222 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001223 return false;
1224 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001225 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001226
1227 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1228 session_->SetIceConfig(session_->ParseIceConfig(configuration));
1229 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001230}
1231
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001232bool PeerConnection::AddIceCandidate(
1233 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001234 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 return session_->ProcessIceMessage(ice_candidate);
1236}
1237
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001238bool PeerConnection::RemoveIceCandidates(
1239 const std::vector<cricket::Candidate>& candidates) {
1240 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1241 return session_->RemoveRemoteIceCandidates(candidates);
1242}
1243
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001244void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001245 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001246 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001247
1248 if (session_) {
1249 session_->set_metrics_observer(uma_observer_);
1250 }
1251
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001252 // Send information about IPv4/IPv6 status.
1253 if (uma_observer_ && port_allocator_) {
1254 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001255 uma_observer_->IncrementEnumCounter(
1256 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1257 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001258 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001259 uma_observer_->IncrementEnumCounter(
1260 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1261 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001262 }
1263 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001264}
1265
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266const SessionDescriptionInterface* PeerConnection::local_description() const {
1267 return session_->local_description();
1268}
1269
1270const SessionDescriptionInterface* PeerConnection::remote_description() const {
1271 return session_->remote_description();
1272}
1273
1274void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001275 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 // Update stats here so that we have the most recent stats for tracks and
1277 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001278 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001279
deadbeefd59daf82015-10-14 15:02:44 -07001280 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281}
1282
deadbeefd59daf82015-10-14 15:02:44 -07001283void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1284 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001286 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001288 break;
deadbeefd59daf82015-10-14 15:02:44 -07001289 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1291 break;
deadbeefd59daf82015-10-14 15:02:44 -07001292 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1294 break;
deadbeefd59daf82015-10-14 15:02:44 -07001295 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1297 break;
deadbeefd59daf82015-10-14 15:02:44 -07001298 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1300 break;
deadbeefd59daf82015-10-14 15:02:44 -07001301 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 ChangeSignalingState(PeerConnectionInterface::kStable);
1303 break;
deadbeefd59daf82015-10-14 15:02:44 -07001304 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 ChangeSignalingState(PeerConnectionInterface::kClosed);
1306 break;
1307 default:
1308 break;
1309 }
1310}
1311
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001312void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1315 SetSessionDescriptionMsg* param =
1316 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1317 param->observer->OnSuccess();
1318 delete param;
1319 break;
1320 }
1321 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1322 SetSessionDescriptionMsg* param =
1323 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1324 param->observer->OnFailure(param->error);
1325 delete param;
1326 break;
1327 }
deadbeefab9b2d12015-10-14 11:33:11 -07001328 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1329 CreateSessionDescriptionMsg* param =
1330 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1331 param->observer->OnFailure(param->error);
1332 delete param;
1333 break;
1334 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335 case MSG_GETSTATS: {
1336 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001337 StatsReports reports;
1338 stats_->GetStats(param->track, &reports);
1339 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340 delete param;
1341 break;
1342 }
deadbeefbd292462015-12-14 18:15:29 -08001343 case MSG_FREE_DATACHANNELS: {
1344 sctp_data_channels_to_free_.clear();
1345 break;
1346 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001348 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 break;
1350 }
1351}
1352
deadbeefab9b2d12015-10-14 11:33:11 -07001353void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001354 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001355 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001356 receivers_.push_back(
1357 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001358 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
1359 session_->voice_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360}
1361
deadbeefab9b2d12015-10-14 11:33:11 -07001362void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001363 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001364 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001365 receivers_.push_back(
1366 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1367 signaling_thread(),
1368 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001369 ssrc, session_->video_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
deadbeef70ab1a12015-09-28 16:53:55 -07001372// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1373// description.
perkjd61bf802016-03-24 03:16:19 -07001374void PeerConnection::DestroyReceiver(const std::string& track_id) {
1375 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001376 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001377 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001378 << " doesn't exist.";
1379 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001380 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001381 receivers_.erase(it);
1382 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383}
1384
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385void PeerConnection::OnIceConnectionChange(
1386 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001387 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001388 // After transitioning to "closed", ignore any additional states from
1389 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001390 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001391 return;
1392 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001394 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395}
1396
1397void PeerConnection::OnIceGatheringChange(
1398 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001399 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400 if (IsClosed()) {
1401 return;
1402 }
1403 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001404 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405}
1406
1407void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001408 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001409 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410}
1411
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001412void PeerConnection::OnIceCandidatesRemoved(
1413 const std::vector<cricket::Candidate>& candidates) {
1414 RTC_DCHECK(signaling_thread()->IsCurrent());
1415 observer_->OnIceCandidatesRemoved(candidates);
1416}
1417
Peter Thatcher54360512015-07-08 11:08:35 -07001418void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001419 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001420 observer_->OnIceConnectionReceivingChange(receiving);
1421}
1422
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001423void PeerConnection::ChangeSignalingState(
1424 PeerConnectionInterface::SignalingState signaling_state) {
1425 signaling_state_ = signaling_state;
1426 if (signaling_state == kClosed) {
1427 ice_connection_state_ = kIceConnectionClosed;
1428 observer_->OnIceConnectionChange(ice_connection_state_);
1429 if (ice_gathering_state_ != kIceGatheringComplete) {
1430 ice_gathering_state_ = kIceGatheringComplete;
1431 observer_->OnIceGatheringChange(ice_gathering_state_);
1432 }
1433 }
1434 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435}
1436
deadbeefeb459812015-12-15 19:24:43 -08001437void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1438 MediaStreamInterface* stream) {
1439 auto sender = FindSenderForTrack(track);
1440 if (sender != senders_.end()) {
1441 // We already have a sender for this track, so just change the stream_id
1442 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001443 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001444 return;
1445 }
1446
1447 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001448 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1449 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001450 signaling_thread(),
1451 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1452 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001453 senders_.push_back(new_sender);
1454 // If the sender has already been configured in SDP, we call SetSsrc,
1455 // which will connect the sender to the underlying transport. This can
1456 // occur if a local session description that contains the ID of the sender
1457 // is set before AddStream is called. It can also occur if the local
1458 // session description is not changed and RemoveStream is called, and
1459 // later AddStream is called again with the same stream.
1460 const TrackInfo* track_info =
1461 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1462 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001463 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001464 }
1465}
1466
1467// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1468// indefinitely, when we have unified plan SDP.
1469void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1470 MediaStreamInterface* stream) {
1471 auto sender = FindSenderForTrack(track);
1472 if (sender == senders_.end()) {
1473 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1474 << " doesn't exist.";
1475 return;
1476 }
deadbeefa601f5c2016-06-06 14:27:39 -07001477 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001478 senders_.erase(sender);
1479}
1480
1481void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1482 MediaStreamInterface* stream) {
1483 auto sender = FindSenderForTrack(track);
1484 if (sender != senders_.end()) {
1485 // We already have a sender for this track, so just change the stream_id
1486 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001487 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001488 return;
1489 }
1490
1491 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001492 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1493 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001494 signaling_thread(), new VideoRtpSender(track, stream->label(),
1495 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001496 senders_.push_back(new_sender);
1497 const TrackInfo* track_info =
1498 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1499 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001500 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001501 }
1502}
1503
1504void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1505 MediaStreamInterface* stream) {
1506 auto sender = FindSenderForTrack(track);
1507 if (sender == senders_.end()) {
1508 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1509 << " doesn't exist.";
1510 return;
1511 }
deadbeefa601f5c2016-06-06 14:27:39 -07001512 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001513 senders_.erase(sender);
1514}
1515
deadbeefab9b2d12015-10-14 11:33:11 -07001516void PeerConnection::PostSetSessionDescriptionFailure(
1517 SetSessionDescriptionObserver* observer,
1518 const std::string& error) {
1519 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1520 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001521 signaling_thread()->Post(RTC_FROM_HERE, this,
1522 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001523}
1524
1525void PeerConnection::PostCreateSessionDescriptionFailure(
1526 CreateSessionDescriptionObserver* observer,
1527 const std::string& error) {
1528 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1529 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001530 signaling_thread()->Post(RTC_FROM_HERE, this,
1531 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001532}
1533
1534bool PeerConnection::GetOptionsForOffer(
1535 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1536 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001537 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1538 // ContentInfos.
1539 if (session_->local_description()) {
1540 for (const cricket::ContentInfo& content :
1541 session_->local_description()->description()->contents()) {
1542 session_options->transport_options[content.name] =
1543 cricket::TransportOptions();
1544 }
1545 }
htaaac2dea2016-03-10 13:35:55 -08001546 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001547 return false;
1548 }
1549
deadbeeffac06552015-11-25 11:26:01 -08001550 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001551 // Offer to receive audio/video if the constraint is not set and there are
1552 // send streams, or we're currently receiving.
1553 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1554 session_options->recv_audio =
1555 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1556 !remote_audio_tracks_.empty();
1557 }
1558 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1559 session_options->recv_video =
1560 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1561 !remote_video_tracks_.empty();
1562 }
1563 session_options->bundle_enabled =
1564 session_options->bundle_enabled &&
1565 (session_options->has_audio() || session_options->has_video() ||
1566 session_options->has_data());
1567
deadbeefab9b2d12015-10-14 11:33:11 -07001568 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1569 session_options->data_channel_type = cricket::DCT_SCTP;
1570 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001571
1572 session_options->rtcp_cname = rtcp_cname_;
deadbeefab9b2d12015-10-14 11:33:11 -07001573 return true;
1574}
1575
htaa2a49d92016-03-04 02:51:39 -08001576void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001577 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001578 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1579 // ContentInfos.
1580 if (session_->remote_description()) {
1581 // Initialize the transport_options map.
1582 for (const cricket::ContentInfo& content :
1583 session_->remote_description()->description()->contents()) {
1584 session_options->transport_options[content.name] =
1585 cricket::TransportOptions();
1586 }
1587 }
deadbeeffac06552015-11-25 11:26:01 -08001588 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001589 session_options->bundle_enabled =
1590 session_options->bundle_enabled &&
1591 (session_options->has_audio() || session_options->has_video() ||
1592 session_options->has_data());
1593
deadbeefab9b2d12015-10-14 11:33:11 -07001594 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1595 // are not signaled in the SDP so does not go through that path and must be
1596 // handled here.
1597 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1598 session_options->data_channel_type = cricket::DCT_SCTP;
1599 }
htaa2a49d92016-03-04 02:51:39 -08001600}
1601
1602bool PeerConnection::GetOptionsForAnswer(
1603 const MediaConstraintsInterface* constraints,
1604 cricket::MediaSessionOptions* session_options) {
1605 session_options->recv_audio = false;
1606 session_options->recv_video = false;
1607 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1608 return false;
1609 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001610 session_options->rtcp_cname = rtcp_cname_;
1611
htaa2a49d92016-03-04 02:51:39 -08001612 FinishOptionsForAnswer(session_options);
1613 return true;
1614}
1615
1616bool PeerConnection::GetOptionsForAnswer(
1617 const RTCOfferAnswerOptions& options,
1618 cricket::MediaSessionOptions* session_options) {
1619 session_options->recv_audio = false;
1620 session_options->recv_video = false;
htaaac2dea2016-03-10 13:35:55 -08001621 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001622 return false;
1623 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001624 session_options->rtcp_cname = rtcp_cname_;
1625
htaa2a49d92016-03-04 02:51:39 -08001626 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001627 return true;
1628}
1629
deadbeeffaac4972015-11-12 15:33:07 -08001630void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1631 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001632 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1633 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001634}
1635
deadbeefab9b2d12015-10-14 11:33:11 -07001636void PeerConnection::UpdateRemoteStreamsList(
1637 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001638 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001639 cricket::MediaType media_type,
1640 StreamCollection* new_streams) {
1641 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1642
1643 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001644 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001645 auto track_it = current_tracks->begin();
1646 while (track_it != current_tracks->end()) {
1647 const TrackInfo& info = *track_it;
1648 const cricket::StreamParams* params =
1649 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001650 bool track_exists = params && params->id == info.track_id;
1651 // If this is a default track, and we still need it, don't remove it.
1652 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1653 track_exists) {
1654 ++track_it;
1655 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001656 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1657 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001658 }
1659 }
1660
1661 // Find new and active tracks.
1662 for (const cricket::StreamParams& params : streams) {
1663 // The sync_label is the MediaStream label and the |stream.id| is the
1664 // track id.
1665 const std::string& stream_label = params.sync_label;
1666 const std::string& track_id = params.id;
1667 uint32_t ssrc = params.first_ssrc();
1668
1669 rtc::scoped_refptr<MediaStreamInterface> stream =
1670 remote_streams_->find(stream_label);
1671 if (!stream) {
1672 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001673 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1674 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001675 remote_streams_->AddStream(stream);
1676 new_streams->AddStream(stream);
1677 }
1678
1679 const TrackInfo* track_info =
1680 FindTrackInfo(*current_tracks, stream_label, track_id);
1681 if (!track_info) {
1682 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1683 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1684 }
1685 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001686
1687 // Add default track if necessary.
1688 if (default_track_needed) {
1689 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1690 remote_streams_->find(kDefaultStreamLabel);
1691 if (!default_stream) {
1692 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001693 default_stream = MediaStreamProxy::Create(
1694 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001695 remote_streams_->AddStream(default_stream);
1696 new_streams->AddStream(default_stream);
1697 }
1698 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1699 ? kDefaultAudioTrackLabel
1700 : kDefaultVideoTrackLabel;
1701 const TrackInfo* default_track_info =
1702 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1703 if (!default_track_info) {
1704 current_tracks->push_back(
1705 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1706 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1707 }
1708 }
deadbeefab9b2d12015-10-14 11:33:11 -07001709}
1710
1711void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1712 const std::string& track_id,
1713 uint32_t ssrc,
1714 cricket::MediaType media_type) {
1715 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1716
1717 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001718 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001719 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001720 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001721 } else {
1722 RTC_DCHECK(false && "Invalid media type");
1723 }
1724}
1725
1726void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1727 const std::string& track_id,
1728 cricket::MediaType media_type) {
1729 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1730
1731 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001732 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1733 // will be notified which will end the AudioRtpReceiver::track().
1734 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001735 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1736 stream->FindAudioTrack(track_id);
1737 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001738 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001739 }
1740 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001741 // Stopping or destroying a VideoRtpReceiver will end the
1742 // VideoRtpReceiver::track().
1743 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001744 rtc::scoped_refptr<VideoTrackInterface> video_track =
1745 stream->FindVideoTrack(track_id);
1746 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001747 // There's no guarantee the track is still available, e.g. the track may
1748 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001749 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001750 }
1751 } else {
1752 ASSERT(false && "Invalid media type");
1753 }
1754}
1755
1756void PeerConnection::UpdateEndedRemoteMediaStreams() {
1757 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1758 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1759 MediaStreamInterface* stream = remote_streams_->at(i);
1760 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1761 streams_to_remove.push_back(stream);
1762 }
1763 }
1764
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001765 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001766 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001767 // Call both the raw pointer and scoped_refptr versions of the method
1768 // for compatibility.
1769 observer_->OnRemoveStream(stream.get());
1770 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001771 }
1772}
1773
deadbeefab9b2d12015-10-14 11:33:11 -07001774void PeerConnection::UpdateLocalTracks(
1775 const std::vector<cricket::StreamParams>& streams,
1776 cricket::MediaType media_type) {
1777 TrackInfos* current_tracks = GetLocalTracks(media_type);
1778
1779 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1780 // don't match the new StreamParam.
1781 TrackInfos::iterator track_it = current_tracks->begin();
1782 while (track_it != current_tracks->end()) {
1783 const TrackInfo& info = *track_it;
1784 const cricket::StreamParams* params =
1785 cricket::GetStreamBySsrc(streams, info.ssrc);
1786 if (!params || params->id != info.track_id ||
1787 params->sync_label != info.stream_label) {
1788 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1789 media_type);
1790 track_it = current_tracks->erase(track_it);
1791 } else {
1792 ++track_it;
1793 }
1794 }
1795
1796 // Find new and active tracks.
1797 for (const cricket::StreamParams& params : streams) {
1798 // The sync_label is the MediaStream label and the |stream.id| is the
1799 // track id.
1800 const std::string& stream_label = params.sync_label;
1801 const std::string& track_id = params.id;
1802 uint32_t ssrc = params.first_ssrc();
1803 const TrackInfo* track_info =
1804 FindTrackInfo(*current_tracks, stream_label, track_id);
1805 if (!track_info) {
1806 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1807 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1808 }
1809 }
1810}
1811
1812void PeerConnection::OnLocalTrackSeen(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 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1819 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001820 return;
1821 }
1822
deadbeeffac06552015-11-25 11:26:01 -08001823 if (sender->media_type() != media_type) {
1824 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1825 << " description with an unexpected media type.";
1826 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001827 }
deadbeeffac06552015-11-25 11:26:01 -08001828
1829 sender->set_stream_id(stream_label);
1830 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001831}
1832
1833void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1834 const std::string& track_id,
1835 uint32_t ssrc,
1836 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001837 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001838 if (!sender) {
1839 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001840 // SessionDescriptions has been renegotiated.
1841 return;
1842 }
deadbeeffac06552015-11-25 11:26:01 -08001843
1844 // A sender has been removed from the SessionDescription but it's still
1845 // associated with the PeerConnection. This only occurs if the SDP doesn't
1846 // match with the calls to CreateSender, AddStream and RemoveStream.
1847 if (sender->media_type() != media_type) {
1848 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1849 << " description with an unexpected media type.";
1850 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001851 }
deadbeeffac06552015-11-25 11:26:01 -08001852
1853 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001854}
1855
1856void PeerConnection::UpdateLocalRtpDataChannels(
1857 const cricket::StreamParamsVec& streams) {
1858 std::vector<std::string> existing_channels;
1859
1860 // Find new and active data channels.
1861 for (const cricket::StreamParams& params : streams) {
1862 // |it->sync_label| is actually the data channel label. The reason is that
1863 // we use the same naming of data channels as we do for
1864 // MediaStreams and Tracks.
1865 // For MediaStreams, the sync_label is the MediaStream label and the
1866 // track label is the same as |streamid|.
1867 const std::string& channel_label = params.sync_label;
1868 auto data_channel_it = rtp_data_channels_.find(channel_label);
1869 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1870 continue;
1871 }
1872 // Set the SSRC the data channel should use for sending.
1873 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1874 existing_channels.push_back(data_channel_it->first);
1875 }
1876
1877 UpdateClosingRtpDataChannels(existing_channels, true);
1878}
1879
1880void PeerConnection::UpdateRemoteRtpDataChannels(
1881 const cricket::StreamParamsVec& streams) {
1882 std::vector<std::string> existing_channels;
1883
1884 // Find new and active data channels.
1885 for (const cricket::StreamParams& params : streams) {
1886 // The data channel label is either the mslabel or the SSRC if the mslabel
1887 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1888 std::string label = params.sync_label.empty()
1889 ? rtc::ToString(params.first_ssrc())
1890 : params.sync_label;
1891 auto data_channel_it = rtp_data_channels_.find(label);
1892 if (data_channel_it == rtp_data_channels_.end()) {
1893 // This is a new data channel.
1894 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1895 } else {
1896 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1897 }
1898 existing_channels.push_back(label);
1899 }
1900
1901 UpdateClosingRtpDataChannels(existing_channels, false);
1902}
1903
1904void PeerConnection::UpdateClosingRtpDataChannels(
1905 const std::vector<std::string>& active_channels,
1906 bool is_local_update) {
1907 auto it = rtp_data_channels_.begin();
1908 while (it != rtp_data_channels_.end()) {
1909 DataChannel* data_channel = it->second;
1910 if (std::find(active_channels.begin(), active_channels.end(),
1911 data_channel->label()) != active_channels.end()) {
1912 ++it;
1913 continue;
1914 }
1915
1916 if (is_local_update) {
1917 data_channel->SetSendSsrc(0);
1918 } else {
1919 data_channel->RemotePeerRequestClose();
1920 }
1921
1922 if (data_channel->state() == DataChannel::kClosed) {
1923 rtp_data_channels_.erase(it);
1924 it = rtp_data_channels_.begin();
1925 } else {
1926 ++it;
1927 }
1928 }
1929}
1930
1931void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1932 uint32_t remote_ssrc) {
1933 rtc::scoped_refptr<DataChannel> channel(
1934 InternalCreateDataChannel(label, nullptr));
1935 if (!channel.get()) {
1936 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1937 << "CreateDataChannel failed.";
1938 return;
1939 }
1940 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07001941 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
1942 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001943 // Call both the raw pointer and scoped_refptr versions of the method
1944 // for compatibility.
1945 observer_->OnDataChannel(proxy_channel.get());
1946 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07001947}
1948
1949rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1950 const std::string& label,
1951 const InternalDataChannelInit* config) {
1952 if (IsClosed()) {
1953 return nullptr;
1954 }
1955 if (session_->data_channel_type() == cricket::DCT_NONE) {
1956 LOG(LS_ERROR)
1957 << "InternalCreateDataChannel: Data is not supported in this call.";
1958 return nullptr;
1959 }
1960 InternalDataChannelInit new_config =
1961 config ? (*config) : InternalDataChannelInit();
1962 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1963 if (new_config.id < 0) {
1964 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001965 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07001966 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1967 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1968 return nullptr;
1969 }
1970 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1971 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1972 << "because the id is already in use or out of range.";
1973 return nullptr;
1974 }
1975 }
1976
1977 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1978 session_.get(), session_->data_channel_type(), label, new_config));
1979 if (!channel) {
1980 sid_allocator_.ReleaseSid(new_config.id);
1981 return nullptr;
1982 }
1983
1984 if (channel->data_channel_type() == cricket::DCT_RTP) {
1985 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1986 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1987 << " already exists.";
1988 return nullptr;
1989 }
1990 rtp_data_channels_[channel->label()] = channel;
1991 } else {
1992 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1993 sctp_data_channels_.push_back(channel);
1994 channel->SignalClosed.connect(this,
1995 &PeerConnection::OnSctpDataChannelClosed);
1996 }
1997
1998 return channel;
1999}
2000
2001bool PeerConnection::HasDataChannels() const {
2002 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2003}
2004
2005void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2006 for (const auto& channel : sctp_data_channels_) {
2007 if (channel->id() < 0) {
2008 int sid;
2009 if (!sid_allocator_.AllocateSid(role, &sid)) {
2010 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2011 continue;
2012 }
2013 channel->SetSctpSid(sid);
2014 }
2015 }
2016}
2017
2018void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002019 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002020 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2021 ++it) {
2022 if (it->get() == channel) {
2023 if (channel->id() >= 0) {
2024 sid_allocator_.ReleaseSid(channel->id());
2025 }
deadbeefbd292462015-12-14 18:15:29 -08002026 // Since this method is triggered by a signal from the DataChannel,
2027 // we can't free it directly here; we need to free it asynchronously.
2028 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002029 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002030 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2031 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002032 return;
2033 }
2034 }
2035}
2036
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002037void PeerConnection::OnVoiceChannelCreated() {
2038 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2039 session_->voice_channel(), senders_, receivers_,
2040 cricket::MEDIA_TYPE_AUDIO);
2041}
2042
deadbeefab9b2d12015-10-14 11:33:11 -07002043void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002044 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2045 cricket::VoiceChannel>(
2046 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2047}
2048
2049void PeerConnection::OnVideoChannelCreated() {
2050 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2051 session_->video_channel(), senders_, receivers_,
2052 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002053}
2054
2055void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002056 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2057 cricket::VideoChannel>(
2058 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002059}
2060
2061void PeerConnection::OnDataChannelCreated() {
2062 for (const auto& channel : sctp_data_channels_) {
2063 channel->OnTransportChannelCreated();
2064 }
2065}
2066
2067void PeerConnection::OnDataChannelDestroyed() {
2068 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2069 // DataChannel may callback to us and try to modify the list.
2070 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2071 temp_rtp_dcs.swap(rtp_data_channels_);
2072 for (const auto& kv : temp_rtp_dcs) {
2073 kv.second->OnTransportChannelDestroyed();
2074 }
2075
2076 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2077 temp_sctp_dcs.swap(sctp_data_channels_);
2078 for (const auto& channel : temp_sctp_dcs) {
2079 channel->OnTransportChannelDestroyed();
2080 }
2081}
2082
2083void PeerConnection::OnDataChannelOpenMessage(
2084 const std::string& label,
2085 const InternalDataChannelInit& config) {
2086 rtc::scoped_refptr<DataChannel> channel(
2087 InternalCreateDataChannel(label, &config));
2088 if (!channel.get()) {
2089 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2090 return;
2091 }
2092
deadbeefa601f5c2016-06-06 14:27:39 -07002093 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2094 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002095 // Call both the raw pointer and scoped_refptr versions of the method
2096 // for compatibility.
2097 observer_->OnDataChannel(proxy_channel.get());
2098 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002099}
2100
deadbeefa601f5c2016-06-06 14:27:39 -07002101RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2102 auto it = std::find_if(
2103 senders_.begin(), senders_.end(),
2104 [id](const rtc::scoped_refptr<
2105 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2106 return sender->id() == id;
2107 });
2108 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002109}
2110
deadbeefa601f5c2016-06-06 14:27:39 -07002111std::vector<
2112 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002113PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2114 return std::find_if(
2115 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002116 [track](const rtc::scoped_refptr<
2117 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002118 return sender->track() == track;
2119 });
2120}
2121
deadbeefa601f5c2016-06-06 14:27:39 -07002122std::vector<rtc::scoped_refptr<
2123 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002124PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002125 return std::find_if(
2126 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002127 [track_id](const rtc::scoped_refptr<
2128 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002129 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002130 });
2131}
2132
deadbeefab9b2d12015-10-14 11:33:11 -07002133PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2134 cricket::MediaType media_type) {
2135 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2136 media_type == cricket::MEDIA_TYPE_VIDEO);
2137 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2138 : &remote_video_tracks_;
2139}
2140
2141PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2142 cricket::MediaType media_type) {
2143 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2144 media_type == cricket::MEDIA_TYPE_VIDEO);
2145 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2146 : &local_video_tracks_;
2147}
2148
2149const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2150 const PeerConnection::TrackInfos& infos,
2151 const std::string& stream_label,
2152 const std::string track_id) const {
2153 for (const TrackInfo& track_info : infos) {
2154 if (track_info.stream_label == stream_label &&
2155 track_info.track_id == track_id) {
2156 return &track_info;
2157 }
2158 }
2159 return nullptr;
2160}
2161
2162DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2163 for (const auto& channel : sctp_data_channels_) {
2164 if (channel->id() == sid) {
2165 return channel;
2166 }
2167 }
2168 return nullptr;
2169}
2170
deadbeef91dd5672016-05-18 16:55:30 -07002171bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002172 const RTCConfiguration& configuration) {
2173 cricket::ServerAddresses stun_servers;
2174 std::vector<cricket::RelayServerConfig> turn_servers;
2175 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2176 return false;
2177 }
2178
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002179 port_allocator_->Initialize();
2180
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002181 // To handle both internal and externally created port allocator, we will
2182 // enable BUNDLE here.
2183 int portallocator_flags = port_allocator_->flags();
2184 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2185 cricket::PORTALLOCATOR_ENABLE_IPV6;
2186 // If the disable-IPv6 flag was specified, we'll not override it
2187 // by experiment.
2188 if (configuration.disable_ipv6) {
2189 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2190 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2191 "Disabled") {
2192 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2193 }
2194
2195 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2196 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2197 LOG(LS_INFO) << "TCP candidates are disabled.";
2198 }
2199
honghaiz60347052016-05-31 18:29:12 -07002200 if (configuration.candidate_network_policy ==
2201 kCandidateNetworkPolicyLowCost) {
2202 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2203 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2204 }
2205
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002206 port_allocator_->set_flags(portallocator_flags);
2207 // No step delay is used while allocating ports.
2208 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2209 port_allocator_->set_candidate_filter(
2210 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2211
2212 // Call this last since it may create pooled allocator sessions using the
2213 // properties set above.
2214 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002215 configuration.ice_candidate_pool_size,
2216 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002217 return true;
2218}
2219
deadbeef91dd5672016-05-18 16:55:30 -07002220bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002221 const RTCConfiguration& configuration) {
2222 cricket::ServerAddresses stun_servers;
2223 std::vector<cricket::RelayServerConfig> turn_servers;
2224 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2225 return false;
2226 }
2227 port_allocator_->set_candidate_filter(
2228 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2229 // Call this last since it may create pooled allocator sessions using the
2230 // candidate filter set above.
2231 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002232 configuration.ice_candidate_pool_size,
2233 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002234 return true;
2235}
2236
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002237} // namespace webrtc