blob: 144b1c64b55862b066f595e3737d89a43a251d05 [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),
perkj68343a82016-08-29 23:51:13 -0700571 ice_state_(kIceNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000572 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700573 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700574 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700575 local_streams_(StreamCollection::Create()),
576 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000577
578PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100579 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700580 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700581 // Need to detach RTP senders/receivers from WebRtcSession,
582 // since it's about to be destroyed.
583 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700584 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700585 }
586 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700587 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700588 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700589 // Destroy stats_ because it depends on session_.
590 stats_.reset(nullptr);
591 // Now destroy session_ before destroying other members,
592 // because its destruction fires signals (such as VoiceChannelDestroyed)
593 // which will trigger some final actions in PeerConnection...
594 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700595 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700596 network_thread()->Invoke<void>(RTC_FROM_HERE,
597 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598}
599
600bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000601 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700602 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200603 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800604 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100605 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800606 RTC_DCHECK(observer != nullptr);
607 if (!observer) {
608 return false;
609 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000610 observer_ = observer;
611
kwiberg0eb15ed2015-12-17 03:04:15 -0800612 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800613
deadbeef91dd5672016-05-18 16:55:30 -0700614 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700615 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700616 if (!network_thread()->Invoke<bool>(
617 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
618 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619 return false;
620 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621
nissec36b31b2016-04-11 23:25:29 -0700622 media_controller_.reset(
623 factory_->CreateMediaController(configuration.media_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624
zhihuang29ff8442016-07-27 11:07:25 -0700625 session_.reset(new WebRtcSession(
626 media_controller_.get(), factory_->network_thread(),
627 factory_->worker_thread(), factory_->signaling_thread(),
628 port_allocator_.get(),
629 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700630 factory_->CreateTransportController(
631 port_allocator_.get(),
632 configuration.redetermine_role_on_ice_restart))));
zhihuang29ff8442016-07-27 11:07:25 -0700633
deadbeefab9b2d12015-10-14 11:33:11 -0700634 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700635 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700637 enable_ice_renomination_ = configuration.enable_ice_renomination;
638
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000639 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200640 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800641 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000642 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645 // Register PeerConnection as receiver of local ice candidates.
646 // All the callbacks will be posted to the application from PeerConnection.
647 session_->RegisterIceObserver(this);
648 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700649 session_->SignalVoiceChannelCreated.connect(
650 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700651 session_->SignalVoiceChannelDestroyed.connect(
652 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700653 session_->SignalVideoChannelCreated.connect(
654 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700655 session_->SignalVideoChannelDestroyed.connect(
656 this, &PeerConnection::OnVideoChannelDestroyed);
657 session_->SignalDataChannelCreated.connect(
658 this, &PeerConnection::OnDataChannelCreated);
659 session_->SignalDataChannelDestroyed.connect(
660 this, &PeerConnection::OnDataChannelDestroyed);
661 session_->SignalDataChannelOpenMessage.connect(
662 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663 return true;
664}
665
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000666rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700668 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669}
670
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000671rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700673 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674}
675
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000676bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100677 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678 if (IsClosed()) {
679 return false;
680 }
deadbeefab9b2d12015-10-14 11:33:11 -0700681 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 return false;
683 }
deadbeefab9b2d12015-10-14 11:33:11 -0700684
685 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800686 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
687 observer->SignalAudioTrackAdded.connect(this,
688 &PeerConnection::OnAudioTrackAdded);
689 observer->SignalAudioTrackRemoved.connect(
690 this, &PeerConnection::OnAudioTrackRemoved);
691 observer->SignalVideoTrackAdded.connect(this,
692 &PeerConnection::OnVideoTrackAdded);
693 observer->SignalVideoTrackRemoved.connect(
694 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700695 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700696
deadbeefab9b2d12015-10-14 11:33:11 -0700697 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800698 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700699 }
700 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800701 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700702 }
703
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000704 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705 observer_->OnRenegotiationNeeded();
706 return true;
707}
708
709void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100710 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700711 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800712 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700713 }
714 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800715 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700716 }
717
718 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800719 stream_observers_.erase(
720 std::remove_if(
721 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700722 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800723 return observer->stream()->label().compare(local_stream->label()) ==
724 0;
725 }),
726 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700727
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 if (IsClosed()) {
729 return;
730 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 observer_->OnRenegotiationNeeded();
732}
733
deadbeefe1f9d832016-01-14 15:35:42 -0800734rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
735 MediaStreamTrackInterface* track,
736 std::vector<MediaStreamInterface*> streams) {
737 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
738 if (IsClosed()) {
739 return nullptr;
740 }
741 if (streams.size() >= 2) {
742 LOG(LS_ERROR)
743 << "Adding a track with two streams is not currently supported.";
744 return nullptr;
745 }
746 // TODO(deadbeef): Support adding a track to two different senders.
747 if (FindSenderForTrack(track) != senders_.end()) {
748 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
749 return nullptr;
750 }
751
752 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700753 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800754 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700755 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800756 signaling_thread(),
757 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700758 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800759 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700760 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800761 }
762 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700763 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800764 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700765 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800766 }
767 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700768 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800769 signaling_thread(),
770 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700771 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800772 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700773 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800774 }
775 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700776 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800777 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700778 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800779 }
780 } else {
781 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
782 return rtc::scoped_refptr<RtpSenderInterface>();
783 }
784
785 senders_.push_back(new_sender);
786 observer_->OnRenegotiationNeeded();
787 return new_sender;
788}
789
790bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
791 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
792 if (IsClosed()) {
793 return false;
794 }
795
796 auto it = std::find(senders_.begin(), senders_.end(), sender);
797 if (it == senders_.end()) {
798 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
799 return false;
800 }
deadbeefa601f5c2016-06-06 14:27:39 -0700801 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800802 senders_.erase(it);
803
804 observer_->OnRenegotiationNeeded();
805 return true;
806}
807
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000808rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100810 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700811 if (IsClosed()) {
812 return nullptr;
813 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 if (!track) {
815 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
816 return NULL;
817 }
deadbeefab9b2d12015-10-14 11:33:11 -0700818 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
820 return NULL;
821 }
822
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000823 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824 DtmfSender::Create(track, signaling_thread(), session_.get()));
825 if (!sender.get()) {
826 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
827 return NULL;
828 }
829 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
830}
831
deadbeeffac06552015-11-25 11:26:01 -0800832rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800833 const std::string& kind,
834 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100835 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700836 if (IsClosed()) {
837 return nullptr;
838 }
deadbeefa601f5c2016-06-06 14:27:39 -0700839 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800840 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700841 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700842 signaling_thread(),
843 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800844 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700845 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700846 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800847 } else {
848 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800849 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800850 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800851 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700852 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800853 }
deadbeeffac06552015-11-25 11:26:01 -0800854 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800855 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800856}
857
deadbeef70ab1a12015-09-28 16:53:55 -0700858std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
859 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700860 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
861 for (const auto& sender : senders_) {
862 ret.push_back(sender.get());
863 }
864 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700865}
866
867std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
868PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700869 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
870 for (const auto& receiver : receivers_) {
871 ret.push_back(receiver.get());
872 }
873 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700874}
875
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000876bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000877 MediaStreamTrackInterface* track,
878 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100879 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700880 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000881 if (!VERIFY(observer != NULL)) {
882 LOG(LS_ERROR) << "GetStats - observer is NULL.";
883 return false;
884 }
885
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000886 stats_->UpdateStats(level);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700887 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000888 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 return true;
890}
891
hbos74e1a4f2016-09-15 23:33:01 -0700892void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
893 RTC_DCHECK(stats_collector_);
894 stats_collector_->GetStatsReport(callback);
895}
896
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
898 return signaling_state_;
899}
900
perkj68343a82016-08-29 23:51:13 -0700901PeerConnectionInterface::IceState PeerConnection::ice_state() {
902 return ice_state_;
903}
904
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905PeerConnectionInterface::IceConnectionState
906PeerConnection::ice_connection_state() {
907 return ice_connection_state_;
908}
909
910PeerConnectionInterface::IceGatheringState
911PeerConnection::ice_gathering_state() {
912 return ice_gathering_state_;
913}
914
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000915rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916PeerConnection::CreateDataChannel(
917 const std::string& label,
918 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100919 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700920#ifdef HAVE_QUIC
921 if (session_->data_channel_type() == cricket::DCT_QUIC) {
922 // TODO(zhihuang): Handle case when config is NULL.
923 if (!config) {
924 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
925 return nullptr;
926 }
927 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
928 if (!config->reliable || config->ordered) {
929 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
930 "ordered delivery.";
931 return nullptr;
932 }
933 return session_->quic_data_transport()->CreateDataChannel(label, config);
934 }
935#endif // HAVE_QUIC
936
deadbeefab9b2d12015-10-14 11:33:11 -0700937 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000938
kwibergd1fe2812016-04-27 06:47:29 -0700939 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000940 if (config) {
941 internal_config.reset(new InternalDataChannelInit(*config));
942 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000943 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700944 InternalCreateDataChannel(label, internal_config.get()));
945 if (!channel.get()) {
946 return nullptr;
947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000949 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
950 // the first SCTP DataChannel.
951 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
952 observer_->OnRenegotiationNeeded();
953 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000954
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 return DataChannelProxy::Create(signaling_thread(), channel.get());
956}
957
958void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
959 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100960 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700961 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
963 return;
964 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000965 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000966
967 bool value;
968 size_t mandatory_constraints = 0;
969
970 if (FindConstraint(constraints,
971 MediaConstraintsInterface::kOfferToReceiveAudio,
972 &value,
973 &mandatory_constraints)) {
974 options.offer_to_receive_audio =
975 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
976 }
977
978 if (FindConstraint(constraints,
979 MediaConstraintsInterface::kOfferToReceiveVideo,
980 &value,
981 &mandatory_constraints)) {
982 options.offer_to_receive_video =
983 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
984 }
985
986 if (FindConstraint(constraints,
987 MediaConstraintsInterface::kVoiceActivityDetection,
988 &value,
989 &mandatory_constraints)) {
990 options.voice_activity_detection = value;
991 }
992
993 if (FindConstraint(constraints,
994 MediaConstraintsInterface::kIceRestart,
995 &value,
996 &mandatory_constraints)) {
997 options.ice_restart = value;
998 }
999
1000 if (FindConstraint(constraints,
1001 MediaConstraintsInterface::kUseRtpMux,
1002 &value,
1003 &mandatory_constraints)) {
1004 options.use_rtp_mux = value;
1005 }
1006
1007 CreateOffer(observer, options);
1008}
1009
1010void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1011 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001012 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -07001013 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001014 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1015 return;
1016 }
deadbeefab9b2d12015-10-14 11:33:11 -07001017
1018 cricket::MediaSessionOptions session_options;
1019 if (!GetOptionsForOffer(options, &session_options)) {
1020 std::string error = "CreateOffer called with invalid options.";
1021 LOG(LS_ERROR) << error;
1022 PostCreateSessionDescriptionFailure(observer, error);
1023 return;
1024 }
1025
1026 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027}
1028
1029void PeerConnection::CreateAnswer(
1030 CreateSessionDescriptionObserver* observer,
1031 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001032 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -07001033 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1035 return;
1036 }
deadbeefab9b2d12015-10-14 11:33:11 -07001037
1038 cricket::MediaSessionOptions session_options;
1039 if (!GetOptionsForAnswer(constraints, &session_options)) {
1040 std::string error = "CreateAnswer called with invalid constraints.";
1041 LOG(LS_ERROR) << error;
1042 PostCreateSessionDescriptionFailure(observer, error);
1043 return;
1044 }
1045
htaa2a49d92016-03-04 02:51:39 -08001046 session_->CreateAnswer(observer, session_options);
1047}
1048
1049void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1050 const RTCOfferAnswerOptions& options) {
1051 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
1052 if (!VERIFY(observer != nullptr)) {
1053 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1054 return;
1055 }
1056
1057 cricket::MediaSessionOptions session_options;
1058 if (!GetOptionsForAnswer(options, &session_options)) {
1059 std::string error = "CreateAnswer called with invalid options.";
1060 LOG(LS_ERROR) << error;
1061 PostCreateSessionDescriptionFailure(observer, error);
1062 return;
1063 }
1064
1065 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066}
1067
1068void PeerConnection::SetLocalDescription(
1069 SetSessionDescriptionObserver* observer,
1070 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001071 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001072 if (IsClosed()) {
1073 return;
1074 }
deadbeefab9b2d12015-10-14 11:33:11 -07001075 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001076 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1077 return;
1078 }
1079 if (!desc) {
1080 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1081 return;
1082 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 // Update stats here so that we have the most recent stats for tracks and
1084 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001085 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086 std::string error;
1087 if (!session_->SetLocalDescription(desc, &error)) {
1088 PostSetSessionDescriptionFailure(observer, error);
1089 return;
1090 }
deadbeefab9b2d12015-10-14 11:33:11 -07001091
1092 // If setting the description decided our SSL role, allocate any necessary
1093 // SCTP sids.
1094 rtc::SSLRole role;
1095 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001096 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001097 AllocateSctpSids(role);
1098 }
1099
1100 // Update state and SSRC of local MediaStreams and DataChannels based on the
1101 // local session description.
1102 const cricket::ContentInfo* audio_content =
1103 GetFirstAudioContent(desc->description());
1104 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001105 if (audio_content->rejected) {
1106 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1107 } else {
1108 const cricket::AudioContentDescription* audio_desc =
1109 static_cast<const cricket::AudioContentDescription*>(
1110 audio_content->description);
1111 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1112 }
deadbeefab9b2d12015-10-14 11:33:11 -07001113 }
1114
1115 const cricket::ContentInfo* video_content =
1116 GetFirstVideoContent(desc->description());
1117 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001118 if (video_content->rejected) {
1119 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1120 } else {
1121 const cricket::VideoContentDescription* video_desc =
1122 static_cast<const cricket::VideoContentDescription*>(
1123 video_content->description);
1124 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1125 }
deadbeefab9b2d12015-10-14 11:33:11 -07001126 }
1127
1128 const cricket::ContentInfo* data_content =
1129 GetFirstDataContent(desc->description());
1130 if (data_content) {
1131 const cricket::DataContentDescription* data_desc =
1132 static_cast<const cricket::DataContentDescription*>(
1133 data_content->description);
1134 if (rtc::starts_with(data_desc->protocol().data(),
1135 cricket::kMediaProtocolRtpPrefix)) {
1136 UpdateLocalRtpDataChannels(data_desc->streams());
1137 }
1138 }
1139
1140 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001141 signaling_thread()->Post(RTC_FROM_HERE, this,
1142 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001143
deadbeefcbecd352015-09-23 11:50:27 -07001144 // MaybeStartGathering needs to be called after posting
1145 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1146 // before signaling that SetLocalDescription completed.
1147 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148}
1149
1150void PeerConnection::SetRemoteDescription(
1151 SetSessionDescriptionObserver* observer,
1152 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001153 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001154 if (IsClosed()) {
1155 return;
1156 }
deadbeefab9b2d12015-10-14 11:33:11 -07001157 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1159 return;
1160 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001161 if (!desc) {
1162 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1163 return;
1164 }
1165 // Update stats here so that we have the most recent stats for tracks and
1166 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001167 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 std::string error;
1169 if (!session_->SetRemoteDescription(desc, &error)) {
1170 PostSetSessionDescriptionFailure(observer, error);
1171 return;
1172 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173
deadbeefab9b2d12015-10-14 11:33:11 -07001174 // If setting the description decided our SSL role, allocate any necessary
1175 // SCTP sids.
1176 rtc::SSLRole role;
1177 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001178 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001179 AllocateSctpSids(role);
1180 }
1181
1182 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001183 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1184 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1185 const cricket::AudioContentDescription* audio_desc =
1186 GetFirstAudioContentDescription(remote_desc);
1187 const cricket::VideoContentDescription* video_desc =
1188 GetFirstVideoContentDescription(remote_desc);
1189 const cricket::DataContentDescription* data_desc =
1190 GetFirstDataContentDescription(remote_desc);
1191
1192 // Check if the descriptions include streams, just in case the peer supports
1193 // MSID, but doesn't indicate so with "a=msid-semantic".
1194 if (remote_desc->msid_supported() ||
1195 (audio_desc && !audio_desc->streams().empty()) ||
1196 (video_desc && !video_desc->streams().empty())) {
1197 remote_peer_supports_msid_ = true;
1198 }
deadbeefab9b2d12015-10-14 11:33:11 -07001199
1200 // We wait to signal new streams until we finish processing the description,
1201 // since only at that point will new streams have all their tracks.
1202 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1203
1204 // Find all audio rtp streams and create corresponding remote AudioTracks
1205 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001206 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001207 if (audio_content->rejected) {
1208 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1209 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001210 bool default_audio_track_needed =
1211 !remote_peer_supports_msid_ &&
1212 MediaContentDirectionHasSend(audio_desc->direction());
1213 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1214 default_audio_track_needed, audio_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 // Find all video rtp streams and create corresponding remote VideoTracks
1220 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001221 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001222 if (video_content->rejected) {
1223 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1224 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001225 bool default_video_track_needed =
1226 !remote_peer_supports_msid_ &&
1227 MediaContentDirectionHasSend(video_desc->direction());
1228 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1229 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001230 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001231 }
deadbeefab9b2d12015-10-14 11:33:11 -07001232 }
1233
1234 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001235 if (data_desc) {
1236 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001237 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001238 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001239 }
1240 }
1241
1242 // Iterate new_streams and notify the observer about new MediaStreams.
1243 for (size_t i = 0; i < new_streams->count(); ++i) {
1244 MediaStreamInterface* new_stream = new_streams->at(i);
1245 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001246 // Call both the raw pointer and scoped_refptr versions of the method
1247 // for compatibility.
deadbeefab9b2d12015-10-14 11:33:11 -07001248 observer_->OnAddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001249 observer_->OnAddStream(
1250 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001251 }
1252
deadbeefbda7e0b2015-12-08 17:13:40 -08001253 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001254
1255 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001256 signaling_thread()->Post(RTC_FROM_HERE, this,
1257 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001258}
1259
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001260bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001261 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001262 if (port_allocator_) {
deadbeef91dd5672016-05-18 16:55:30 -07001263 if (!network_thread()->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001264 RTC_FROM_HERE,
deadbeef91dd5672016-05-18 16:55:30 -07001265 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001266 configuration))) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001267 return false;
1268 }
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001269 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001270
1271 // TODO(deadbeef): Shouldn't have to hop to the worker thread twice...
1272 session_->SetIceConfig(session_->ParseIceConfig(configuration));
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001273
1274 enable_ice_renomination_ = configuration.enable_ice_renomination;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001275 return true;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001276}
1277
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278bool PeerConnection::AddIceCandidate(
1279 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001280 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001281 if (IsClosed()) {
1282 return false;
1283 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284 return session_->ProcessIceMessage(ice_candidate);
1285}
1286
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001287bool PeerConnection::RemoveIceCandidates(
1288 const std::vector<cricket::Candidate>& candidates) {
1289 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1290 return session_->RemoveRemoteIceCandidates(candidates);
1291}
1292
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001293void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001294 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001295 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001296
1297 if (session_) {
1298 session_->set_metrics_observer(uma_observer_);
1299 }
1300
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001301 // Send information about IPv4/IPv6 status.
1302 if (uma_observer_ && port_allocator_) {
1303 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001304 uma_observer_->IncrementEnumCounter(
1305 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1306 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001307 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001308 uma_observer_->IncrementEnumCounter(
1309 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1310 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001311 }
1312 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001313}
1314
ivoc14d5dbe2016-07-04 07:06:55 -07001315bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1316 int64_t max_size_bytes) {
1317 return factory_->worker_thread()->Invoke<bool>(
1318 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1319 max_size_bytes));
1320}
1321
1322void PeerConnection::StopRtcEventLog() {
1323 factory_->worker_thread()->Invoke<void>(
1324 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1325}
1326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327const SessionDescriptionInterface* PeerConnection::local_description() const {
1328 return session_->local_description();
1329}
1330
1331const SessionDescriptionInterface* PeerConnection::remote_description() const {
1332 return session_->remote_description();
1333}
1334
1335void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001336 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 // Update stats here so that we have the most recent stats for tracks and
1338 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001339 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340
deadbeefd59daf82015-10-14 15:02:44 -07001341 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342}
1343
deadbeefd59daf82015-10-14 15:02:44 -07001344void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1345 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001347 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001349 break;
deadbeefd59daf82015-10-14 15:02:44 -07001350 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1352 break;
deadbeefd59daf82015-10-14 15:02:44 -07001353 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1355 break;
deadbeefd59daf82015-10-14 15:02:44 -07001356 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1358 break;
deadbeefd59daf82015-10-14 15:02:44 -07001359 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1361 break;
deadbeefd59daf82015-10-14 15:02:44 -07001362 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChangeSignalingState(PeerConnectionInterface::kStable);
1364 break;
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kClosed);
1367 break;
1368 default:
1369 break;
1370 }
1371}
1372
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001373void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1376 SetSessionDescriptionMsg* param =
1377 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1378 param->observer->OnSuccess();
1379 delete param;
1380 break;
1381 }
1382 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1383 SetSessionDescriptionMsg* param =
1384 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1385 param->observer->OnFailure(param->error);
1386 delete param;
1387 break;
1388 }
deadbeefab9b2d12015-10-14 11:33:11 -07001389 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1390 CreateSessionDescriptionMsg* param =
1391 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1392 param->observer->OnFailure(param->error);
1393 delete param;
1394 break;
1395 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 case MSG_GETSTATS: {
1397 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001398 StatsReports reports;
1399 stats_->GetStats(param->track, &reports);
1400 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 delete param;
1402 break;
1403 }
deadbeefbd292462015-12-14 18:15:29 -08001404 case MSG_FREE_DATACHANNELS: {
1405 sctp_data_channels_to_free_.clear();
1406 break;
1407 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001409 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410 break;
1411 }
1412}
1413
deadbeefab9b2d12015-10-14 11:33:11 -07001414void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001415 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001416 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001417 receivers_.push_back(
1418 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001419 signaling_thread(), new AudioRtpReceiver(stream, track_id, ssrc,
1420 session_->voice_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001421}
1422
deadbeefab9b2d12015-10-14 11:33:11 -07001423void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001424 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001425 uint32_t ssrc) {
deadbeefa601f5c2016-06-06 14:27:39 -07001426 receivers_.push_back(
1427 RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1428 signaling_thread(),
1429 new VideoRtpReceiver(stream, track_id, factory_->worker_thread(),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001430 ssrc, session_->video_channel())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001431}
1432
deadbeef70ab1a12015-09-28 16:53:55 -07001433// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1434// description.
perkjd61bf802016-03-24 03:16:19 -07001435void PeerConnection::DestroyReceiver(const std::string& track_id) {
1436 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001437 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001438 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001439 << " doesn't exist.";
1440 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001441 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001442 receivers_.erase(it);
1443 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444}
1445
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446void PeerConnection::OnIceConnectionChange(
1447 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001448 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001449 // After transitioning to "closed", ignore any additional states from
1450 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001451 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001452 return;
1453 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001455 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456}
1457
1458void PeerConnection::OnIceGatheringChange(
1459 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001460 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 if (IsClosed()) {
1462 return;
1463 }
1464 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001465 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466}
1467
1468void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001469 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001470 if (IsClosed()) {
1471 return;
1472 }
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001473 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474}
1475
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001476void PeerConnection::OnIceCandidatesRemoved(
1477 const std::vector<cricket::Candidate>& candidates) {
1478 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001479 if (IsClosed()) {
1480 return;
1481 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001482 observer_->OnIceCandidatesRemoved(candidates);
1483}
1484
Peter Thatcher54360512015-07-08 11:08:35 -07001485void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001486 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001487 if (IsClosed()) {
1488 return;
1489 }
Peter Thatcher54360512015-07-08 11:08:35 -07001490 observer_->OnIceConnectionReceivingChange(receiving);
1491}
1492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493void PeerConnection::ChangeSignalingState(
1494 PeerConnectionInterface::SignalingState signaling_state) {
1495 signaling_state_ = signaling_state;
1496 if (signaling_state == kClosed) {
1497 ice_connection_state_ = kIceConnectionClosed;
1498 observer_->OnIceConnectionChange(ice_connection_state_);
1499 if (ice_gathering_state_ != kIceGatheringComplete) {
1500 ice_gathering_state_ = kIceGatheringComplete;
1501 observer_->OnIceGatheringChange(ice_gathering_state_);
1502 }
1503 }
1504 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505}
1506
deadbeefeb459812015-12-15 19:24:43 -08001507void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1508 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001509 if (IsClosed()) {
1510 return;
1511 }
deadbeefeb459812015-12-15 19:24:43 -08001512 auto sender = FindSenderForTrack(track);
1513 if (sender != senders_.end()) {
1514 // We already have a sender for this track, so just change the stream_id
1515 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001516 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001517 return;
1518 }
1519
1520 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001521 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1522 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001523 signaling_thread(),
1524 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1525 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001526 senders_.push_back(new_sender);
1527 // If the sender has already been configured in SDP, we call SetSsrc,
1528 // which will connect the sender to the underlying transport. This can
1529 // occur if a local session description that contains the ID of the sender
1530 // is set before AddStream is called. It can also occur if the local
1531 // session description is not changed and RemoveStream is called, and
1532 // later AddStream is called again with the same stream.
1533 const TrackInfo* track_info =
1534 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1535 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001536 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001537 }
1538}
1539
1540// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1541// indefinitely, when we have unified plan SDP.
1542void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1543 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001544 if (IsClosed()) {
1545 return;
1546 }
deadbeefeb459812015-12-15 19:24:43 -08001547 auto sender = FindSenderForTrack(track);
1548 if (sender == senders_.end()) {
1549 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1550 << " doesn't exist.";
1551 return;
1552 }
deadbeefa601f5c2016-06-06 14:27:39 -07001553 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001554 senders_.erase(sender);
1555}
1556
1557void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1558 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001559 if (IsClosed()) {
1560 return;
1561 }
deadbeefeb459812015-12-15 19:24:43 -08001562 auto sender = FindSenderForTrack(track);
1563 if (sender != senders_.end()) {
1564 // We already have a sender for this track, so just change the stream_id
1565 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001566 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001567 return;
1568 }
1569
1570 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001571 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1572 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001573 signaling_thread(), new VideoRtpSender(track, stream->label(),
1574 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001575 senders_.push_back(new_sender);
1576 const TrackInfo* track_info =
1577 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1578 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001579 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001580 }
1581}
1582
1583void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1584 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001585 if (IsClosed()) {
1586 return;
1587 }
deadbeefeb459812015-12-15 19:24:43 -08001588 auto sender = FindSenderForTrack(track);
1589 if (sender == senders_.end()) {
1590 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1591 << " doesn't exist.";
1592 return;
1593 }
deadbeefa601f5c2016-06-06 14:27:39 -07001594 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001595 senders_.erase(sender);
1596}
1597
deadbeefab9b2d12015-10-14 11:33:11 -07001598void PeerConnection::PostSetSessionDescriptionFailure(
1599 SetSessionDescriptionObserver* observer,
1600 const std::string& error) {
1601 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1602 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001603 signaling_thread()->Post(RTC_FROM_HERE, this,
1604 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001605}
1606
1607void PeerConnection::PostCreateSessionDescriptionFailure(
1608 CreateSessionDescriptionObserver* observer,
1609 const std::string& error) {
1610 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1611 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001612 signaling_thread()->Post(RTC_FROM_HERE, this,
1613 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001614}
1615
1616bool PeerConnection::GetOptionsForOffer(
1617 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1618 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001619 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1620 // ContentInfos.
1621 if (session_->local_description()) {
1622 for (const cricket::ContentInfo& content :
1623 session_->local_description()->description()->contents()) {
1624 session_options->transport_options[content.name] =
1625 cricket::TransportOptions();
1626 }
1627 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001628 session_options->enable_ice_renomination = enable_ice_renomination_;
1629
htaaac2dea2016-03-10 13:35:55 -08001630 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001631 return false;
1632 }
1633
deadbeeffac06552015-11-25 11:26:01 -08001634 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001635 // Offer to receive audio/video if the constraint is not set and there are
1636 // send streams, or we're currently receiving.
1637 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1638 session_options->recv_audio =
1639 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1640 !remote_audio_tracks_.empty();
1641 }
1642 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1643 session_options->recv_video =
1644 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1645 !remote_video_tracks_.empty();
1646 }
1647 session_options->bundle_enabled =
1648 session_options->bundle_enabled &&
1649 (session_options->has_audio() || session_options->has_video() ||
1650 session_options->has_data());
1651
zhihuang9763d562016-08-05 11:14:50 -07001652 // Intentionally unset the data channel type for RTP data channel with the
1653 // second condition. Otherwise the RTP data channels would be successfully
1654 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1655 // when building with chromium. We want to leave RTP data channels broken, so
1656 // people won't try to use them.
1657 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1658 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001659 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001660
1661 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001662 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001663 return true;
1664}
1665
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001666void PeerConnection::InitializeOptionsForAnswer(
1667 cricket::MediaSessionOptions* session_options) {
1668 session_options->recv_audio = false;
1669 session_options->recv_video = false;
1670 session_options->enable_ice_renomination = enable_ice_renomination_;
1671}
1672
htaa2a49d92016-03-04 02:51:39 -08001673void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001674 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001675 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1676 // ContentInfos.
1677 if (session_->remote_description()) {
1678 // Initialize the transport_options map.
1679 for (const cricket::ContentInfo& content :
1680 session_->remote_description()->description()->contents()) {
1681 session_options->transport_options[content.name] =
1682 cricket::TransportOptions();
1683 }
1684 }
deadbeeffac06552015-11-25 11:26:01 -08001685 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001686 session_options->bundle_enabled =
1687 session_options->bundle_enabled &&
1688 (session_options->has_audio() || session_options->has_video() ||
1689 session_options->has_data());
1690
deadbeefab9b2d12015-10-14 11:33:11 -07001691 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1692 // are not signaled in the SDP so does not go through that path and must be
1693 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001694 // Intentionally unset the data channel type for RTP data channel. Otherwise
1695 // the RTP data channels would be successfully negotiated by default and the
1696 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1697 // We want to leave RTP data channels broken, so people won't try to use them.
1698 if (session_->data_channel_type() != cricket::DCT_RTP) {
1699 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001700 }
jbauchcb560652016-08-04 05:20:32 -07001701 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001702}
1703
1704bool PeerConnection::GetOptionsForAnswer(
1705 const MediaConstraintsInterface* constraints,
1706 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001707 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001708 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1709 return false;
1710 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001711 session_options->rtcp_cname = rtcp_cname_;
1712
htaa2a49d92016-03-04 02:51:39 -08001713 FinishOptionsForAnswer(session_options);
1714 return true;
1715}
1716
1717bool PeerConnection::GetOptionsForAnswer(
1718 const RTCOfferAnswerOptions& options,
1719 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001720 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001721 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001722 return false;
1723 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001724 session_options->rtcp_cname = rtcp_cname_;
1725
htaa2a49d92016-03-04 02:51:39 -08001726 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001727 return true;
1728}
1729
deadbeeffaac4972015-11-12 15:33:07 -08001730void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1731 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001732 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1733 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001734}
1735
deadbeefab9b2d12015-10-14 11:33:11 -07001736void PeerConnection::UpdateRemoteStreamsList(
1737 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001738 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001739 cricket::MediaType media_type,
1740 StreamCollection* new_streams) {
1741 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1742
1743 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001744 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001745 auto track_it = current_tracks->begin();
1746 while (track_it != current_tracks->end()) {
1747 const TrackInfo& info = *track_it;
1748 const cricket::StreamParams* params =
1749 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001750 bool track_exists = params && params->id == info.track_id;
1751 // If this is a default track, and we still need it, don't remove it.
1752 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1753 track_exists) {
1754 ++track_it;
1755 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001756 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1757 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001758 }
1759 }
1760
1761 // Find new and active tracks.
1762 for (const cricket::StreamParams& params : streams) {
1763 // The sync_label is the MediaStream label and the |stream.id| is the
1764 // track id.
1765 const std::string& stream_label = params.sync_label;
1766 const std::string& track_id = params.id;
1767 uint32_t ssrc = params.first_ssrc();
1768
1769 rtc::scoped_refptr<MediaStreamInterface> stream =
1770 remote_streams_->find(stream_label);
1771 if (!stream) {
1772 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001773 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1774 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001775 remote_streams_->AddStream(stream);
1776 new_streams->AddStream(stream);
1777 }
1778
1779 const TrackInfo* track_info =
1780 FindTrackInfo(*current_tracks, stream_label, track_id);
1781 if (!track_info) {
1782 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1783 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1784 }
1785 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001786
1787 // Add default track if necessary.
1788 if (default_track_needed) {
1789 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1790 remote_streams_->find(kDefaultStreamLabel);
1791 if (!default_stream) {
1792 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001793 default_stream = MediaStreamProxy::Create(
1794 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001795 remote_streams_->AddStream(default_stream);
1796 new_streams->AddStream(default_stream);
1797 }
1798 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1799 ? kDefaultAudioTrackLabel
1800 : kDefaultVideoTrackLabel;
1801 const TrackInfo* default_track_info =
1802 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1803 if (!default_track_info) {
1804 current_tracks->push_back(
1805 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1806 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1807 }
1808 }
deadbeefab9b2d12015-10-14 11:33:11 -07001809}
1810
1811void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1812 const std::string& track_id,
1813 uint32_t ssrc,
1814 cricket::MediaType media_type) {
1815 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1816
1817 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001818 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001819 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001820 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001821 } else {
1822 RTC_DCHECK(false && "Invalid media type");
1823 }
1824}
1825
1826void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1827 const std::string& track_id,
1828 cricket::MediaType media_type) {
1829 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1830
1831 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001832 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1833 // will be notified which will end the AudioRtpReceiver::track().
1834 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001835 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1836 stream->FindAudioTrack(track_id);
1837 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001838 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001839 }
1840 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001841 // Stopping or destroying a VideoRtpReceiver will end the
1842 // VideoRtpReceiver::track().
1843 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001844 rtc::scoped_refptr<VideoTrackInterface> video_track =
1845 stream->FindVideoTrack(track_id);
1846 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001847 // There's no guarantee the track is still available, e.g. the track may
1848 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001849 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001850 }
1851 } else {
1852 ASSERT(false && "Invalid media type");
1853 }
1854}
1855
1856void PeerConnection::UpdateEndedRemoteMediaStreams() {
1857 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1858 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1859 MediaStreamInterface* stream = remote_streams_->at(i);
1860 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1861 streams_to_remove.push_back(stream);
1862 }
1863 }
1864
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001865 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001866 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001867 // Call both the raw pointer and scoped_refptr versions of the method
1868 // for compatibility.
1869 observer_->OnRemoveStream(stream.get());
1870 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001871 }
1872}
1873
deadbeefab9b2d12015-10-14 11:33:11 -07001874void PeerConnection::UpdateLocalTracks(
1875 const std::vector<cricket::StreamParams>& streams,
1876 cricket::MediaType media_type) {
1877 TrackInfos* current_tracks = GetLocalTracks(media_type);
1878
1879 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1880 // don't match the new StreamParam.
1881 TrackInfos::iterator track_it = current_tracks->begin();
1882 while (track_it != current_tracks->end()) {
1883 const TrackInfo& info = *track_it;
1884 const cricket::StreamParams* params =
1885 cricket::GetStreamBySsrc(streams, info.ssrc);
1886 if (!params || params->id != info.track_id ||
1887 params->sync_label != info.stream_label) {
1888 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1889 media_type);
1890 track_it = current_tracks->erase(track_it);
1891 } else {
1892 ++track_it;
1893 }
1894 }
1895
1896 // Find new and active tracks.
1897 for (const cricket::StreamParams& params : streams) {
1898 // The sync_label is the MediaStream label and the |stream.id| is the
1899 // track id.
1900 const std::string& stream_label = params.sync_label;
1901 const std::string& track_id = params.id;
1902 uint32_t ssrc = params.first_ssrc();
1903 const TrackInfo* track_info =
1904 FindTrackInfo(*current_tracks, stream_label, track_id);
1905 if (!track_info) {
1906 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1907 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1908 }
1909 }
1910}
1911
1912void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1913 const std::string& track_id,
1914 uint32_t ssrc,
1915 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001916 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001917 if (!sender) {
1918 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1919 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001920 return;
1921 }
1922
deadbeeffac06552015-11-25 11:26:01 -08001923 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->set_stream_id(stream_label);
1930 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001931}
1932
1933void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1934 const std::string& track_id,
1935 uint32_t ssrc,
1936 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001937 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001938 if (!sender) {
1939 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001940 // SessionDescriptions has been renegotiated.
1941 return;
1942 }
deadbeeffac06552015-11-25 11:26:01 -08001943
1944 // A sender has been removed from the SessionDescription but it's still
1945 // associated with the PeerConnection. This only occurs if the SDP doesn't
1946 // match with the calls to CreateSender, AddStream and RemoveStream.
1947 if (sender->media_type() != media_type) {
1948 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1949 << " description with an unexpected media type.";
1950 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001951 }
deadbeeffac06552015-11-25 11:26:01 -08001952
1953 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001954}
1955
1956void PeerConnection::UpdateLocalRtpDataChannels(
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 // |it->sync_label| is actually the data channel label. The reason is that
1963 // we use the same naming of data channels as we do for
1964 // MediaStreams and Tracks.
1965 // For MediaStreams, the sync_label is the MediaStream label and the
1966 // track label is the same as |streamid|.
1967 const std::string& channel_label = params.sync_label;
1968 auto data_channel_it = rtp_data_channels_.find(channel_label);
1969 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1970 continue;
1971 }
1972 // Set the SSRC the data channel should use for sending.
1973 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1974 existing_channels.push_back(data_channel_it->first);
1975 }
1976
1977 UpdateClosingRtpDataChannels(existing_channels, true);
1978}
1979
1980void PeerConnection::UpdateRemoteRtpDataChannels(
1981 const cricket::StreamParamsVec& streams) {
1982 std::vector<std::string> existing_channels;
1983
1984 // Find new and active data channels.
1985 for (const cricket::StreamParams& params : streams) {
1986 // The data channel label is either the mslabel or the SSRC if the mslabel
1987 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1988 std::string label = params.sync_label.empty()
1989 ? rtc::ToString(params.first_ssrc())
1990 : params.sync_label;
1991 auto data_channel_it = rtp_data_channels_.find(label);
1992 if (data_channel_it == rtp_data_channels_.end()) {
1993 // This is a new data channel.
1994 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1995 } else {
1996 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1997 }
1998 existing_channels.push_back(label);
1999 }
2000
2001 UpdateClosingRtpDataChannels(existing_channels, false);
2002}
2003
2004void PeerConnection::UpdateClosingRtpDataChannels(
2005 const std::vector<std::string>& active_channels,
2006 bool is_local_update) {
2007 auto it = rtp_data_channels_.begin();
2008 while (it != rtp_data_channels_.end()) {
2009 DataChannel* data_channel = it->second;
2010 if (std::find(active_channels.begin(), active_channels.end(),
2011 data_channel->label()) != active_channels.end()) {
2012 ++it;
2013 continue;
2014 }
2015
2016 if (is_local_update) {
2017 data_channel->SetSendSsrc(0);
2018 } else {
2019 data_channel->RemotePeerRequestClose();
2020 }
2021
2022 if (data_channel->state() == DataChannel::kClosed) {
2023 rtp_data_channels_.erase(it);
2024 it = rtp_data_channels_.begin();
2025 } else {
2026 ++it;
2027 }
2028 }
2029}
2030
2031void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2032 uint32_t remote_ssrc) {
2033 rtc::scoped_refptr<DataChannel> channel(
2034 InternalCreateDataChannel(label, nullptr));
2035 if (!channel.get()) {
2036 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2037 << "CreateDataChannel failed.";
2038 return;
2039 }
2040 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002041 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2042 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002043 // Call both the raw pointer and scoped_refptr versions of the method
2044 // for compatibility.
2045 observer_->OnDataChannel(proxy_channel.get());
2046 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002047}
2048
2049rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2050 const std::string& label,
2051 const InternalDataChannelInit* config) {
2052 if (IsClosed()) {
2053 return nullptr;
2054 }
2055 if (session_->data_channel_type() == cricket::DCT_NONE) {
2056 LOG(LS_ERROR)
2057 << "InternalCreateDataChannel: Data is not supported in this call.";
2058 return nullptr;
2059 }
2060 InternalDataChannelInit new_config =
2061 config ? (*config) : InternalDataChannelInit();
2062 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2063 if (new_config.id < 0) {
2064 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08002065 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002066 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2067 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2068 return nullptr;
2069 }
2070 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2071 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2072 << "because the id is already in use or out of range.";
2073 return nullptr;
2074 }
2075 }
2076
2077 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2078 session_.get(), session_->data_channel_type(), label, new_config));
2079 if (!channel) {
2080 sid_allocator_.ReleaseSid(new_config.id);
2081 return nullptr;
2082 }
2083
2084 if (channel->data_channel_type() == cricket::DCT_RTP) {
2085 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2086 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2087 << " already exists.";
2088 return nullptr;
2089 }
2090 rtp_data_channels_[channel->label()] = channel;
2091 } else {
2092 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2093 sctp_data_channels_.push_back(channel);
2094 channel->SignalClosed.connect(this,
2095 &PeerConnection::OnSctpDataChannelClosed);
2096 }
2097
2098 return channel;
2099}
2100
2101bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002102#ifdef HAVE_QUIC
2103 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2104 (session_->quic_data_transport() &&
2105 session_->quic_data_transport()->HasDataChannels());
2106#else
deadbeefab9b2d12015-10-14 11:33:11 -07002107 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002108#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002109}
2110
2111void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2112 for (const auto& channel : sctp_data_channels_) {
2113 if (channel->id() < 0) {
2114 int sid;
2115 if (!sid_allocator_.AllocateSid(role, &sid)) {
2116 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2117 continue;
2118 }
2119 channel->SetSctpSid(sid);
2120 }
2121 }
2122}
2123
2124void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002125 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002126 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2127 ++it) {
2128 if (it->get() == channel) {
2129 if (channel->id() >= 0) {
2130 sid_allocator_.ReleaseSid(channel->id());
2131 }
deadbeefbd292462015-12-14 18:15:29 -08002132 // Since this method is triggered by a signal from the DataChannel,
2133 // we can't free it directly here; we need to free it asynchronously.
2134 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002135 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002136 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2137 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002138 return;
2139 }
2140 }
2141}
2142
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002143void PeerConnection::OnVoiceChannelCreated() {
2144 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2145 session_->voice_channel(), senders_, receivers_,
2146 cricket::MEDIA_TYPE_AUDIO);
2147}
2148
deadbeefab9b2d12015-10-14 11:33:11 -07002149void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002150 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2151 cricket::VoiceChannel>(
2152 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2153}
2154
2155void PeerConnection::OnVideoChannelCreated() {
2156 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2157 session_->video_channel(), senders_, receivers_,
2158 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002159}
2160
2161void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002162 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2163 cricket::VideoChannel>(
2164 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002165}
2166
2167void PeerConnection::OnDataChannelCreated() {
2168 for (const auto& channel : sctp_data_channels_) {
2169 channel->OnTransportChannelCreated();
2170 }
2171}
2172
2173void PeerConnection::OnDataChannelDestroyed() {
2174 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2175 // DataChannel may callback to us and try to modify the list.
2176 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2177 temp_rtp_dcs.swap(rtp_data_channels_);
2178 for (const auto& kv : temp_rtp_dcs) {
2179 kv.second->OnTransportChannelDestroyed();
2180 }
2181
2182 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2183 temp_sctp_dcs.swap(sctp_data_channels_);
2184 for (const auto& channel : temp_sctp_dcs) {
2185 channel->OnTransportChannelDestroyed();
2186 }
2187}
2188
2189void PeerConnection::OnDataChannelOpenMessage(
2190 const std::string& label,
2191 const InternalDataChannelInit& config) {
2192 rtc::scoped_refptr<DataChannel> channel(
2193 InternalCreateDataChannel(label, &config));
2194 if (!channel.get()) {
2195 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2196 return;
2197 }
2198
deadbeefa601f5c2016-06-06 14:27:39 -07002199 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2200 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002201 // Call both the raw pointer and scoped_refptr versions of the method
2202 // for compatibility.
2203 observer_->OnDataChannel(proxy_channel.get());
2204 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002205}
2206
deadbeefa601f5c2016-06-06 14:27:39 -07002207RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2208 auto it = std::find_if(
2209 senders_.begin(), senders_.end(),
2210 [id](const rtc::scoped_refptr<
2211 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2212 return sender->id() == id;
2213 });
2214 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002215}
2216
deadbeefa601f5c2016-06-06 14:27:39 -07002217std::vector<
2218 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002219PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2220 return std::find_if(
2221 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002222 [track](const rtc::scoped_refptr<
2223 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002224 return sender->track() == track;
2225 });
2226}
2227
deadbeefa601f5c2016-06-06 14:27:39 -07002228std::vector<rtc::scoped_refptr<
2229 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002230PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002231 return std::find_if(
2232 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002233 [track_id](const rtc::scoped_refptr<
2234 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002235 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002236 });
2237}
2238
deadbeefab9b2d12015-10-14 11:33:11 -07002239PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2240 cricket::MediaType media_type) {
2241 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2242 media_type == cricket::MEDIA_TYPE_VIDEO);
2243 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2244 : &remote_video_tracks_;
2245}
2246
2247PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2248 cricket::MediaType media_type) {
2249 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2250 media_type == cricket::MEDIA_TYPE_VIDEO);
2251 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2252 : &local_video_tracks_;
2253}
2254
2255const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2256 const PeerConnection::TrackInfos& infos,
2257 const std::string& stream_label,
2258 const std::string track_id) const {
2259 for (const TrackInfo& track_info : infos) {
2260 if (track_info.stream_label == stream_label &&
2261 track_info.track_id == track_id) {
2262 return &track_info;
2263 }
2264 }
2265 return nullptr;
2266}
2267
2268DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2269 for (const auto& channel : sctp_data_channels_) {
2270 if (channel->id() == sid) {
2271 return channel;
2272 }
2273 }
2274 return nullptr;
2275}
2276
deadbeef91dd5672016-05-18 16:55:30 -07002277bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002278 const RTCConfiguration& configuration) {
2279 cricket::ServerAddresses stun_servers;
2280 std::vector<cricket::RelayServerConfig> turn_servers;
2281 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2282 return false;
2283 }
2284
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002285 port_allocator_->Initialize();
2286
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002287 // To handle both internal and externally created port allocator, we will
2288 // enable BUNDLE here.
2289 int portallocator_flags = port_allocator_->flags();
2290 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
2291 cricket::PORTALLOCATOR_ENABLE_IPV6;
2292 // If the disable-IPv6 flag was specified, we'll not override it
2293 // by experiment.
2294 if (configuration.disable_ipv6) {
2295 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2296 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
2297 "Disabled") {
2298 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2299 }
2300
2301 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2302 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2303 LOG(LS_INFO) << "TCP candidates are disabled.";
2304 }
2305
honghaiz60347052016-05-31 18:29:12 -07002306 if (configuration.candidate_network_policy ==
2307 kCandidateNetworkPolicyLowCost) {
2308 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2309 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2310 }
2311
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002312 port_allocator_->set_flags(portallocator_flags);
2313 // No step delay is used while allocating ports.
2314 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2315 port_allocator_->set_candidate_filter(
2316 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2317
2318 // Call this last since it may create pooled allocator sessions using the
2319 // properties set above.
2320 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002321 configuration.ice_candidate_pool_size,
2322 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002323 return true;
2324}
2325
deadbeef91dd5672016-05-18 16:55:30 -07002326bool PeerConnection::ReconfigurePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002327 const RTCConfiguration& configuration) {
2328 cricket::ServerAddresses stun_servers;
2329 std::vector<cricket::RelayServerConfig> turn_servers;
2330 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
2331 return false;
2332 }
2333 port_allocator_->set_candidate_filter(
2334 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2335 // Call this last since it may create pooled allocator sessions using the
2336 // candidate filter set above.
2337 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002338 configuration.ice_candidate_pool_size,
2339 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002340 return true;
2341}
2342
ivoc14d5dbe2016-07-04 07:06:55 -07002343bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2344 int64_t max_size_bytes) {
2345 return media_controller_->call_w()->StartEventLog(file, max_size_bytes);
2346}
2347
2348void PeerConnection::StopRtcEventLog_w() {
2349 media_controller_->call_w()->StopEventLog();
2350}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002351} // namespace webrtc