blob: c493f40c9ce87ae35b0096aea4e156e5c70c73f2 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Henrik Kjellander15583c12016-02-10 10:53:12 +010011#include "webrtc/api/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070014#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Henrik Kjellander15583c12016-02-10 10:53:12 +010018#include "webrtc/api/audiotrack.h"
19#include "webrtc/api/dtmfsender.h"
20#include "webrtc/api/jsepicecandidate.h"
21#include "webrtc/api/jsepsessiondescription.h"
22#include "webrtc/api/mediaconstraintsinterface.h"
23#include "webrtc/api/mediastream.h"
24#include "webrtc/api/mediastreamobserver.h"
25#include "webrtc/api/mediastreamproxy.h"
26#include "webrtc/api/mediastreamtrackproxy.h"
27#include "webrtc/api/remoteaudiosource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010028#include "webrtc/api/rtpreceiver.h"
29#include "webrtc/api/rtpsender.h"
30#include "webrtc/api/streamcollection.h"
perkja3ede6c2016-03-08 01:27:48 +010031#include "webrtc/api/videocapturertracksource.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010032#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080033#include "webrtc/base/arraysize.h"
ivoc14d5dbe2016-07-04 07:06:55 -070034#include "webrtc/base/bind.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000035#include "webrtc/base/logging.h"
36#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070037#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010038#include "webrtc/base/trace_event.h"
ivoc14d5dbe2016-07-04 07:06:55 -070039#include "webrtc/call.h"
kjellandera96e2d72016-02-04 23:52:28 -080040#include "webrtc/media/sctp/sctpdataengine.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010041#include "webrtc/pc/channelmanager.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010042#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043
44namespace {
45
deadbeefab9b2d12015-10-14 11:33:11 -070046using webrtc::DataChannel;
47using webrtc::MediaConstraintsInterface;
48using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000049using webrtc::PeerConnectionInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070050using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080051using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070052using webrtc::RtpSenderProxy;
53using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070054using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
deadbeefab9b2d12015-10-14 11:33:11 -070056static const char kDefaultStreamLabel[] = "default";
57static const char kDefaultAudioTrackLabel[] = "defaulta0";
58static const char kDefaultVideoTrackLabel[] = "defaultv0";
59
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060// The min number of tokens must present in Turn host uri.
61// e.g. user@turn.example.org
62static const size_t kTurnHostTokensNum = 2;
63// Number of tokens must be preset when TURN uri has transport param.
64static const size_t kTurnTransportTokensNum = 2;
65// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000066static const int kDefaultStunPort = 3478;
67static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069
70// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070071static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072
zhihuang8f65cdf2016-05-06 18:40:30 -070073// The length of RTCP CNAMEs.
74static const int kRtcpCnameLength = 16;
75
deadbeef0a6c4ca2015-10-06 11:38:28 -070076// NOTE: A loop below assumes that the first value of this enum is 0 and all
77// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070079 STUN = 0, // Indicates a STUN server.
80 STUNS, // Indicates a STUN server used with a TLS session.
81 TURN, // Indicates a TURN server
82 TURNS, // Indicates a TURN server used with a TLS session.
83 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000084};
tfarina5237aaf2015-11-10 23:44:30 -080085static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070086 "kValidIceServiceTypes must have as many strings as ServiceType "
87 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
89enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000090 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070092 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080094 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095};
96
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000097struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098 explicit SetSessionDescriptionMsg(
99 webrtc::SetSessionDescriptionObserver* observer)
100 : observer(observer) {
101 }
102
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000103 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 std::string error;
105};
106
deadbeefab9b2d12015-10-14 11:33:11 -0700107struct CreateSessionDescriptionMsg : public rtc::MessageData {
108 explicit CreateSessionDescriptionMsg(
109 webrtc::CreateSessionDescriptionObserver* observer)
110 : observer(observer) {}
111
112 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
113 std::string error;
114};
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000117 GetStatsMsg(webrtc::StatsObserver* observer,
118 webrtc::MediaStreamTrackInterface* track)
119 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000120 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000121 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000122 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000123};
124
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000125// |in_str| should be of format
126// stunURI = scheme ":" stun-host [ ":" stun-port ]
127// scheme = "stun" / "stuns"
128// stun-host = IP-literal / IPv4address / reg-name
129// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700130//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000131// draft-petithuguenin-behave-turn-uris-01
132// turnURI = scheme ":" turn-host [ ":" turn-port ]
133// turn-host = username@IP-literal / IPv4address / reg-name
134bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
135 ServiceType* service_type,
136 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200137 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700138 if (colonpos == std::string::npos) {
139 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000140 return false;
141 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700142 if ((colonpos + 1) == in_str.length()) {
143 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
144 return false;
145 }
146 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800147 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700148 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000149 *service_type = static_cast<ServiceType>(i);
150 break;
151 }
152 }
153 if (*service_type == INVALID) {
154 return false;
155 }
156 *hostname = in_str.substr(colonpos + 1, std::string::npos);
157 return true;
158}
159
deadbeef0a6c4ca2015-10-06 11:38:28 -0700160bool ParsePort(const std::string& in_str, int* port) {
161 // Make sure port only contains digits. FromString doesn't check this.
162 for (const char& c : in_str) {
163 if (!std::isdigit(c)) {
164 return false;
165 }
166 }
167 return rtc::FromString(in_str, port);
168}
169
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000170// This method parses IPv6 and IPv4 literal strings, along with hostnames in
171// standard hostname:port format.
172// Consider following formats as correct.
173// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700174// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000175bool ParseHostnameAndPortFromString(const std::string& in_str,
176 std::string* host,
177 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700178 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000179 if (in_str.at(0) == '[') {
180 std::string::size_type closebracket = in_str.rfind(']');
181 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000182 std::string::size_type colonpos = in_str.find(':', closebracket);
183 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700184 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
185 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000186 return false;
187 }
188 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700189 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000190 } else {
191 return false;
192 }
193 } else {
194 std::string::size_type colonpos = in_str.find(':');
195 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700196 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000197 return false;
198 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700199 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000200 } else {
201 *host = in_str;
202 }
203 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700204 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000205}
206
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800207// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700208// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200209bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
210 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800211 cricket::ServerAddresses* stun_servers,
212 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000213 // draft-nandakumar-rtcweb-stun-uri-01
214 // stunURI = scheme ":" stun-host [ ":" stun-port ]
215 // scheme = "stun" / "stuns"
216 // stun-host = IP-literal / IPv4address / reg-name
217 // stun-port = *DIGIT
218
219 // draft-petithuguenin-behave-turn-uris-01
220 // turnURI = scheme ":" turn-host [ ":" turn-port ]
221 // [ "?transport=" transport ]
222 // scheme = "turn" / "turns"
223 // transport = "udp" / "tcp" / transport-ext
224 // transport-ext = 1*unreserved
225 // turn-host = IP-literal / IPv4address / reg-name
226 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800227 RTC_DCHECK(stun_servers != nullptr);
228 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200229 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800230 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700231 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200232 rtc::tokenize(url, '?', &tokens);
233 std::string uri_without_transport = tokens[0];
234 // Let's look into transport= param, if it exists.
235 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
236 std::string uri_transport_param = tokens[1];
237 rtc::tokenize(uri_transport_param, '=', &tokens);
238 if (tokens[0] == kTransport) {
239 // As per above grammar transport param will be consist of lower case
240 // letters.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800241 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
242 (turn_transport_type != cricket::PROTO_UDP &&
243 turn_transport_type != cricket::PROTO_TCP)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200244 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700245 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000246 }
247 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200248 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200250 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700251 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200252 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
253 &service_type,
254 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700255 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
256 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200257 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000258
deadbeef0a6c4ca2015-10-06 11:38:28 -0700259 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
260 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200261
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200262 // Let's break hostname.
263 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700264 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
265
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200266 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700267 if (tokens.size() > kTurnHostTokensNum) {
268 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
269 return false;
270 }
271 if (tokens.size() == kTurnHostTokensNum) {
272 if (tokens[0].empty() || tokens[1].empty()) {
273 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
274 return false;
275 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200276 username.assign(rtc::s_url_decode(tokens[0]));
277 hoststring = tokens[1];
278 } else {
279 hoststring = tokens[0];
280 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000281
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200282 int port = kDefaultStunPort;
283 if (service_type == TURNS) {
284 port = kDefaultStunTlsPort;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800285 turn_transport_type = cricket::PROTO_TCP;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200286 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000287
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200288 std::string address;
289 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
291 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200292 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000293
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200294 if (port <= 0 || port > 0xffff) {
295 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700296 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000298
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 switch (service_type) {
300 case STUN:
301 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800302 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200303 break;
304 case TURN:
305 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200306 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800307 turn_servers->push_back(
308 cricket::RelayServerConfig(address, port, username, server.password,
309 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200310 break;
311 }
312 case INVALID:
313 default:
314 LOG(WARNING) << "Configuration not supported: " << url;
315 return false;
316 }
317 return true;
318}
319
deadbeefab9b2d12015-10-14 11:33:11 -0700320// Check if we can send |new_stream| on a PeerConnection.
321bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
322 webrtc::MediaStreamInterface* new_stream) {
323 if (!new_stream || !current_streams) {
324 return false;
325 }
326 if (current_streams->find(new_stream->label()) != nullptr) {
327 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
328 << " is already added.";
329 return false;
330 }
331 return true;
332}
333
334bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
335 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
336}
337
deadbeef5e97fb52015-10-15 12:49:08 -0700338// If the direction is "recvonly" or "inactive", treat the description
339// as containing no streams.
340// See: https://code.google.com/p/webrtc/issues/detail?id=5054
341std::vector<cricket::StreamParams> GetActiveStreams(
342 const cricket::MediaContentDescription* desc) {
343 return MediaContentDirectionHasSend(desc->direction())
344 ? desc->streams()
345 : std::vector<cricket::StreamParams>();
346}
347
deadbeefab9b2d12015-10-14 11:33:11 -0700348bool IsValidOfferToReceiveMedia(int value) {
349 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
350 return (value >= Options::kUndefined) &&
351 (value <= Options::kMaxOfferToReceiveMedia);
352}
353
354// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800355void AddSendStreams(
356 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700357 const std::vector<rtc::scoped_refptr<
358 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800359 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
360 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700361 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800362 for (const auto& sender : senders) {
363 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700364 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700365 }
366
367 // Check for data channels.
368 for (const auto& kv : rtp_data_channels) {
369 const DataChannel* channel = kv.second;
370 if (channel->state() == DataChannel::kConnecting ||
371 channel->state() == DataChannel::kOpen) {
372 // |streamid| and |sync_label| are both set to the DataChannel label
373 // here so they can be signaled the same way as MediaStreams and Tracks.
374 // For MediaStreams, the sync_label is the MediaStream label and the
375 // track label is the same as |streamid|.
376 const std::string& streamid = channel->label();
377 const std::string& sync_label = channel->label();
378 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
379 sync_label);
380 }
381 }
382}
383
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700384uint32_t ConvertIceTransportTypeToCandidateFilter(
385 PeerConnectionInterface::IceTransportsType type) {
386 switch (type) {
387 case PeerConnectionInterface::kNone:
388 return cricket::CF_NONE;
389 case PeerConnectionInterface::kRelay:
390 return cricket::CF_RELAY;
391 case PeerConnectionInterface::kNoHost:
392 return (cricket::CF_ALL & ~cricket::CF_HOST);
393 case PeerConnectionInterface::kAll:
394 return cricket::CF_ALL;
395 default:
396 ASSERT(false);
397 }
398 return cricket::CF_NONE;
399}
400
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700401// Helper method to set a voice/video channel on all applicable senders
402// and receivers when one is created/destroyed by WebRtcSession.
403//
404// Used by On(Voice|Video)Channel(Created|Destroyed)
405template <class SENDER,
406 class RECEIVER,
407 class CHANNEL,
408 class SENDERS,
409 class RECEIVERS>
410void SetChannelOnSendersAndReceivers(CHANNEL* channel,
411 SENDERS& senders,
412 RECEIVERS& receivers,
413 cricket::MediaType media_type) {
414 for (auto& sender : senders) {
415 if (sender->media_type() == media_type) {
416 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
417 }
418 }
419 for (auto& receiver : receivers) {
420 if (receiver->media_type() == media_type) {
421 if (!channel) {
422 receiver->internal()->Stop();
423 }
424 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
425 }
426 }
427}
428
deadbeef0a6c4ca2015-10-06 11:38:28 -0700429} // namespace
430
431namespace webrtc {
432
zhihuang8f65cdf2016-05-06 18:40:30 -0700433// Generate a RTCP CNAME when a PeerConnection is created.
434std::string GenerateRtcpCname() {
435 std::string cname;
436 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
437 LOG(LS_ERROR) << "Failed to generate CNAME.";
438 RTC_DCHECK(false);
439 }
440 return cname;
441}
442
htaa2a49d92016-03-04 02:51:39 -0800443bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700444 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800445 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700446 cricket::MediaSessionOptions* session_options) {
447 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
448 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
449 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
450 return false;
451 }
452
htaaac2dea2016-03-10 13:35:55 -0800453 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700454 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700455 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800456 } else {
457 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700458 }
htaaac2dea2016-03-10 13:35:55 -0800459 // For offers, we only offer video if we have it or it's forced by options.
460 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700461 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700462 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800463 } else if (is_offer) {
464 session_options->recv_video = false;
465 } else {
466 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700467 }
468
469 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700470 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800471 for (auto& kv : session_options->transport_options) {
472 kv.second.ice_restart = rtc_options.ice_restart;
473 }
deadbeefab9b2d12015-10-14 11:33:11 -0700474
475 return true;
476}
477
478bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
479 cricket::MediaSessionOptions* session_options) {
480 bool value = false;
481 size_t mandatory_constraints_satisfied = 0;
482
483 // kOfferToReceiveAudio defaults to true according to spec.
484 if (!FindConstraint(constraints,
485 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
486 &mandatory_constraints_satisfied) ||
487 value) {
488 session_options->recv_audio = true;
489 }
490
491 // kOfferToReceiveVideo defaults to false according to spec. But
492 // if it is an answer and video is offered, we should still accept video
493 // per default.
494 value = false;
495 if (!FindConstraint(constraints,
496 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
497 &mandatory_constraints_satisfied) ||
498 value) {
499 session_options->recv_video = true;
500 }
501
502 if (FindConstraint(constraints,
503 MediaConstraintsInterface::kVoiceActivityDetection, &value,
504 &mandatory_constraints_satisfied)) {
505 session_options->vad_enabled = value;
506 }
507
508 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
509 &mandatory_constraints_satisfied)) {
510 session_options->bundle_enabled = value;
511 } else {
512 // kUseRtpMux defaults to true according to spec.
513 session_options->bundle_enabled = true;
514 }
deadbeefab9b2d12015-10-14 11:33:11 -0700515
deadbeef0ed85b22016-02-23 17:24:52 -0800516 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700517 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
518 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700519 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800520 ice_restart = true;
521 }
522 for (auto& kv : session_options->transport_options) {
523 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700524 }
525
526 if (!constraints) {
527 return true;
528 }
529 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
530}
531
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200532bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800533 cricket::ServerAddresses* stun_servers,
534 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200535 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
536 if (!server.urls.empty()) {
537 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200538 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700539 LOG(LS_ERROR) << "Empty uri.";
540 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200541 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800542 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200543 return false;
544 }
545 }
546 } else if (!server.uri.empty()) {
547 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800548 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000549 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200550 }
551 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700552 LOG(LS_ERROR) << "Empty uri.";
553 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000554 }
555 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800556 // Candidates must have unique priorities, so that connectivity checks
557 // are performed in a well-defined order.
558 int priority = static_cast<int>(turn_servers->size() - 1);
559 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
560 // First in the list gets highest priority.
561 turn_server.priority = priority--;
562 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000563 return true;
564}
565
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000566PeerConnection::PeerConnection(PeerConnectionFactory* factory)
567 : factory_(factory),
568 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000569 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000570 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000571 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700572 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700573 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700574 local_streams_(StreamCollection::Create()),
575 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576
577PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100578 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700579 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700580 // Need to detach RTP senders/receivers from WebRtcSession,
581 // since it's about to be destroyed.
582 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700583 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700584 }
585 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700586 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700587 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700588 // Destroy stats_ because it depends on session_.
589 stats_.reset(nullptr);
590 // Now destroy session_ before destroying other members,
591 // because its destruction fires signals (such as VoiceChannelDestroyed)
592 // which will trigger some final actions in PeerConnection...
593 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700594 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700595 network_thread()->Invoke<void>(RTC_FROM_HERE,
596 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597}
598
599bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000600 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700601 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200602 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800603 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100604 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800605 RTC_DCHECK(observer != nullptr);
606 if (!observer) {
607 return false;
608 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000609 observer_ = observer;
610
kwiberg0eb15ed2015-12-17 03:04:15 -0800611 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800612
deadbeef91dd5672016-05-18 16:55:30 -0700613 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700614 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700615 if (!network_thread()->Invoke<bool>(
616 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
617 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000618 return false;
619 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000620
nissec36b31b2016-04-11 23:25:29 -0700621 media_controller_.reset(
622 factory_->CreateMediaController(configuration.media_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000623
zhihuang29ff8442016-07-27 11:07:25 -0700624 session_.reset(new WebRtcSession(
625 media_controller_.get(), factory_->network_thread(),
626 factory_->worker_thread(), factory_->signaling_thread(),
627 port_allocator_.get(),
628 std::unique_ptr<cricket::TransportController>(
629 factory_->CreateTransportController(port_allocator_.get()))));
630
deadbeefab9b2d12015-10-14 11:33:11 -0700631 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000632
633 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200634 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800635 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700637 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000639 // Register PeerConnection as receiver of local ice candidates.
640 // All the callbacks will be posted to the application from PeerConnection.
641 session_->RegisterIceObserver(this);
642 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700643 session_->SignalVoiceChannelCreated.connect(
644 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700645 session_->SignalVoiceChannelDestroyed.connect(
646 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700647 session_->SignalVideoChannelCreated.connect(
648 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700649 session_->SignalVideoChannelDestroyed.connect(
650 this, &PeerConnection::OnVideoChannelDestroyed);
651 session_->SignalDataChannelCreated.connect(
652 this, &PeerConnection::OnDataChannelCreated);
653 session_->SignalDataChannelDestroyed.connect(
654 this, &PeerConnection::OnDataChannelDestroyed);
655 session_->SignalDataChannelOpenMessage.connect(
656 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 return true;
658}
659
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000660rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000661PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700662 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663}
664
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000665rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700667 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668}
669
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000670bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100671 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672 if (IsClosed()) {
673 return false;
674 }
deadbeefab9b2d12015-10-14 11:33:11 -0700675 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 return false;
677 }
deadbeefab9b2d12015-10-14 11:33:11 -0700678
679 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800680 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
681 observer->SignalAudioTrackAdded.connect(this,
682 &PeerConnection::OnAudioTrackAdded);
683 observer->SignalAudioTrackRemoved.connect(
684 this, &PeerConnection::OnAudioTrackRemoved);
685 observer->SignalVideoTrackAdded.connect(this,
686 &PeerConnection::OnVideoTrackAdded);
687 observer->SignalVideoTrackRemoved.connect(
688 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700689 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700690
deadbeefab9b2d12015-10-14 11:33:11 -0700691 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800692 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700693 }
694 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800695 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700696 }
697
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000698 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000699 observer_->OnRenegotiationNeeded();
700 return true;
701}
702
703void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100704 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700705 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800706 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700707 }
708 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800709 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700710 }
711
712 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800713 stream_observers_.erase(
714 std::remove_if(
715 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700716 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800717 return observer->stream()->label().compare(local_stream->label()) ==
718 0;
719 }),
720 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700721
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 if (IsClosed()) {
723 return;
724 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 observer_->OnRenegotiationNeeded();
726}
727
deadbeefe1f9d832016-01-14 15:35:42 -0800728rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
729 MediaStreamTrackInterface* track,
730 std::vector<MediaStreamInterface*> streams) {
731 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
732 if (IsClosed()) {
733 return nullptr;
734 }
735 if (streams.size() >= 2) {
736 LOG(LS_ERROR)
737 << "Adding a track with two streams is not currently supported.";
738 return nullptr;
739 }
740 // TODO(deadbeef): Support adding a track to two different senders.
741 if (FindSenderForTrack(track) != senders_.end()) {
742 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
743 return nullptr;
744 }
745
746 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700747 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800748 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700749 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800750 signaling_thread(),
751 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700752 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800753 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700754 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800755 }
756 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700757 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800758 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700759 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800760 }
761 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700762 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800763 signaling_thread(),
764 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700765 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800766 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700767 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800768 }
769 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700770 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800771 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700772 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800773 }
774 } else {
775 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
776 return rtc::scoped_refptr<RtpSenderInterface>();
777 }
778
779 senders_.push_back(new_sender);
780 observer_->OnRenegotiationNeeded();
781 return new_sender;
782}
783
784bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
785 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
786 if (IsClosed()) {
787 return false;
788 }
789
790 auto it = std::find(senders_.begin(), senders_.end(), sender);
791 if (it == senders_.end()) {
792 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
793 return false;
794 }
deadbeefa601f5c2016-06-06 14:27:39 -0700795 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800796 senders_.erase(it);
797
798 observer_->OnRenegotiationNeeded();
799 return true;
800}
801
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000802rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000803 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100804 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700805 if (IsClosed()) {
806 return nullptr;
807 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808 if (!track) {
809 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
810 return NULL;
811 }
deadbeefab9b2d12015-10-14 11:33:11 -0700812 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
814 return NULL;
815 }
816
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000817 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 DtmfSender::Create(track, signaling_thread(), session_.get()));
819 if (!sender.get()) {
820 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
821 return NULL;
822 }
823 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
824}
825
deadbeeffac06552015-11-25 11:26:01 -0800826rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800827 const std::string& kind,
828 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100829 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700830 if (IsClosed()) {
831 return nullptr;
832 }
deadbeefa601f5c2016-06-06 14:27:39 -0700833 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800834 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700835 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700836 signaling_thread(),
837 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800838 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700839 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700840 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800841 } else {
842 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800843 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800844 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800845 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700846 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800847 }
deadbeeffac06552015-11-25 11:26:01 -0800848 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800849 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800850}
851
deadbeef70ab1a12015-09-28 16:53:55 -0700852std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
853 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700854 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
855 for (const auto& sender : senders_) {
856 ret.push_back(sender.get());
857 }
858 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700859}
860
861std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
862PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700863 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
864 for (const auto& receiver : receivers_) {
865 ret.push_back(receiver.get());
866 }
867 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700868}
869
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000871 MediaStreamTrackInterface* track,
872 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100873 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700874 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875 if (!VERIFY(observer != NULL)) {
876 LOG(LS_ERROR) << "GetStats - observer is NULL.";
877 return false;
878 }
879
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000880 stats_->UpdateStats(level);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700881 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000882 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883 return true;
884}
885
886PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
887 return signaling_state_;
888}
889
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000890PeerConnectionInterface::IceConnectionState
891PeerConnection::ice_connection_state() {
892 return ice_connection_state_;
893}
894
895PeerConnectionInterface::IceGatheringState
896PeerConnection::ice_gathering_state() {
897 return ice_gathering_state_;
898}
899
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000900rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901PeerConnection::CreateDataChannel(
902 const std::string& label,
903 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100904 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700905#ifdef HAVE_QUIC
906 if (session_->data_channel_type() == cricket::DCT_QUIC) {
907 // TODO(zhihuang): Handle case when config is NULL.
908 if (!config) {
909 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
910 return nullptr;
911 }
912 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
913 if (!config->reliable || config->ordered) {
914 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
915 "ordered delivery.";
916 return nullptr;
917 }
918 return session_->quic_data_transport()->CreateDataChannel(label, config);
919 }
920#endif // HAVE_QUIC
921
deadbeefab9b2d12015-10-14 11:33:11 -0700922 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000923
kwibergd1fe2812016-04-27 06:47:29 -0700924 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000925 if (config) {
926 internal_config.reset(new InternalDataChannelInit(*config));
927 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000928 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700929 InternalCreateDataChannel(label, internal_config.get()));
930 if (!channel.get()) {
931 return nullptr;
932 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000934 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
935 // the first SCTP DataChannel.
936 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
937 observer_->OnRenegotiationNeeded();
938 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000939
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940 return DataChannelProxy::Create(signaling_thread(), channel.get());
941}
942
943void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
944 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100945 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700946 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
948 return;
949 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000950 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000951
952 bool value;
953 size_t mandatory_constraints = 0;
954
955 if (FindConstraint(constraints,
956 MediaConstraintsInterface::kOfferToReceiveAudio,
957 &value,
958 &mandatory_constraints)) {
959 options.offer_to_receive_audio =
960 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
961 }
962
963 if (FindConstraint(constraints,
964 MediaConstraintsInterface::kOfferToReceiveVideo,
965 &value,
966 &mandatory_constraints)) {
967 options.offer_to_receive_video =
968 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
969 }
970
971 if (FindConstraint(constraints,
972 MediaConstraintsInterface::kVoiceActivityDetection,
973 &value,
974 &mandatory_constraints)) {
975 options.voice_activity_detection = value;
976 }
977
978 if (FindConstraint(constraints,
979 MediaConstraintsInterface::kIceRestart,
980 &value,
981 &mandatory_constraints)) {
982 options.ice_restart = value;
983 }
984
985 if (FindConstraint(constraints,
986 MediaConstraintsInterface::kUseRtpMux,
987 &value,
988 &mandatory_constraints)) {
989 options.use_rtp_mux = value;
990 }
991
992 CreateOffer(observer, options);
993}
994
995void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
996 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100997 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700998 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000999 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1000 return;
1001 }
deadbeefab9b2d12015-10-14 11:33:11 -07001002
1003 cricket::MediaSessionOptions session_options;
1004 if (!GetOptionsForOffer(options, &session_options)) {
1005 std::string error = "CreateOffer called with invalid options.";
1006 LOG(LS_ERROR) << error;
1007 PostCreateSessionDescriptionFailure(observer, error);
1008 return;
1009 }
1010
1011 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012}
1013
1014void PeerConnection::CreateAnswer(
1015 CreateSessionDescriptionObserver* observer,
1016 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001017 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001018 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1020 return;
1021 }
deadbeefab9b2d12015-10-14 11:33:11 -07001022
1023 cricket::MediaSessionOptions session_options;
1024 if (!GetOptionsForAnswer(constraints, &session_options)) {
1025 std::string error = "CreateAnswer called with invalid constraints.";
1026 LOG(LS_ERROR) << error;
1027 PostCreateSessionDescriptionFailure(observer, error);
1028 return;
1029 }
1030
htaa2a49d92016-03-04 02:51:39 -08001031 session_->CreateAnswer(observer, session_options);
1032}
1033
1034void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1035 const RTCOfferAnswerOptions& options) {
1036 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1037 if (!VERIFY(observer != nullptr)) {
1038 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1039 return;
1040 }
1041
1042 cricket::MediaSessionOptions session_options;
1043 if (!GetOptionsForAnswer(options, &session_options)) {
1044 std::string error = "CreateAnswer called with invalid options.";
1045 LOG(LS_ERROR) << error;
1046 PostCreateSessionDescriptionFailure(observer, error);
1047 return;
1048 }
1049
1050 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051}
1052
1053void PeerConnection::SetLocalDescription(
1054 SetSessionDescriptionObserver* observer,
1055 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001056 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001057 if (IsClosed()) {
1058 return;
1059 }
deadbeefab9b2d12015-10-14 11:33:11 -07001060 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1062 return;
1063 }
1064 if (!desc) {
1065 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1066 return;
1067 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068 // Update stats here so that we have the most recent stats for tracks and
1069 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001070 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071 std::string error;
1072 if (!session_->SetLocalDescription(desc, &error)) {
1073 PostSetSessionDescriptionFailure(observer, error);
1074 return;
1075 }
deadbeefab9b2d12015-10-14 11:33:11 -07001076
1077 // If setting the description decided our SSL role, allocate any necessary
1078 // SCTP sids.
1079 rtc::SSLRole role;
1080 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001081 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001082 AllocateSctpSids(role);
1083 }
1084
1085 // Update state and SSRC of local MediaStreams and DataChannels based on the
1086 // local session description.
1087 const cricket::ContentInfo* audio_content =
1088 GetFirstAudioContent(desc->description());
1089 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001090 if (audio_content->rejected) {
1091 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1092 } else {
1093 const cricket::AudioContentDescription* audio_desc =
1094 static_cast<const cricket::AudioContentDescription*>(
1095 audio_content->description);
1096 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1097 }
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099
1100 const cricket::ContentInfo* video_content =
1101 GetFirstVideoContent(desc->description());
1102 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001103 if (video_content->rejected) {
1104 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1105 } else {
1106 const cricket::VideoContentDescription* video_desc =
1107 static_cast<const cricket::VideoContentDescription*>(
1108 video_content->description);
1109 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1110 }
deadbeefab9b2d12015-10-14 11:33:11 -07001111 }
1112
1113 const cricket::ContentInfo* data_content =
1114 GetFirstDataContent(desc->description());
1115 if (data_content) {
1116 const cricket::DataContentDescription* data_desc =
1117 static_cast<const cricket::DataContentDescription*>(
1118 data_content->description);
1119 if (rtc::starts_with(data_desc->protocol().data(),
1120 cricket::kMediaProtocolRtpPrefix)) {
1121 UpdateLocalRtpDataChannels(data_desc->streams());
1122 }
1123 }
1124
1125 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001126 signaling_thread()->Post(RTC_FROM_HERE, this,
1127 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001128
deadbeefcbecd352015-09-23 11:50:27 -07001129 // MaybeStartGathering needs to be called after posting
1130 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1131 // before signaling that SetLocalDescription completed.
1132 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133}
1134
1135void PeerConnection::SetRemoteDescription(
1136 SetSessionDescriptionObserver* observer,
1137 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001138 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001139 if (IsClosed()) {
1140 return;
1141 }
deadbeefab9b2d12015-10-14 11:33:11 -07001142 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001143 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1144 return;
1145 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146 if (!desc) {
1147 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1148 return;
1149 }
1150 // Update stats here so that we have the most recent stats for tracks and
1151 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001152 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001153 std::string error;
1154 if (!session_->SetRemoteDescription(desc, &error)) {
1155 PostSetSessionDescriptionFailure(observer, error);
1156 return;
1157 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158
deadbeefab9b2d12015-10-14 11:33:11 -07001159 // If setting the description decided our SSL role, allocate any necessary
1160 // SCTP sids.
1161 rtc::SSLRole role;
1162 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001163 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001164 AllocateSctpSids(role);
1165 }
1166
1167 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001168 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1169 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1170 const cricket::AudioContentDescription* audio_desc =
1171 GetFirstAudioContentDescription(remote_desc);
1172 const cricket::VideoContentDescription* video_desc =
1173 GetFirstVideoContentDescription(remote_desc);
1174 const cricket::DataContentDescription* data_desc =
1175 GetFirstDataContentDescription(remote_desc);
1176
1177 // Check if the descriptions include streams, just in case the peer supports
1178 // MSID, but doesn't indicate so with "a=msid-semantic".
1179 if (remote_desc->msid_supported() ||
1180 (audio_desc && !audio_desc->streams().empty()) ||
1181 (video_desc && !video_desc->streams().empty())) {
1182 remote_peer_supports_msid_ = true;
1183 }
deadbeefab9b2d12015-10-14 11:33:11 -07001184
1185 // We wait to signal new streams until we finish processing the description,
1186 // since only at that point will new streams have all their tracks.
1187 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1188
1189 // Find all audio rtp streams and create corresponding remote AudioTracks
1190 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001191 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001192 if (audio_content->rejected) {
1193 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1194 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001195 bool default_audio_track_needed =
1196 !remote_peer_supports_msid_ &&
1197 MediaContentDirectionHasSend(audio_desc->direction());
1198 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1199 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001200 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001201 }
deadbeefab9b2d12015-10-14 11:33:11 -07001202 }
1203
1204 // Find all video rtp streams and create corresponding remote VideoTracks
1205 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001206 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001207 if (video_content->rejected) {
1208 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1209 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001210 bool default_video_track_needed =
1211 !remote_peer_supports_msid_ &&
1212 MediaContentDirectionHasSend(video_desc->direction());
1213 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1214 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001215 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001216 }
deadbeefab9b2d12015-10-14 11:33:11 -07001217 }
1218
1219 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001220 if (data_desc) {
1221 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001222 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001223 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001224 }
1225 }
1226
1227 // Iterate new_streams and notify the observer about new MediaStreams.
1228 for (size_t i = 0; i < new_streams->count(); ++i) {
1229 MediaStreamInterface* new_stream = new_streams->at(i);
1230 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001231 // Call both the raw pointer and scoped_refptr versions of the method
1232 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001233 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001234 observer_->OnAddStream(
1235 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001236 }
1237
deadbeefbda7e0b2015-12-08 17:13:40 -08001238 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001239
1240 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001241 signaling_thread()->Post(RTC_FROM_HERE, this,
1242 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001243}
1244
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001245bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001246 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001247 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001248 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001249 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001250 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001251 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001252 return false;
1253 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001254 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001255
1256 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1257 session_->SetIceConfig(session_->ParseIceConfig(configuration));
1258 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001259}
1260
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261bool PeerConnection::AddIceCandidate(
1262 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001263 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001264 if (IsClosed()) {
1265 return false;
1266 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 return session_->ProcessIceMessage(ice_candidate);
1268}
1269
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001270bool PeerConnection::RemoveIceCandidates(
1271 const std::vector<cricket::Candidate>& candidates) {
1272 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1273 return session_->RemoveRemoteIceCandidates(candidates);
1274}
1275
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001276void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001277 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001278 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001279
1280 if (session_) {
1281 session_->set_metrics_observer(uma_observer_);
1282 }
1283
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001284 // Send information about IPv4/IPv6 status.
1285 if (uma_observer_ && port_allocator_) {
1286 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001287 uma_observer_->IncrementEnumCounter(
1288 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1289 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001290 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001291 uma_observer_->IncrementEnumCounter(
1292 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1293 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001294 }
1295 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001296}
1297
ivoc14d5dbe2016-07-04 07:06:55 -07001298bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1299 int64_t max_size_bytes) {
1300 return factory_->worker_thread()->Invoke<bool>(
1301 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1302 max_size_bytes));
1303}
1304
1305void PeerConnection::StopRtcEventLog() {
1306 factory_->worker_thread()->Invoke<void>(
1307 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1308}
1309
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310const SessionDescriptionInterface* PeerConnection::local_description() const {
1311 return session_->local_description();
1312}
1313
1314const SessionDescriptionInterface* PeerConnection::remote_description() const {
1315 return session_->remote_description();
1316}
1317
1318void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001319 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 // Update stats here so that we have the most recent stats for tracks and
1321 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001322 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323
deadbeefd59daf82015-10-14 15:02:44 -07001324 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325}
1326
deadbeefd59daf82015-10-14 15:02:44 -07001327void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1328 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001330 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001331 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001332 break;
deadbeefd59daf82015-10-14 15:02:44 -07001333 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1335 break;
deadbeefd59daf82015-10-14 15:02:44 -07001336 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1338 break;
deadbeefd59daf82015-10-14 15:02:44 -07001339 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1341 break;
deadbeefd59daf82015-10-14 15:02:44 -07001342 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1344 break;
deadbeefd59daf82015-10-14 15:02:44 -07001345 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 ChangeSignalingState(PeerConnectionInterface::kStable);
1347 break;
deadbeefd59daf82015-10-14 15:02:44 -07001348 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 ChangeSignalingState(PeerConnectionInterface::kClosed);
1350 break;
1351 default:
1352 break;
1353 }
1354}
1355
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001356void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1359 SetSessionDescriptionMsg* param =
1360 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1361 param->observer->OnSuccess();
1362 delete param;
1363 break;
1364 }
1365 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1366 SetSessionDescriptionMsg* param =
1367 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1368 param->observer->OnFailure(param->error);
1369 delete param;
1370 break;
1371 }
deadbeefab9b2d12015-10-14 11:33:11 -07001372 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1373 CreateSessionDescriptionMsg* param =
1374 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1375 param->observer->OnFailure(param->error);
1376 delete param;
1377 break;
1378 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379 case MSG_GETSTATS: {
1380 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001381 StatsReports reports;
1382 stats_->GetStats(param->track, &reports);
1383 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384 delete param;
1385 break;
1386 }
deadbeefbd292462015-12-14 18:15:29 -08001387 case MSG_FREE_DATACHANNELS: {
1388 sctp_data_channels_to_free_.clear();
1389 break;
1390 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001392 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 break;
1394 }
1395}
1396
deadbeefab9b2d12015-10-14 11:33:11 -07001397void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001398 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001399 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001400 receivers_.push_back(
1401 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001402 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
1403 session_->voice_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404}
1405
deadbeefab9b2d12015-10-14 11:33:11 -07001406void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001407 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001408 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001409 receivers_.push_back(
1410 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1411 signaling_thread(),
1412 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001413 ssrc, session_->video_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414}
1415
deadbeef70ab1a12015-09-28 16:53:55 -07001416// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1417// description.
perkjd61bf802016-03-24 03:16:19 -07001418void PeerConnection::DestroyReceiver(const std::string& track_id) {
1419 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001420 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001421 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001422 << " doesn't exist.";
1423 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001424 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001425 receivers_.erase(it);
1426 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427}
1428
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001429void PeerConnection::OnIceConnectionChange(
1430 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001431 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001432 // After transitioning to "closed", ignore any additional states from
1433 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001434 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001435 return;
1436 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001438 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439}
1440
1441void PeerConnection::OnIceGatheringChange(
1442 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001443 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 if (IsClosed()) {
1445 return;
1446 }
1447 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001448 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449}
1450
1451void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001452 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001453 if (IsClosed()) {
1454 return;
1455 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001456 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457}
1458
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001459void PeerConnection::OnIceCandidatesRemoved(
1460 const std::vector<cricket::Candidate>& candidates) {
1461 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001462 if (IsClosed()) {
1463 return;
1464 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001465 observer_->OnIceCandidatesRemoved(candidates);
1466}
1467
Peter Thatcher54360512015-07-08 11:08:35 -07001468void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001469 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001470 if (IsClosed()) {
1471 return;
1472 }
Peter Thatcher54360512015-07-08 11:08:35 -07001473 observer_->OnIceConnectionReceivingChange(receiving);
1474}
1475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476void PeerConnection::ChangeSignalingState(
1477 PeerConnectionInterface::SignalingState signaling_state) {
1478 signaling_state_ = signaling_state;
1479 if (signaling_state == kClosed) {
1480 ice_connection_state_ = kIceConnectionClosed;
1481 observer_->OnIceConnectionChange(ice_connection_state_);
1482 if (ice_gathering_state_ != kIceGatheringComplete) {
1483 ice_gathering_state_ = kIceGatheringComplete;
1484 observer_->OnIceGatheringChange(ice_gathering_state_);
1485 }
1486 }
1487 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488}
1489
deadbeefeb459812015-12-15 19:24:43 -08001490void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1491 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001492 if (IsClosed()) {
1493 return;
1494 }
deadbeefeb459812015-12-15 19:24:43 -08001495 auto sender = FindSenderForTrack(track);
1496 if (sender != senders_.end()) {
1497 // We already have a sender for this track, so just change the stream_id
1498 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001499 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001500 return;
1501 }
1502
1503 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001504 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1505 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001506 signaling_thread(),
1507 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1508 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001509 senders_.push_back(new_sender);
1510 // If the sender has already been configured in SDP, we call SetSsrc,
1511 // which will connect the sender to the underlying transport. This can
1512 // occur if a local session description that contains the ID of the sender
1513 // is set before AddStream is called. It can also occur if the local
1514 // session description is not changed and RemoveStream is called, and
1515 // later AddStream is called again with the same stream.
1516 const TrackInfo* track_info =
1517 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1518 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001519 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001520 }
1521}
1522
1523// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1524// indefinitely, when we have unified plan SDP.
1525void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1526 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001527 if (IsClosed()) {
1528 return;
1529 }
deadbeefeb459812015-12-15 19:24:43 -08001530 auto sender = FindSenderForTrack(track);
1531 if (sender == senders_.end()) {
1532 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1533 << " doesn't exist.";
1534 return;
1535 }
deadbeefa601f5c2016-06-06 14:27:39 -07001536 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001537 senders_.erase(sender);
1538}
1539
1540void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1541 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001542 if (IsClosed()) {
1543 return;
1544 }
deadbeefeb459812015-12-15 19:24:43 -08001545 auto sender = FindSenderForTrack(track);
1546 if (sender != senders_.end()) {
1547 // We already have a sender for this track, so just change the stream_id
1548 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001549 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001550 return;
1551 }
1552
1553 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001554 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1555 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001556 signaling_thread(), new VideoRtpSender(track, stream->label(),
1557 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001558 senders_.push_back(new_sender);
1559 const TrackInfo* track_info =
1560 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1561 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001562 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001563 }
1564}
1565
1566void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1567 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001568 if (IsClosed()) {
1569 return;
1570 }
deadbeefeb459812015-12-15 19:24:43 -08001571 auto sender = FindSenderForTrack(track);
1572 if (sender == senders_.end()) {
1573 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1574 << " doesn't exist.";
1575 return;
1576 }
deadbeefa601f5c2016-06-06 14:27:39 -07001577 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001578 senders_.erase(sender);
1579}
1580
deadbeefab9b2d12015-10-14 11:33:11 -07001581void PeerConnection::PostSetSessionDescriptionFailure(
1582 SetSessionDescriptionObserver* observer,
1583 const std::string& error) {
1584 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1585 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001586 signaling_thread()->Post(RTC_FROM_HERE, this,
1587 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001588}
1589
1590void PeerConnection::PostCreateSessionDescriptionFailure(
1591 CreateSessionDescriptionObserver* observer,
1592 const std::string& error) {
1593 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1594 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001595 signaling_thread()->Post(RTC_FROM_HERE, this,
1596 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001597}
1598
1599bool PeerConnection::GetOptionsForOffer(
1600 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1601 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001602 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1603 // ContentInfos.
1604 if (session_->local_description()) {
1605 for (const cricket::ContentInfo& content :
1606 session_->local_description()->description()->contents()) {
1607 session_options->transport_options[content.name] =
1608 cricket::TransportOptions();
1609 }
1610 }
htaaac2dea2016-03-10 13:35:55 -08001611 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001612 return false;
1613 }
1614
deadbeeffac06552015-11-25 11:26:01 -08001615 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001616 // Offer to receive audio/video if the constraint is not set and there are
1617 // send streams, or we're currently receiving.
1618 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1619 session_options->recv_audio =
1620 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1621 !remote_audio_tracks_.empty();
1622 }
1623 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1624 session_options->recv_video =
1625 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1626 !remote_video_tracks_.empty();
1627 }
1628 session_options->bundle_enabled =
1629 session_options->bundle_enabled &&
1630 (session_options->has_audio() || session_options->has_video() ||
1631 session_options->has_data());
1632
zhihuang9763d562016-08-05 11:14:50 -07001633 // Intentionally unset the data channel type for RTP data channel with the
1634 // second condition. Otherwise the RTP data channels would be successfully
1635 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1636 // when building with chromium. We want to leave RTP data channels broken, so
1637 // people won't try to use them.
1638 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1639 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001640 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001641
1642 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001643 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001644 return true;
1645}
1646
htaa2a49d92016-03-04 02:51:39 -08001647void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001648 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001649 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1650 // ContentInfos.
1651 if (session_->remote_description()) {
1652 // Initialize the transport_options map.
1653 for (const cricket::ContentInfo& content :
1654 session_->remote_description()->description()->contents()) {
1655 session_options->transport_options[content.name] =
1656 cricket::TransportOptions();
1657 }
1658 }
deadbeeffac06552015-11-25 11:26:01 -08001659 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001660 session_options->bundle_enabled =
1661 session_options->bundle_enabled &&
1662 (session_options->has_audio() || session_options->has_video() ||
1663 session_options->has_data());
1664
deadbeefab9b2d12015-10-14 11:33:11 -07001665 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1666 // are not signaled in the SDP so does not go through that path and must be
1667 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001668 // Intentionally unset the data channel type for RTP data channel. Otherwise
1669 // the RTP data channels would be successfully negotiated by default and the
1670 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1671 // We want to leave RTP data channels broken, so people won't try to use them.
1672 if (session_->data_channel_type() != cricket::DCT_RTP) {
1673 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001674 }
jbauchcb560652016-08-04 05:20:32 -07001675 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001676}
1677
1678bool PeerConnection::GetOptionsForAnswer(
1679 const MediaConstraintsInterface* constraints,
1680 cricket::MediaSessionOptions* session_options) {
1681 session_options->recv_audio = false;
1682 session_options->recv_video = false;
1683 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1684 return false;
1685 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001686 session_options->rtcp_cname = rtcp_cname_;
1687
htaa2a49d92016-03-04 02:51:39 -08001688 FinishOptionsForAnswer(session_options);
1689 return true;
1690}
1691
1692bool PeerConnection::GetOptionsForAnswer(
1693 const RTCOfferAnswerOptions& options,
1694 cricket::MediaSessionOptions* session_options) {
1695 session_options->recv_audio = false;
1696 session_options->recv_video = false;
htaaac2dea2016-03-10 13:35:55 -08001697 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001698 return false;
1699 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001700 session_options->rtcp_cname = rtcp_cname_;
1701
htaa2a49d92016-03-04 02:51:39 -08001702 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001703 return true;
1704}
1705
deadbeeffaac4972015-11-12 15:33:07 -08001706void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1707 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001708 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1709 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001710}
1711
deadbeefab9b2d12015-10-14 11:33:11 -07001712void PeerConnection::UpdateRemoteStreamsList(
1713 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001714 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001715 cricket::MediaType media_type,
1716 StreamCollection* new_streams) {
1717 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1718
1719 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001720 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001721 auto track_it = current_tracks->begin();
1722 while (track_it != current_tracks->end()) {
1723 const TrackInfo& info = *track_it;
1724 const cricket::StreamParams* params =
1725 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001726 bool track_exists = params && params->id == info.track_id;
1727 // If this is a default track, and we still need it, don't remove it.
1728 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1729 track_exists) {
1730 ++track_it;
1731 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001732 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1733 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001734 }
1735 }
1736
1737 // Find new and active tracks.
1738 for (const cricket::StreamParams& params : streams) {
1739 // The sync_label is the MediaStream label and the |stream.id| is the
1740 // track id.
1741 const std::string& stream_label = params.sync_label;
1742 const std::string& track_id = params.id;
1743 uint32_t ssrc = params.first_ssrc();
1744
1745 rtc::scoped_refptr<MediaStreamInterface> stream =
1746 remote_streams_->find(stream_label);
1747 if (!stream) {
1748 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001749 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1750 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001751 remote_streams_->AddStream(stream);
1752 new_streams->AddStream(stream);
1753 }
1754
1755 const TrackInfo* track_info =
1756 FindTrackInfo(*current_tracks, stream_label, track_id);
1757 if (!track_info) {
1758 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1759 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1760 }
1761 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001762
1763 // Add default track if necessary.
1764 if (default_track_needed) {
1765 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1766 remote_streams_->find(kDefaultStreamLabel);
1767 if (!default_stream) {
1768 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001769 default_stream = MediaStreamProxy::Create(
1770 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001771 remote_streams_->AddStream(default_stream);
1772 new_streams->AddStream(default_stream);
1773 }
1774 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1775 ? kDefaultAudioTrackLabel
1776 : kDefaultVideoTrackLabel;
1777 const TrackInfo* default_track_info =
1778 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1779 if (!default_track_info) {
1780 current_tracks->push_back(
1781 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1782 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1783 }
1784 }
deadbeefab9b2d12015-10-14 11:33:11 -07001785}
1786
1787void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1788 const std::string& track_id,
1789 uint32_t ssrc,
1790 cricket::MediaType media_type) {
1791 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1792
1793 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001794 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001795 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001796 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001797 } else {
1798 RTC_DCHECK(false && "Invalid media type");
1799 }
1800}
1801
1802void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1803 const std::string& track_id,
1804 cricket::MediaType media_type) {
1805 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1806
1807 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001808 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1809 // will be notified which will end the AudioRtpReceiver::track().
1810 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001811 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1812 stream->FindAudioTrack(track_id);
1813 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001814 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001815 }
1816 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001817 // Stopping or destroying a VideoRtpReceiver will end the
1818 // VideoRtpReceiver::track().
1819 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001820 rtc::scoped_refptr<VideoTrackInterface> video_track =
1821 stream->FindVideoTrack(track_id);
1822 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001823 // There's no guarantee the track is still available, e.g. the track may
1824 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001825 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001826 }
1827 } else {
1828 ASSERT(false && "Invalid media type");
1829 }
1830}
1831
1832void PeerConnection::UpdateEndedRemoteMediaStreams() {
1833 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1834 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1835 MediaStreamInterface* stream = remote_streams_->at(i);
1836 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1837 streams_to_remove.push_back(stream);
1838 }
1839 }
1840
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001841 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001842 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001843 // Call both the raw pointer and scoped_refptr versions of the method
1844 // for compatibility.
1845 observer_->OnRemoveStream(stream.get());
1846 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001847 }
1848}
1849
deadbeefab9b2d12015-10-14 11:33:11 -07001850void PeerConnection::UpdateLocalTracks(
1851 const std::vector<cricket::StreamParams>& streams,
1852 cricket::MediaType media_type) {
1853 TrackInfos* current_tracks = GetLocalTracks(media_type);
1854
1855 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1856 // don't match the new StreamParam.
1857 TrackInfos::iterator track_it = current_tracks->begin();
1858 while (track_it != current_tracks->end()) {
1859 const TrackInfo& info = *track_it;
1860 const cricket::StreamParams* params =
1861 cricket::GetStreamBySsrc(streams, info.ssrc);
1862 if (!params || params->id != info.track_id ||
1863 params->sync_label != info.stream_label) {
1864 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1865 media_type);
1866 track_it = current_tracks->erase(track_it);
1867 } else {
1868 ++track_it;
1869 }
1870 }
1871
1872 // Find new and active tracks.
1873 for (const cricket::StreamParams& params : streams) {
1874 // The sync_label is the MediaStream label and the |stream.id| is the
1875 // track id.
1876 const std::string& stream_label = params.sync_label;
1877 const std::string& track_id = params.id;
1878 uint32_t ssrc = params.first_ssrc();
1879 const TrackInfo* track_info =
1880 FindTrackInfo(*current_tracks, stream_label, track_id);
1881 if (!track_info) {
1882 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1883 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1884 }
1885 }
1886}
1887
1888void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1889 const std::string& track_id,
1890 uint32_t ssrc,
1891 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001892 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001893 if (!sender) {
1894 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1895 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001896 return;
1897 }
1898
deadbeeffac06552015-11-25 11:26:01 -08001899 if (sender->media_type() != media_type) {
1900 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1901 << " description with an unexpected media type.";
1902 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001903 }
deadbeeffac06552015-11-25 11:26:01 -08001904
1905 sender->set_stream_id(stream_label);
1906 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001907}
1908
1909void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1910 const std::string& track_id,
1911 uint32_t ssrc,
1912 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001913 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001914 if (!sender) {
1915 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001916 // SessionDescriptions has been renegotiated.
1917 return;
1918 }
deadbeeffac06552015-11-25 11:26:01 -08001919
1920 // A sender has been removed from the SessionDescription but it's still
1921 // associated with the PeerConnection. This only occurs if the SDP doesn't
1922 // match with the calls to CreateSender, AddStream and RemoveStream.
1923 if (sender->media_type() != media_type) {
1924 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1925 << " description with an unexpected media type.";
1926 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001927 }
deadbeeffac06552015-11-25 11:26:01 -08001928
1929 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001930}
1931
1932void PeerConnection::UpdateLocalRtpDataChannels(
1933 const cricket::StreamParamsVec& streams) {
1934 std::vector<std::string> existing_channels;
1935
1936 // Find new and active data channels.
1937 for (const cricket::StreamParams& params : streams) {
1938 // |it->sync_label| is actually the data channel label. The reason is that
1939 // we use the same naming of data channels as we do for
1940 // MediaStreams and Tracks.
1941 // For MediaStreams, the sync_label is the MediaStream label and the
1942 // track label is the same as |streamid|.
1943 const std::string& channel_label = params.sync_label;
1944 auto data_channel_it = rtp_data_channels_.find(channel_label);
1945 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1946 continue;
1947 }
1948 // Set the SSRC the data channel should use for sending.
1949 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1950 existing_channels.push_back(data_channel_it->first);
1951 }
1952
1953 UpdateClosingRtpDataChannels(existing_channels, true);
1954}
1955
1956void PeerConnection::UpdateRemoteRtpDataChannels(
1957 const cricket::StreamParamsVec& streams) {
1958 std::vector<std::string> existing_channels;
1959
1960 // Find new and active data channels.
1961 for (const cricket::StreamParams& params : streams) {
1962 // The data channel label is either the mslabel or the SSRC if the mslabel
1963 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1964 std::string label = params.sync_label.empty()
1965 ? rtc::ToString(params.first_ssrc())
1966 : params.sync_label;
1967 auto data_channel_it = rtp_data_channels_.find(label);
1968 if (data_channel_it == rtp_data_channels_.end()) {
1969 // This is a new data channel.
1970 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1971 } else {
1972 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1973 }
1974 existing_channels.push_back(label);
1975 }
1976
1977 UpdateClosingRtpDataChannels(existing_channels, false);
1978}
1979
1980void PeerConnection::UpdateClosingRtpDataChannels(
1981 const std::vector<std::string>& active_channels,
1982 bool is_local_update) {
1983 auto it = rtp_data_channels_.begin();
1984 while (it != rtp_data_channels_.end()) {
1985 DataChannel* data_channel = it->second;
1986 if (std::find(active_channels.begin(), active_channels.end(),
1987 data_channel->label()) != active_channels.end()) {
1988 ++it;
1989 continue;
1990 }
1991
1992 if (is_local_update) {
1993 data_channel->SetSendSsrc(0);
1994 } else {
1995 data_channel->RemotePeerRequestClose();
1996 }
1997
1998 if (data_channel->state() == DataChannel::kClosed) {
1999 rtp_data_channels_.erase(it);
2000 it = rtp_data_channels_.begin();
2001 } else {
2002 ++it;
2003 }
2004 }
2005}
2006
2007void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2008 uint32_t remote_ssrc) {
2009 rtc::scoped_refptr<DataChannel> channel(
2010 InternalCreateDataChannel(label, nullptr));
2011 if (!channel.get()) {
2012 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2013 << "CreateDataChannel failed.";
2014 return;
2015 }
2016 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002017 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2018 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002019 // Call both the raw pointer and scoped_refptr versions of the method
2020 // for compatibility.
2021 observer_->OnDataChannel(proxy_channel.get());
2022 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002023}
2024
2025rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2026 const std::string& label,
2027 const InternalDataChannelInit* config) {
2028 if (IsClosed()) {
2029 return nullptr;
2030 }
2031 if (session_->data_channel_type() == cricket::DCT_NONE) {
2032 LOG(LS_ERROR)
2033 << "InternalCreateDataChannel: Data is not supported in this call.";
2034 return nullptr;
2035 }
2036 InternalDataChannelInit new_config =
2037 config ? (*config) : InternalDataChannelInit();
2038 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2039 if (new_config.id < 0) {
2040 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002041 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002042 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2043 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2044 return nullptr;
2045 }
2046 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2047 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2048 << "because the id is already in use or out of range.";
2049 return nullptr;
2050 }
2051 }
2052
2053 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2054 session_.get(), session_->data_channel_type(), label, new_config));
2055 if (!channel) {
2056 sid_allocator_.ReleaseSid(new_config.id);
2057 return nullptr;
2058 }
2059
2060 if (channel->data_channel_type() == cricket::DCT_RTP) {
2061 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2062 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2063 << " already exists.";
2064 return nullptr;
2065 }
2066 rtp_data_channels_[channel->label()] = channel;
2067 } else {
2068 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2069 sctp_data_channels_.push_back(channel);
2070 channel->SignalClosed.connect(this,
2071 &PeerConnection::OnSctpDataChannelClosed);
2072 }
2073
2074 return channel;
2075}
2076
2077bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002078#ifdef HAVE_QUIC
2079 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2080 (session_->quic_data_transport() &&
2081 session_->quic_data_transport()->HasDataChannels());
2082#else
deadbeefab9b2d12015-10-14 11:33:11 -07002083 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002084#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002085}
2086
2087void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2088 for (const auto& channel : sctp_data_channels_) {
2089 if (channel->id() < 0) {
2090 int sid;
2091 if (!sid_allocator_.AllocateSid(role, &sid)) {
2092 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2093 continue;
2094 }
2095 channel->SetSctpSid(sid);
2096 }
2097 }
2098}
2099
2100void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002101 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002102 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2103 ++it) {
2104 if (it->get() == channel) {
2105 if (channel->id() >= 0) {
2106 sid_allocator_.ReleaseSid(channel->id());
2107 }
deadbeefbd292462015-12-14 18:15:29 -08002108 // Since this method is triggered by a signal from the DataChannel,
2109 // we can't free it directly here; we need to free it asynchronously.
2110 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002111 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002112 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2113 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002114 return;
2115 }
2116 }
2117}
2118
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002119void PeerConnection::OnVoiceChannelCreated() {
2120 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2121 session_->voice_channel(), senders_, receivers_,
2122 cricket::MEDIA_TYPE_AUDIO);
2123}
2124
deadbeefab9b2d12015-10-14 11:33:11 -07002125void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002126 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2127 cricket::VoiceChannel>(
2128 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2129}
2130
2131void PeerConnection::OnVideoChannelCreated() {
2132 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2133 session_->video_channel(), senders_, receivers_,
2134 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002135}
2136
2137void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002138 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2139 cricket::VideoChannel>(
2140 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002141}
2142
2143void PeerConnection::OnDataChannelCreated() {
2144 for (const auto& channel : sctp_data_channels_) {
2145 channel->OnTransportChannelCreated();
2146 }
2147}
2148
2149void PeerConnection::OnDataChannelDestroyed() {
2150 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2151 // DataChannel may callback to us and try to modify the list.
2152 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2153 temp_rtp_dcs.swap(rtp_data_channels_);
2154 for (const auto& kv : temp_rtp_dcs) {
2155 kv.second->OnTransportChannelDestroyed();
2156 }
2157
2158 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2159 temp_sctp_dcs.swap(sctp_data_channels_);
2160 for (const auto& channel : temp_sctp_dcs) {
2161 channel->OnTransportChannelDestroyed();
2162 }
2163}
2164
2165void PeerConnection::OnDataChannelOpenMessage(
2166 const std::string& label,
2167 const InternalDataChannelInit& config) {
2168 rtc::scoped_refptr<DataChannel> channel(
2169 InternalCreateDataChannel(label, &config));
2170 if (!channel.get()) {
2171 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2172 return;
2173 }
2174
deadbeefa601f5c2016-06-06 14:27:39 -07002175 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2176 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002177 // Call both the raw pointer and scoped_refptr versions of the method
2178 // for compatibility.
2179 observer_->OnDataChannel(proxy_channel.get());
2180 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002181}
2182
deadbeefa601f5c2016-06-06 14:27:39 -07002183RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2184 auto it = std::find_if(
2185 senders_.begin(), senders_.end(),
2186 [id](const rtc::scoped_refptr<
2187 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2188 return sender->id() == id;
2189 });
2190 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002191}
2192
deadbeefa601f5c2016-06-06 14:27:39 -07002193std::vector<
2194 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002195PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2196 return std::find_if(
2197 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002198 [track](const rtc::scoped_refptr<
2199 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002200 return sender->track() == track;
2201 });
2202}
2203
deadbeefa601f5c2016-06-06 14:27:39 -07002204std::vector<rtc::scoped_refptr<
2205 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002206PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002207 return std::find_if(
2208 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002209 [track_id](const rtc::scoped_refptr<
2210 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002211 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002212 });
2213}
2214
deadbeefab9b2d12015-10-14 11:33:11 -07002215PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2216 cricket::MediaType media_type) {
2217 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2218 media_type == cricket::MEDIA_TYPE_VIDEO);
2219 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2220 : &remote_video_tracks_;
2221}
2222
2223PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2224 cricket::MediaType media_type) {
2225 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2226 media_type == cricket::MEDIA_TYPE_VIDEO);
2227 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2228 : &local_video_tracks_;
2229}
2230
2231const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2232 const PeerConnection::TrackInfos& infos,
2233 const std::string& stream_label,
2234 const std::string track_id) const {
2235 for (const TrackInfo& track_info : infos) {
2236 if (track_info.stream_label == stream_label &&
2237 track_info.track_id == track_id) {
2238 return &track_info;
2239 }
2240 }
2241 return nullptr;
2242}
2243
2244DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2245 for (const auto& channel : sctp_data_channels_) {
2246 if (channel->id() == sid) {
2247 return channel;
2248 }
2249 }
2250 return nullptr;
2251}
2252
deadbeef91dd5672016-05-18 16:55:30 -07002253bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002254 const RTCConfiguration& configuration) {
2255 cricket::ServerAddresses stun_servers;
2256 std::vector<cricket::RelayServerConfig> turn_servers;
2257 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2258 return false;
2259 }
2260
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002261 port_allocator_->Initialize();
2262
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002263 // To handle both internal and externally created port allocator, we will
2264 // enable BUNDLE here.
2265 int portallocator_flags = port_allocator_->flags();
2266 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2267 cricket::PORTALLOCATOR_ENABLE_IPV6;
2268 // If the disable-IPv6 flag was specified, we'll not override it
2269 // by experiment.
2270 if (configuration.disable_ipv6) {
2271 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2272 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2273 "Disabled") {
2274 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2275 }
2276
2277 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2278 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2279 LOG(LS_INFO) << "TCP candidates are disabled.";
2280 }
2281
honghaiz60347052016-05-31 18:29:12 -07002282 if (configuration.candidate_network_policy ==
2283 kCandidateNetworkPolicyLowCost) {
2284 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2285 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2286 }
2287
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002288 port_allocator_->set_flags(portallocator_flags);
2289 // No step delay is used while allocating ports.
2290 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2291 port_allocator_->set_candidate_filter(
2292 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2293
2294 // Call this last since it may create pooled allocator sessions using the
2295 // properties set above.
2296 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002297 configuration.ice_candidate_pool_size,
2298 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002299 return true;
2300}
2301
deadbeef91dd5672016-05-18 16:55:30 -07002302bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002303 const RTCConfiguration& configuration) {
2304 cricket::ServerAddresses stun_servers;
2305 std::vector<cricket::RelayServerConfig> turn_servers;
2306 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2307 return false;
2308 }
2309 port_allocator_->set_candidate_filter(
2310 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2311 // Call this last since it may create pooled allocator sessions using the
2312 // candidate filter set above.
2313 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002314 configuration.ice_candidate_pool_size,
2315 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002316 return true;
2317}
2318
ivoc14d5dbe2016-07-04 07:06:55 -07002319bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2320 int64_t max_size_bytes) {
2321 return media_controller_->call_w()->StartEventLog(file, max_size_bytes);
2322}
2323
2324void PeerConnection::StopRtcEventLog_w() {
2325 media_controller_->call_w()->StopEventLog();
2326}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327} // namespace webrtc