blob: ee359271c2fc2573b2f209d9af2c365ed6a5970c [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"
28#include "webrtc/api/remotevideocapturer.h"
29#include "webrtc/api/rtpreceiver.h"
30#include "webrtc/api/rtpsender.h"
31#include "webrtc/api/streamcollection.h"
32#include "webrtc/api/videosource.h"
33#include "webrtc/api/videotrack.h"
tfarina5237aaf2015-11-10 23:44:30 -080034#include "webrtc/base/arraysize.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"
kjellandera96e2d72016-02-04 23:52:28 -080039#include "webrtc/media/sctp/sctpdataengine.h"
tfarina5237aaf2015-11-10 23:44:30 -080040#include "webrtc/p2p/client/basicportallocator.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;
deadbeeffac06552015-11-25 11:26:01 -080050using webrtc::RtpSenderInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070051using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052
deadbeefab9b2d12015-10-14 11:33:11 -070053static const char kDefaultStreamLabel[] = "default";
54static const char kDefaultAudioTrackLabel[] = "defaulta0";
55static const char kDefaultVideoTrackLabel[] = "defaultv0";
56
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057// The min number of tokens must present in Turn host uri.
58// e.g. user@turn.example.org
59static const size_t kTurnHostTokensNum = 2;
60// Number of tokens must be preset when TURN uri has transport param.
61static const size_t kTurnTransportTokensNum = 2;
62// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000063static const int kDefaultStunPort = 3478;
64static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066
67// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070068static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069
deadbeef0a6c4ca2015-10-06 11:38:28 -070070// NOTE: A loop below assumes that the first value of this enum is 0 and all
71// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070073 STUN = 0, // Indicates a STUN server.
74 STUNS, // Indicates a STUN server used with a TLS session.
75 TURN, // Indicates a TURN server
76 TURNS, // Indicates a TURN server used with a TLS session.
77 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078};
tfarina5237aaf2015-11-10 23:44:30 -080079static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070080 "kValidIceServiceTypes must have as many strings as ServiceType "
81 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082
83enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000084 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070086 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080088 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089};
90
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000091struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092 explicit SetSessionDescriptionMsg(
93 webrtc::SetSessionDescriptionObserver* observer)
94 : observer(observer) {
95 }
96
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000097 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098 std::string error;
99};
100
deadbeefab9b2d12015-10-14 11:33:11 -0700101struct CreateSessionDescriptionMsg : public rtc::MessageData {
102 explicit CreateSessionDescriptionMsg(
103 webrtc::CreateSessionDescriptionObserver* observer)
104 : observer(observer) {}
105
106 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
107 std::string error;
108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000110struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000111 GetStatsMsg(webrtc::StatsObserver* observer,
112 webrtc::MediaStreamTrackInterface* track)
113 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000116 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117};
118
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000119// |in_str| should be of format
120// stunURI = scheme ":" stun-host [ ":" stun-port ]
121// scheme = "stun" / "stuns"
122// stun-host = IP-literal / IPv4address / reg-name
123// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700124//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000125// draft-petithuguenin-behave-turn-uris-01
126// turnURI = scheme ":" turn-host [ ":" turn-port ]
127// turn-host = username@IP-literal / IPv4address / reg-name
128bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
129 ServiceType* service_type,
130 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200131 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700132 if (colonpos == std::string::npos) {
133 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000134 return false;
135 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700136 if ((colonpos + 1) == in_str.length()) {
137 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
138 return false;
139 }
140 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800141 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700142 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000143 *service_type = static_cast<ServiceType>(i);
144 break;
145 }
146 }
147 if (*service_type == INVALID) {
148 return false;
149 }
150 *hostname = in_str.substr(colonpos + 1, std::string::npos);
151 return true;
152}
153
deadbeef0a6c4ca2015-10-06 11:38:28 -0700154bool ParsePort(const std::string& in_str, int* port) {
155 // Make sure port only contains digits. FromString doesn't check this.
156 for (const char& c : in_str) {
157 if (!std::isdigit(c)) {
158 return false;
159 }
160 }
161 return rtc::FromString(in_str, port);
162}
163
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000164// This method parses IPv6 and IPv4 literal strings, along with hostnames in
165// standard hostname:port format.
166// Consider following formats as correct.
167// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700168// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000169bool ParseHostnameAndPortFromString(const std::string& in_str,
170 std::string* host,
171 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700172 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000173 if (in_str.at(0) == '[') {
174 std::string::size_type closebracket = in_str.rfind(']');
175 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000176 std::string::size_type colonpos = in_str.find(':', closebracket);
177 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700178 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
179 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000180 return false;
181 }
182 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700183 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000184 } else {
185 return false;
186 }
187 } else {
188 std::string::size_type colonpos = in_str.find(':');
189 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700190 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000191 return false;
192 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700193 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000194 } else {
195 *host = in_str;
196 }
197 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700198 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000199}
200
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800201// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700202// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200203bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
204 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800205 cricket::ServerAddresses* stun_servers,
206 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000207 // draft-nandakumar-rtcweb-stun-uri-01
208 // stunURI = scheme ":" stun-host [ ":" stun-port ]
209 // scheme = "stun" / "stuns"
210 // stun-host = IP-literal / IPv4address / reg-name
211 // stun-port = *DIGIT
212
213 // draft-petithuguenin-behave-turn-uris-01
214 // turnURI = scheme ":" turn-host [ ":" turn-port ]
215 // [ "?transport=" transport ]
216 // scheme = "turn" / "turns"
217 // transport = "udp" / "tcp" / transport-ext
218 // transport-ext = 1*unreserved
219 // turn-host = IP-literal / IPv4address / reg-name
220 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800221 RTC_DCHECK(stun_servers != nullptr);
222 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200223 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800224 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700225 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200226 rtc::tokenize(url, '?', &tokens);
227 std::string uri_without_transport = tokens[0];
228 // Let's look into transport= param, if it exists.
229 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
230 std::string uri_transport_param = tokens[1];
231 rtc::tokenize(uri_transport_param, '=', &tokens);
232 if (tokens[0] == kTransport) {
233 // As per above grammar transport param will be consist of lower case
234 // letters.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800235 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
236 (turn_transport_type != cricket::PROTO_UDP &&
237 turn_transport_type != cricket::PROTO_TCP)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200238 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700239 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000240 }
241 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200242 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200244 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700245 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200246 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
247 &service_type,
248 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700249 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
250 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200251 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000252
deadbeef0a6c4ca2015-10-06 11:38:28 -0700253 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
254 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200255
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200256 // Let's break hostname.
257 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700258 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
259
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200260 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261 if (tokens.size() > kTurnHostTokensNum) {
262 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
263 return false;
264 }
265 if (tokens.size() == kTurnHostTokensNum) {
266 if (tokens[0].empty() || tokens[1].empty()) {
267 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
268 return false;
269 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200270 username.assign(rtc::s_url_decode(tokens[0]));
271 hoststring = tokens[1];
272 } else {
273 hoststring = tokens[0];
274 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000275
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200276 int port = kDefaultStunPort;
277 if (service_type == TURNS) {
278 port = kDefaultStunTlsPort;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800279 turn_transport_type = cricket::PROTO_TCP;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200280 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000281
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200282 std::string address;
283 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700284 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
285 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200286 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000287
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200288 if (port <= 0 || port > 0xffff) {
289 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700290 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200291 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000292
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200293 switch (service_type) {
294 case STUN:
295 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800296 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 break;
298 case TURN:
299 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200300 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800301 turn_servers->push_back(
302 cricket::RelayServerConfig(address, port, username, server.password,
303 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200304 break;
305 }
306 case INVALID:
307 default:
308 LOG(WARNING) << "Configuration not supported: " << url;
309 return false;
310 }
311 return true;
312}
313
deadbeefab9b2d12015-10-14 11:33:11 -0700314// Check if we can send |new_stream| on a PeerConnection.
315bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
316 webrtc::MediaStreamInterface* new_stream) {
317 if (!new_stream || !current_streams) {
318 return false;
319 }
320 if (current_streams->find(new_stream->label()) != nullptr) {
321 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
322 << " is already added.";
323 return false;
324 }
325 return true;
326}
327
328bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
329 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
330}
331
deadbeef5e97fb52015-10-15 12:49:08 -0700332// If the direction is "recvonly" or "inactive", treat the description
333// as containing no streams.
334// See: https://code.google.com/p/webrtc/issues/detail?id=5054
335std::vector<cricket::StreamParams> GetActiveStreams(
336 const cricket::MediaContentDescription* desc) {
337 return MediaContentDirectionHasSend(desc->direction())
338 ? desc->streams()
339 : std::vector<cricket::StreamParams>();
340}
341
deadbeefab9b2d12015-10-14 11:33:11 -0700342bool IsValidOfferToReceiveMedia(int value) {
343 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
344 return (value >= Options::kUndefined) &&
345 (value <= Options::kMaxOfferToReceiveMedia);
346}
347
348// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800349void AddSendStreams(
350 cricket::MediaSessionOptions* session_options,
351 const std::vector<rtc::scoped_refptr<RtpSenderInterface>>& senders,
352 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
353 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700354 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800355 for (const auto& sender : senders) {
356 session_options->AddSendStream(sender->media_type(), sender->id(),
357 sender->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700358 }
359
360 // Check for data channels.
361 for (const auto& kv : rtp_data_channels) {
362 const DataChannel* channel = kv.second;
363 if (channel->state() == DataChannel::kConnecting ||
364 channel->state() == DataChannel::kOpen) {
365 // |streamid| and |sync_label| are both set to the DataChannel label
366 // here so they can be signaled the same way as MediaStreams and Tracks.
367 // For MediaStreams, the sync_label is the MediaStream label and the
368 // track label is the same as |streamid|.
369 const std::string& streamid = channel->label();
370 const std::string& sync_label = channel->label();
371 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
372 sync_label);
373 }
374 }
375}
376
deadbeef0a6c4ca2015-10-06 11:38:28 -0700377} // namespace
378
379namespace webrtc {
380
deadbeefab9b2d12015-10-14 11:33:11 -0700381// Factory class for creating remote MediaStreams and MediaStreamTracks.
382class RemoteMediaStreamFactory {
383 public:
384 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
385 cricket::ChannelManager* channel_manager)
386 : signaling_thread_(signaling_thread),
387 channel_manager_(channel_manager) {}
388
389 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
390 const std::string& stream_label) {
391 return MediaStreamProxy::Create(signaling_thread_,
392 MediaStream::Create(stream_label));
393 }
394
Tommif888bb52015-12-12 01:37:01 +0100395 AudioTrackInterface* AddAudioTrack(uint32_t ssrc,
396 AudioProviderInterface* provider,
397 webrtc::MediaStreamInterface* stream,
deadbeefab9b2d12015-10-14 11:33:11 -0700398 const std::string& track_id) {
tommi6eca7e32015-12-15 04:27:11 -0800399 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
Tommif888bb52015-12-12 01:37:01 +0100400 stream, track_id, RemoteAudioSource::Create(ssrc, provider));
deadbeefab9b2d12015-10-14 11:33:11 -0700401 }
402
403 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
404 const std::string& track_id) {
405 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
406 stream, track_id,
407 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
tommi6eca7e32015-12-15 04:27:11 -0800408 nullptr, true)
deadbeefab9b2d12015-10-14 11:33:11 -0700409 .get());
410 }
411
412 private:
413 template <typename TI, typename T, typename TP, typename S>
414 TI* AddTrack(MediaStreamInterface* stream,
415 const std::string& track_id,
Tommif888bb52015-12-12 01:37:01 +0100416 const S& source) {
deadbeefab9b2d12015-10-14 11:33:11 -0700417 rtc::scoped_refptr<TI> track(
418 TP::Create(signaling_thread_, T::Create(track_id, source)));
419 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
420 if (stream->AddTrack(track)) {
421 return track;
422 }
423 return nullptr;
424 }
425
426 rtc::Thread* signaling_thread_;
427 cricket::ChannelManager* channel_manager_;
428};
429
430bool ConvertRtcOptionsForOffer(
431 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
432 cricket::MediaSessionOptions* session_options) {
433 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
434 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
435 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
436 return false;
437 }
438
deadbeefc80741f2015-10-22 13:14:45 -0700439 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700440 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
441 }
deadbeefc80741f2015-10-22 13:14:45 -0700442 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700443 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
444 }
445
446 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700447 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800448 for (auto& kv : session_options->transport_options) {
449 kv.second.ice_restart = rtc_options.ice_restart;
450 }
deadbeefab9b2d12015-10-14 11:33:11 -0700451
452 return true;
453}
454
455bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
456 cricket::MediaSessionOptions* session_options) {
457 bool value = false;
458 size_t mandatory_constraints_satisfied = 0;
459
460 // kOfferToReceiveAudio defaults to true according to spec.
461 if (!FindConstraint(constraints,
462 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
463 &mandatory_constraints_satisfied) ||
464 value) {
465 session_options->recv_audio = true;
466 }
467
468 // kOfferToReceiveVideo defaults to false according to spec. But
469 // if it is an answer and video is offered, we should still accept video
470 // per default.
471 value = false;
472 if (!FindConstraint(constraints,
473 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
474 &mandatory_constraints_satisfied) ||
475 value) {
476 session_options->recv_video = true;
477 }
478
479 if (FindConstraint(constraints,
480 MediaConstraintsInterface::kVoiceActivityDetection, &value,
481 &mandatory_constraints_satisfied)) {
482 session_options->vad_enabled = value;
483 }
484
485 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
486 &mandatory_constraints_satisfied)) {
487 session_options->bundle_enabled = value;
488 } else {
489 // kUseRtpMux defaults to true according to spec.
490 session_options->bundle_enabled = true;
491 }
deadbeefab9b2d12015-10-14 11:33:11 -0700492
deadbeef0ed85b22016-02-23 17:24:52 -0800493 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700494 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
495 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700496 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800497 ice_restart = true;
498 }
499 for (auto& kv : session_options->transport_options) {
500 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700501 }
502
503 if (!constraints) {
504 return true;
505 }
506 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
507}
508
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200509bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800510 cricket::ServerAddresses* stun_servers,
511 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200512 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
513 if (!server.urls.empty()) {
514 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200515 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700516 LOG(LS_ERROR) << "Empty uri.";
517 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200518 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800519 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200520 return false;
521 }
522 }
523 } else if (!server.uri.empty()) {
524 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800525 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000526 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200527 }
528 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700529 LOG(LS_ERROR) << "Empty uri.";
530 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531 }
532 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800533 // Candidates must have unique priorities, so that connectivity checks
534 // are performed in a well-defined order.
535 int priority = static_cast<int>(turn_servers->size() - 1);
536 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
537 // First in the list gets highest priority.
538 turn_server.priority = priority--;
539 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540 return true;
541}
542
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000543PeerConnection::PeerConnection(PeerConnectionFactory* factory)
544 : factory_(factory),
545 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000546 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 signaling_state_(kStable),
548 ice_state_(kIceNew),
549 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700550 ice_gathering_state_(kIceGatheringNew),
551 local_streams_(StreamCollection::Create()),
552 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000553
554PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100555 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700556 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700557 // Need to detach RTP senders/receivers from WebRtcSession,
558 // since it's about to be destroyed.
559 for (const auto& sender : senders_) {
560 sender->Stop();
561 }
562 for (const auto& receiver : receivers_) {
563 receiver->Stop();
564 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000565}
566
567bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000568 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000569 const MediaConstraintsInterface* constraints,
deadbeef653b8e02015-11-11 12:55:10 -0800570 rtc::scoped_ptr<cricket::PortAllocator> allocator,
571 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
572 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100573 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800574 RTC_DCHECK(observer != nullptr);
575 if (!observer) {
576 return false;
577 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000578 observer_ = observer;
579
kwiberg0eb15ed2015-12-17 03:04:15 -0800580 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800581
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800582 cricket::ServerAddresses stun_servers;
583 std::vector<cricket::RelayServerConfig> turn_servers;
584 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585 return false;
586 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800587 port_allocator_->SetIceServers(stun_servers, turn_servers);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000588
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000590 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000591 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700592 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000593 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000594 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000595 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700596 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
597 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000598 if (!value) {
599 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000600 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000601 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000602 "Disabled") {
603 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000604 }
605
Jiayang Liucac1b382015-04-30 12:35:24 -0700606 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
607 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
608 LOG(LS_INFO) << "TCP candidates are disabled.";
609 }
610
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000611 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 // No step delay is used while allocating ports.
613 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
614
nisse51542be2016-02-12 02:27:06 -0800615 // We rely on default values when constraints aren't found.
616 cricket::MediaConfig media_config;
617
618 media_config.disable_prerenderer_smoothing =
619 configuration.disable_prerenderer_smoothing;
620
621 // Find DSCP constraint.
622 FindConstraint(constraints, MediaConstraintsInterface::kEnableDscp,
623 &media_config.enable_dscp, NULL);
624 // Find constraints for cpu overuse detection.
625 FindConstraint(constraints, MediaConstraintsInterface::kCpuOveruseDetection,
626 &media_config.enable_cpu_overuse_detection, NULL);
627
628 media_controller_.reset(factory_->CreateMediaController(media_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000629
stefanc1aeaf02015-10-15 07:26:07 -0700630 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
631 factory_->signaling_thread(), media_controller_->channel_manager()));
632
633 session_.reset(
634 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
635 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700636 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000637
638 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000639 if (!session_->Initialize(factory_->options(), constraints,
kwiberg0eb15ed2015-12-17 03:04:15 -0800640 std::move(dtls_identity_store), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700642 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644 // Register PeerConnection as receiver of local ice candidates.
645 // All the callbacks will be posted to the application from PeerConnection.
646 session_->RegisterIceObserver(this);
647 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700648 session_->SignalVoiceChannelDestroyed.connect(
649 this, &PeerConnection::OnVoiceChannelDestroyed);
650 session_->SignalVideoChannelDestroyed.connect(
651 this, &PeerConnection::OnVideoChannelDestroyed);
652 session_->SignalDataChannelCreated.connect(
653 this, &PeerConnection::OnDataChannelCreated);
654 session_->SignalDataChannelDestroyed.connect(
655 this, &PeerConnection::OnDataChannelDestroyed);
656 session_->SignalDataChannelOpenMessage.connect(
657 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 return true;
659}
660
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000661rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700663 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664}
665
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000666rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700668 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669}
670
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000671bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100672 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 if (IsClosed()) {
674 return false;
675 }
deadbeefab9b2d12015-10-14 11:33:11 -0700676 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677 return false;
678 }
deadbeefab9b2d12015-10-14 11:33:11 -0700679
680 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800681 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
682 observer->SignalAudioTrackAdded.connect(this,
683 &PeerConnection::OnAudioTrackAdded);
684 observer->SignalAudioTrackRemoved.connect(
685 this, &PeerConnection::OnAudioTrackRemoved);
686 observer->SignalVideoTrackAdded.connect(this,
687 &PeerConnection::OnVideoTrackAdded);
688 observer->SignalVideoTrackRemoved.connect(
689 this, &PeerConnection::OnVideoTrackRemoved);
690 stream_observers_.push_back(rtc::scoped_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700691
deadbeefab9b2d12015-10-14 11:33:11 -0700692 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800693 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700694 }
695 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800696 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700697 }
698
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000699 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 observer_->OnRenegotiationNeeded();
701 return true;
702}
703
704void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100705 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700706 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800707 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700708 }
709 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800710 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700711 }
712
713 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800714 stream_observers_.erase(
715 std::remove_if(
716 stream_observers_.begin(), stream_observers_.end(),
717 [local_stream](const rtc::scoped_ptr<MediaStreamObserver>& observer) {
718 return observer->stream()->label().compare(local_stream->label()) ==
719 0;
720 }),
721 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700722
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 if (IsClosed()) {
724 return;
725 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 observer_->OnRenegotiationNeeded();
727}
728
deadbeefe1f9d832016-01-14 15:35:42 -0800729rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
730 MediaStreamTrackInterface* track,
731 std::vector<MediaStreamInterface*> streams) {
732 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
733 if (IsClosed()) {
734 return nullptr;
735 }
736 if (streams.size() >= 2) {
737 LOG(LS_ERROR)
738 << "Adding a track with two streams is not currently supported.";
739 return nullptr;
740 }
741 // TODO(deadbeef): Support adding a track to two different senders.
742 if (FindSenderForTrack(track) != senders_.end()) {
743 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
744 return nullptr;
745 }
746
747 // TODO(deadbeef): Support adding a track to multiple streams.
748 rtc::scoped_refptr<RtpSenderInterface> new_sender;
749 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
750 new_sender = RtpSenderProxy::Create(
751 signaling_thread(),
752 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
753 session_.get(), stats_.get()));
754 if (!streams.empty()) {
755 new_sender->set_stream_id(streams[0]->label());
756 }
757 const TrackInfo* track_info = FindTrackInfo(
758 local_audio_tracks_, new_sender->stream_id(), track->id());
759 if (track_info) {
760 new_sender->SetSsrc(track_info->ssrc);
761 }
762 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
763 new_sender = RtpSenderProxy::Create(
764 signaling_thread(),
765 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
766 session_.get()));
767 if (!streams.empty()) {
768 new_sender->set_stream_id(streams[0]->label());
769 }
770 const TrackInfo* track_info = FindTrackInfo(
771 local_video_tracks_, new_sender->stream_id(), track->id());
772 if (track_info) {
773 new_sender->SetSsrc(track_info->ssrc);
774 }
775 } else {
776 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
777 return rtc::scoped_refptr<RtpSenderInterface>();
778 }
779
780 senders_.push_back(new_sender);
781 observer_->OnRenegotiationNeeded();
782 return new_sender;
783}
784
785bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
786 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
787 if (IsClosed()) {
788 return false;
789 }
790
791 auto it = std::find(senders_.begin(), senders_.end(), sender);
792 if (it == senders_.end()) {
793 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
794 return false;
795 }
796 (*it)->Stop();
797 senders_.erase(it);
798
799 observer_->OnRenegotiationNeeded();
800 return true;
801}
802
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000803rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100805 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 if (!track) {
807 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
808 return NULL;
809 }
deadbeefab9b2d12015-10-14 11:33:11 -0700810 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
812 return NULL;
813 }
814
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000815 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000816 DtmfSender::Create(track, signaling_thread(), session_.get()));
817 if (!sender.get()) {
818 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
819 return NULL;
820 }
821 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
822}
823
deadbeeffac06552015-11-25 11:26:01 -0800824rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800825 const std::string& kind,
826 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100827 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeefe1f9d832016-01-14 15:35:42 -0800828 rtc::scoped_refptr<RtpSenderInterface> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800829 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefe1f9d832016-01-14 15:35:42 -0800830 new_sender = RtpSenderProxy::Create(
831 signaling_thread(), new AudioRtpSender(session_.get(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800832 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefe1f9d832016-01-14 15:35:42 -0800833 new_sender = RtpSenderProxy::Create(signaling_thread(),
834 new VideoRtpSender(session_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800835 } else {
836 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800837 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800838 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800839 if (!stream_id.empty()) {
840 new_sender->set_stream_id(stream_id);
841 }
deadbeeffac06552015-11-25 11:26:01 -0800842 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800843 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800844}
845
deadbeef70ab1a12015-09-28 16:53:55 -0700846std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
847 const {
deadbeefe1f9d832016-01-14 15:35:42 -0800848 return senders_;
deadbeef70ab1a12015-09-28 16:53:55 -0700849}
850
851std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
852PeerConnection::GetReceivers() const {
deadbeefe1f9d832016-01-14 15:35:42 -0800853 return receivers_;
deadbeef70ab1a12015-09-28 16:53:55 -0700854}
855
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000856bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000857 MediaStreamTrackInterface* track,
858 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100859 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700860 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000861 if (!VERIFY(observer != NULL)) {
862 LOG(LS_ERROR) << "GetStats - observer is NULL.";
863 return false;
864 }
865
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000866 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000867 signaling_thread()->Post(this, MSG_GETSTATS,
868 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869 return true;
870}
871
872PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
873 return signaling_state_;
874}
875
876PeerConnectionInterface::IceState PeerConnection::ice_state() {
877 return ice_state_;
878}
879
880PeerConnectionInterface::IceConnectionState
881PeerConnection::ice_connection_state() {
882 return ice_connection_state_;
883}
884
885PeerConnectionInterface::IceGatheringState
886PeerConnection::ice_gathering_state() {
887 return ice_gathering_state_;
888}
889
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000890rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891PeerConnection::CreateDataChannel(
892 const std::string& label,
893 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100894 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700895 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000896
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000897 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000898 if (config) {
899 internal_config.reset(new InternalDataChannelInit(*config));
900 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000901 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700902 InternalCreateDataChannel(label, internal_config.get()));
903 if (!channel.get()) {
904 return nullptr;
905 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000907 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
908 // the first SCTP DataChannel.
909 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
910 observer_->OnRenegotiationNeeded();
911 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000912
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913 return DataChannelProxy::Create(signaling_thread(), channel.get());
914}
915
916void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
917 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100918 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700919 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
921 return;
922 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000923 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000924
925 bool value;
926 size_t mandatory_constraints = 0;
927
928 if (FindConstraint(constraints,
929 MediaConstraintsInterface::kOfferToReceiveAudio,
930 &value,
931 &mandatory_constraints)) {
932 options.offer_to_receive_audio =
933 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
934 }
935
936 if (FindConstraint(constraints,
937 MediaConstraintsInterface::kOfferToReceiveVideo,
938 &value,
939 &mandatory_constraints)) {
940 options.offer_to_receive_video =
941 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
942 }
943
944 if (FindConstraint(constraints,
945 MediaConstraintsInterface::kVoiceActivityDetection,
946 &value,
947 &mandatory_constraints)) {
948 options.voice_activity_detection = value;
949 }
950
951 if (FindConstraint(constraints,
952 MediaConstraintsInterface::kIceRestart,
953 &value,
954 &mandatory_constraints)) {
955 options.ice_restart = value;
956 }
957
958 if (FindConstraint(constraints,
959 MediaConstraintsInterface::kUseRtpMux,
960 &value,
961 &mandatory_constraints)) {
962 options.use_rtp_mux = value;
963 }
964
965 CreateOffer(observer, options);
966}
967
968void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
969 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100970 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700971 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000972 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
973 return;
974 }
deadbeefab9b2d12015-10-14 11:33:11 -0700975
976 cricket::MediaSessionOptions session_options;
977 if (!GetOptionsForOffer(options, &session_options)) {
978 std::string error = "CreateOffer called with invalid options.";
979 LOG(LS_ERROR) << error;
980 PostCreateSessionDescriptionFailure(observer, error);
981 return;
982 }
983
984 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985}
986
987void PeerConnection::CreateAnswer(
988 CreateSessionDescriptionObserver* observer,
989 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100990 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -0700991 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
993 return;
994 }
deadbeefab9b2d12015-10-14 11:33:11 -0700995
996 cricket::MediaSessionOptions session_options;
997 if (!GetOptionsForAnswer(constraints, &session_options)) {
998 std::string error = "CreateAnswer called with invalid constraints.";
999 LOG(LS_ERROR) << error;
1000 PostCreateSessionDescriptionFailure(observer, error);
1001 return;
1002 }
1003
1004 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005}
1006
1007void PeerConnection::SetLocalDescription(
1008 SetSessionDescriptionObserver* observer,
1009 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001010 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001011 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1013 return;
1014 }
1015 if (!desc) {
1016 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1017 return;
1018 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019 // Update stats here so that we have the most recent stats for tracks and
1020 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001021 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 std::string error;
1023 if (!session_->SetLocalDescription(desc, &error)) {
1024 PostSetSessionDescriptionFailure(observer, error);
1025 return;
1026 }
deadbeefab9b2d12015-10-14 11:33:11 -07001027
1028 // If setting the description decided our SSL role, allocate any necessary
1029 // SCTP sids.
1030 rtc::SSLRole role;
1031 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001032 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001033 AllocateSctpSids(role);
1034 }
1035
1036 // Update state and SSRC of local MediaStreams and DataChannels based on the
1037 // local session description.
1038 const cricket::ContentInfo* audio_content =
1039 GetFirstAudioContent(desc->description());
1040 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001041 if (audio_content->rejected) {
1042 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1043 } else {
1044 const cricket::AudioContentDescription* audio_desc =
1045 static_cast<const cricket::AudioContentDescription*>(
1046 audio_content->description);
1047 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1048 }
deadbeefab9b2d12015-10-14 11:33:11 -07001049 }
1050
1051 const cricket::ContentInfo* video_content =
1052 GetFirstVideoContent(desc->description());
1053 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001054 if (video_content->rejected) {
1055 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1056 } else {
1057 const cricket::VideoContentDescription* video_desc =
1058 static_cast<const cricket::VideoContentDescription*>(
1059 video_content->description);
1060 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1061 }
deadbeefab9b2d12015-10-14 11:33:11 -07001062 }
1063
1064 const cricket::ContentInfo* data_content =
1065 GetFirstDataContent(desc->description());
1066 if (data_content) {
1067 const cricket::DataContentDescription* data_desc =
1068 static_cast<const cricket::DataContentDescription*>(
1069 data_content->description);
1070 if (rtc::starts_with(data_desc->protocol().data(),
1071 cricket::kMediaProtocolRtpPrefix)) {
1072 UpdateLocalRtpDataChannels(data_desc->streams());
1073 }
1074 }
1075
1076 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001078
deadbeefcbecd352015-09-23 11:50:27 -07001079 // MaybeStartGathering needs to be called after posting
1080 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1081 // before signaling that SetLocalDescription completed.
1082 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083}
1084
1085void PeerConnection::SetRemoteDescription(
1086 SetSessionDescriptionObserver* observer,
1087 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001088 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001089 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1091 return;
1092 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 if (!desc) {
1094 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1095 return;
1096 }
1097 // Update stats here so that we have the most recent stats for tracks and
1098 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001099 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100 std::string error;
1101 if (!session_->SetRemoteDescription(desc, &error)) {
1102 PostSetSessionDescriptionFailure(observer, error);
1103 return;
1104 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105
deadbeefab9b2d12015-10-14 11:33:11 -07001106 // If setting the description decided our SSL role, allocate any necessary
1107 // SCTP sids.
1108 rtc::SSLRole role;
1109 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001110 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001111 AllocateSctpSids(role);
1112 }
1113
1114 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001115 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1116 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1117 const cricket::AudioContentDescription* audio_desc =
1118 GetFirstAudioContentDescription(remote_desc);
1119 const cricket::VideoContentDescription* video_desc =
1120 GetFirstVideoContentDescription(remote_desc);
1121 const cricket::DataContentDescription* data_desc =
1122 GetFirstDataContentDescription(remote_desc);
1123
1124 // Check if the descriptions include streams, just in case the peer supports
1125 // MSID, but doesn't indicate so with "a=msid-semantic".
1126 if (remote_desc->msid_supported() ||
1127 (audio_desc && !audio_desc->streams().empty()) ||
1128 (video_desc && !video_desc->streams().empty())) {
1129 remote_peer_supports_msid_ = true;
1130 }
deadbeefab9b2d12015-10-14 11:33:11 -07001131
1132 // We wait to signal new streams until we finish processing the description,
1133 // since only at that point will new streams have all their tracks.
1134 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1135
1136 // Find all audio rtp streams and create corresponding remote AudioTracks
1137 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001138 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001139 if (audio_content->rejected) {
1140 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1141 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001142 bool default_audio_track_needed =
1143 !remote_peer_supports_msid_ &&
1144 MediaContentDirectionHasSend(audio_desc->direction());
1145 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1146 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001147 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001148 }
deadbeefab9b2d12015-10-14 11:33:11 -07001149 }
1150
1151 // Find all video rtp streams and create corresponding remote VideoTracks
1152 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001153 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001154 if (video_content->rejected) {
1155 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1156 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001157 bool default_video_track_needed =
1158 !remote_peer_supports_msid_ &&
1159 MediaContentDirectionHasSend(video_desc->direction());
1160 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1161 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001162 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001163 }
deadbeefab9b2d12015-10-14 11:33:11 -07001164 }
1165
1166 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001167 if (data_desc) {
1168 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001169 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001170 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001171 }
1172 }
1173
1174 // Iterate new_streams and notify the observer about new MediaStreams.
1175 for (size_t i = 0; i < new_streams->count(); ++i) {
1176 MediaStreamInterface* new_stream = new_streams->at(i);
1177 stats_->AddStream(new_stream);
1178 observer_->OnAddStream(new_stream);
1179 }
1180
deadbeefbda7e0b2015-12-08 17:13:40 -08001181 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001182
1183 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1184 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001185}
1186
deadbeefa67696b2015-09-29 11:56:26 -07001187bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001188 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001189 if (port_allocator_) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -08001190 cricket::ServerAddresses stun_servers;
1191 std::vector<cricket::RelayServerConfig> turn_servers;
1192 if (!ParseIceServers(config.servers, &stun_servers, &turn_servers)) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001193 return false;
1194 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -08001195 port_allocator_->SetIceServers(stun_servers, turn_servers);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001196 }
honghaiz1f429e32015-09-28 07:57:34 -07001197 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001198 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001199}
1200
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201bool PeerConnection::AddIceCandidate(
1202 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001203 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001204 return session_->ProcessIceMessage(ice_candidate);
1205}
1206
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001207void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001208 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001209 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001210
1211 if (session_) {
1212 session_->set_metrics_observer(uma_observer_);
1213 }
1214
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001215 // Send information about IPv4/IPv6 status.
1216 if (uma_observer_ && port_allocator_) {
1217 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001218 uma_observer_->IncrementEnumCounter(
1219 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1220 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001221 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001222 uma_observer_->IncrementEnumCounter(
1223 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1224 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001225 }
1226 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001227}
1228
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229const SessionDescriptionInterface* PeerConnection::local_description() const {
1230 return session_->local_description();
1231}
1232
1233const SessionDescriptionInterface* PeerConnection::remote_description() const {
1234 return session_->remote_description();
1235}
1236
1237void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001238 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 // Update stats here so that we have the most recent stats for tracks and
1240 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001241 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242
deadbeefd59daf82015-10-14 15:02:44 -07001243 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244}
1245
deadbeefd59daf82015-10-14 15:02:44 -07001246void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1247 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001248 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001249 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001251 break;
deadbeefd59daf82015-10-14 15:02:44 -07001252 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001253 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1254 break;
deadbeefd59daf82015-10-14 15:02:44 -07001255 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1257 break;
deadbeefd59daf82015-10-14 15:02:44 -07001258 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1260 break;
deadbeefd59daf82015-10-14 15:02:44 -07001261 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001262 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1263 break;
deadbeefd59daf82015-10-14 15:02:44 -07001264 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265 ChangeSignalingState(PeerConnectionInterface::kStable);
1266 break;
deadbeefd59daf82015-10-14 15:02:44 -07001267 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268 ChangeSignalingState(PeerConnectionInterface::kClosed);
1269 break;
1270 default:
1271 break;
1272 }
1273}
1274
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001275void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001277 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1278 SetSessionDescriptionMsg* param =
1279 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1280 param->observer->OnSuccess();
1281 delete param;
1282 break;
1283 }
1284 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1285 SetSessionDescriptionMsg* param =
1286 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1287 param->observer->OnFailure(param->error);
1288 delete param;
1289 break;
1290 }
deadbeefab9b2d12015-10-14 11:33:11 -07001291 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1292 CreateSessionDescriptionMsg* param =
1293 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1294 param->observer->OnFailure(param->error);
1295 delete param;
1296 break;
1297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298 case MSG_GETSTATS: {
1299 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001300 StatsReports reports;
1301 stats_->GetStats(param->track, &reports);
1302 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303 delete param;
1304 break;
1305 }
deadbeefbd292462015-12-14 18:15:29 -08001306 case MSG_FREE_DATACHANNELS: {
1307 sctp_data_channels_to_free_.clear();
1308 break;
1309 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001311 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 break;
1313 }
1314}
1315
deadbeefab9b2d12015-10-14 11:33:11 -07001316void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1317 AudioTrackInterface* audio_track,
1318 uint32_t ssrc) {
deadbeefe1f9d832016-01-14 15:35:42 -08001319 receivers_.push_back(RtpReceiverProxy::Create(
1320 signaling_thread(),
1321 new AudioRtpReceiver(audio_track, ssrc, session_.get())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322}
1323
deadbeefab9b2d12015-10-14 11:33:11 -07001324void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1325 VideoTrackInterface* video_track,
1326 uint32_t ssrc) {
deadbeefe1f9d832016-01-14 15:35:42 -08001327 receivers_.push_back(RtpReceiverProxy::Create(
1328 signaling_thread(),
1329 new VideoRtpReceiver(video_track, ssrc, session_.get())));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330}
1331
deadbeef70ab1a12015-09-28 16:53:55 -07001332// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1333// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001334void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1335 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001336 auto it = FindReceiverForTrack(audio_track);
1337 if (it == receivers_.end()) {
1338 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1339 << " doesn't exist.";
1340 } else {
1341 (*it)->Stop();
1342 receivers_.erase(it);
1343 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344}
1345
deadbeefab9b2d12015-10-14 11:33:11 -07001346void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1347 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001348 auto it = FindReceiverForTrack(video_track);
1349 if (it == receivers_.end()) {
1350 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1351 << " doesn't exist.";
1352 } else {
1353 (*it)->Stop();
1354 receivers_.erase(it);
1355 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356}
deadbeef70ab1a12015-09-28 16:53:55 -07001357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358void PeerConnection::OnIceConnectionChange(
1359 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001360 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001361 // After transitioning to "closed", ignore any additional states from
1362 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001363 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001364 return;
1365 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001367 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368}
1369
1370void PeerConnection::OnIceGatheringChange(
1371 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001372 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373 if (IsClosed()) {
1374 return;
1375 }
1376 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001377 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378}
1379
1380void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001381 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001382 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383}
1384
Peter Thatcher54360512015-07-08 11:08:35 -07001385void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001386 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001387 observer_->OnIceConnectionReceivingChange(receiving);
1388}
1389
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390void PeerConnection::ChangeSignalingState(
1391 PeerConnectionInterface::SignalingState signaling_state) {
1392 signaling_state_ = signaling_state;
1393 if (signaling_state == kClosed) {
1394 ice_connection_state_ = kIceConnectionClosed;
1395 observer_->OnIceConnectionChange(ice_connection_state_);
1396 if (ice_gathering_state_ != kIceGatheringComplete) {
1397 ice_gathering_state_ = kIceGatheringComplete;
1398 observer_->OnIceGatheringChange(ice_gathering_state_);
1399 }
1400 }
1401 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402}
1403
deadbeefeb459812015-12-15 19:24:43 -08001404void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1405 MediaStreamInterface* stream) {
1406 auto sender = FindSenderForTrack(track);
1407 if (sender != senders_.end()) {
1408 // We already have a sender for this track, so just change the stream_id
1409 // so that it's correct in the next call to CreateOffer.
1410 (*sender)->set_stream_id(stream->label());
1411 return;
1412 }
1413
1414 // Normal case; we've never seen this track before.
deadbeefe1f9d832016-01-14 15:35:42 -08001415 rtc::scoped_refptr<RtpSenderInterface> new_sender = RtpSenderProxy::Create(
1416 signaling_thread(),
1417 new AudioRtpSender(track, stream->label(), session_.get(), stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001418 senders_.push_back(new_sender);
1419 // If the sender has already been configured in SDP, we call SetSsrc,
1420 // which will connect the sender to the underlying transport. This can
1421 // occur if a local session description that contains the ID of the sender
1422 // is set before AddStream is called. It can also occur if the local
1423 // session description is not changed and RemoveStream is called, and
1424 // later AddStream is called again with the same stream.
1425 const TrackInfo* track_info =
1426 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1427 if (track_info) {
1428 new_sender->SetSsrc(track_info->ssrc);
1429 }
1430}
1431
1432// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1433// indefinitely, when we have unified plan SDP.
1434void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1435 MediaStreamInterface* stream) {
1436 auto sender = FindSenderForTrack(track);
1437 if (sender == senders_.end()) {
1438 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1439 << " doesn't exist.";
1440 return;
1441 }
1442 (*sender)->Stop();
1443 senders_.erase(sender);
1444}
1445
1446void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1447 MediaStreamInterface* stream) {
1448 auto sender = FindSenderForTrack(track);
1449 if (sender != senders_.end()) {
1450 // We already have a sender for this track, so just change the stream_id
1451 // so that it's correct in the next call to CreateOffer.
1452 (*sender)->set_stream_id(stream->label());
1453 return;
1454 }
1455
1456 // Normal case; we've never seen this track before.
deadbeefe1f9d832016-01-14 15:35:42 -08001457 rtc::scoped_refptr<RtpSenderInterface> new_sender = RtpSenderProxy::Create(
1458 signaling_thread(),
1459 new VideoRtpSender(track, stream->label(), session_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001460 senders_.push_back(new_sender);
1461 const TrackInfo* track_info =
1462 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1463 if (track_info) {
1464 new_sender->SetSsrc(track_info->ssrc);
1465 }
1466}
1467
1468void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1469 MediaStreamInterface* stream) {
1470 auto sender = FindSenderForTrack(track);
1471 if (sender == senders_.end()) {
1472 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1473 << " doesn't exist.";
1474 return;
1475 }
1476 (*sender)->Stop();
1477 senders_.erase(sender);
1478}
1479
deadbeefab9b2d12015-10-14 11:33:11 -07001480void PeerConnection::PostSetSessionDescriptionFailure(
1481 SetSessionDescriptionObserver* observer,
1482 const std::string& error) {
1483 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1484 msg->error = error;
1485 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1486}
1487
1488void PeerConnection::PostCreateSessionDescriptionFailure(
1489 CreateSessionDescriptionObserver* observer,
1490 const std::string& error) {
1491 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1492 msg->error = error;
1493 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1494}
1495
1496bool PeerConnection::GetOptionsForOffer(
1497 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1498 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001499 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1500 // ContentInfos.
1501 if (session_->local_description()) {
1502 for (const cricket::ContentInfo& content :
1503 session_->local_description()->description()->contents()) {
1504 session_options->transport_options[content.name] =
1505 cricket::TransportOptions();
1506 }
1507 }
deadbeefab9b2d12015-10-14 11:33:11 -07001508 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1509 return false;
1510 }
1511
deadbeeffac06552015-11-25 11:26:01 -08001512 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001513 // Offer to receive audio/video if the constraint is not set and there are
1514 // send streams, or we're currently receiving.
1515 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1516 session_options->recv_audio =
1517 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1518 !remote_audio_tracks_.empty();
1519 }
1520 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1521 session_options->recv_video =
1522 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1523 !remote_video_tracks_.empty();
1524 }
1525 session_options->bundle_enabled =
1526 session_options->bundle_enabled &&
1527 (session_options->has_audio() || session_options->has_video() ||
1528 session_options->has_data());
1529
deadbeefab9b2d12015-10-14 11:33:11 -07001530 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1531 session_options->data_channel_type = cricket::DCT_SCTP;
1532 }
1533 return true;
1534}
1535
1536bool PeerConnection::GetOptionsForAnswer(
1537 const MediaConstraintsInterface* constraints,
1538 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001539 session_options->recv_audio = false;
1540 session_options->recv_video = false;
deadbeef0ed85b22016-02-23 17:24:52 -08001541 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1542 // ContentInfos.
1543 if (session_->remote_description()) {
1544 // Initialize the transport_options map.
1545 for (const cricket::ContentInfo& content :
1546 session_->remote_description()->description()->contents()) {
1547 session_options->transport_options[content.name] =
1548 cricket::TransportOptions();
1549 }
1550 }
deadbeefab9b2d12015-10-14 11:33:11 -07001551 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1552 return false;
1553 }
1554
deadbeeffac06552015-11-25 11:26:01 -08001555 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001556 session_options->bundle_enabled =
1557 session_options->bundle_enabled &&
1558 (session_options->has_audio() || session_options->has_video() ||
1559 session_options->has_data());
1560
deadbeefab9b2d12015-10-14 11:33:11 -07001561 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1562 // are not signaled in the SDP so does not go through that path and must be
1563 // handled here.
1564 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1565 session_options->data_channel_type = cricket::DCT_SCTP;
1566 }
1567 return true;
1568}
1569
deadbeeffaac4972015-11-12 15:33:07 -08001570void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1571 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001572 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1573 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001574}
1575
deadbeefab9b2d12015-10-14 11:33:11 -07001576void PeerConnection::UpdateRemoteStreamsList(
1577 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001578 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001579 cricket::MediaType media_type,
1580 StreamCollection* new_streams) {
1581 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1582
1583 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001584 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001585 auto track_it = current_tracks->begin();
1586 while (track_it != current_tracks->end()) {
1587 const TrackInfo& info = *track_it;
1588 const cricket::StreamParams* params =
1589 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001590 bool track_exists = params && params->id == info.track_id;
1591 // If this is a default track, and we still need it, don't remove it.
1592 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1593 track_exists) {
1594 ++track_it;
1595 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001596 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1597 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001598 }
1599 }
1600
1601 // Find new and active tracks.
1602 for (const cricket::StreamParams& params : streams) {
1603 // The sync_label is the MediaStream label and the |stream.id| is the
1604 // track id.
1605 const std::string& stream_label = params.sync_label;
1606 const std::string& track_id = params.id;
1607 uint32_t ssrc = params.first_ssrc();
1608
1609 rtc::scoped_refptr<MediaStreamInterface> stream =
1610 remote_streams_->find(stream_label);
1611 if (!stream) {
1612 // This is a new MediaStream. Create a new remote MediaStream.
1613 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1614 remote_streams_->AddStream(stream);
1615 new_streams->AddStream(stream);
1616 }
1617
1618 const TrackInfo* track_info =
1619 FindTrackInfo(*current_tracks, stream_label, track_id);
1620 if (!track_info) {
1621 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1622 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1623 }
1624 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001625
1626 // Add default track if necessary.
1627 if (default_track_needed) {
1628 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1629 remote_streams_->find(kDefaultStreamLabel);
1630 if (!default_stream) {
1631 // Create the new default MediaStream.
1632 default_stream =
1633 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1634 remote_streams_->AddStream(default_stream);
1635 new_streams->AddStream(default_stream);
1636 }
1637 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1638 ? kDefaultAudioTrackLabel
1639 : kDefaultVideoTrackLabel;
1640 const TrackInfo* default_track_info =
1641 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1642 if (!default_track_info) {
1643 current_tracks->push_back(
1644 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1645 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1646 }
1647 }
deadbeefab9b2d12015-10-14 11:33:11 -07001648}
1649
1650void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1651 const std::string& track_id,
1652 uint32_t ssrc,
1653 cricket::MediaType media_type) {
1654 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1655
1656 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Tommif888bb52015-12-12 01:37:01 +01001657 AudioTrackInterface* audio_track = remote_stream_factory_->AddAudioTrack(
1658 ssrc, session_.get(), stream, track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001659 CreateAudioReceiver(stream, audio_track, ssrc);
1660 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1661 VideoTrackInterface* video_track =
1662 remote_stream_factory_->AddVideoTrack(stream, track_id);
1663 CreateVideoReceiver(stream, video_track, ssrc);
1664 } else {
1665 RTC_DCHECK(false && "Invalid media type");
1666 }
1667}
1668
1669void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1670 const std::string& track_id,
1671 cricket::MediaType media_type) {
1672 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1673
1674 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1675 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1676 stream->FindAudioTrack(track_id);
1677 if (audio_track) {
1678 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1679 stream->RemoveTrack(audio_track);
1680 DestroyAudioReceiver(stream, audio_track);
1681 }
1682 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1683 rtc::scoped_refptr<VideoTrackInterface> video_track =
1684 stream->FindVideoTrack(track_id);
1685 if (video_track) {
1686 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1687 stream->RemoveTrack(video_track);
1688 DestroyVideoReceiver(stream, video_track);
1689 }
1690 } else {
1691 ASSERT(false && "Invalid media type");
1692 }
1693}
1694
1695void PeerConnection::UpdateEndedRemoteMediaStreams() {
1696 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1697 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1698 MediaStreamInterface* stream = remote_streams_->at(i);
1699 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1700 streams_to_remove.push_back(stream);
1701 }
1702 }
1703
1704 for (const auto& stream : streams_to_remove) {
1705 remote_streams_->RemoveStream(stream);
1706 observer_->OnRemoveStream(stream);
1707 }
1708}
1709
deadbeefab9b2d12015-10-14 11:33:11 -07001710void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1711 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1712 for (TrackInfos::iterator track_it = current_tracks->begin();
1713 track_it != current_tracks->end(); ++track_it) {
1714 const TrackInfo& info = *track_it;
1715 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1716 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1717 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1718 // There's no guarantee the track is still available, e.g. the track may
1719 // have been removed from the stream by javascript.
1720 if (track) {
1721 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1722 }
1723 }
1724 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1725 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1726 // There's no guarantee the track is still available, e.g. the track may
1727 // have been removed from the stream by javascript.
1728 if (track) {
1729 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1730 }
1731 }
1732 }
1733}
1734
1735void PeerConnection::UpdateLocalTracks(
1736 const std::vector<cricket::StreamParams>& streams,
1737 cricket::MediaType media_type) {
1738 TrackInfos* current_tracks = GetLocalTracks(media_type);
1739
1740 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1741 // don't match the new StreamParam.
1742 TrackInfos::iterator track_it = current_tracks->begin();
1743 while (track_it != current_tracks->end()) {
1744 const TrackInfo& info = *track_it;
1745 const cricket::StreamParams* params =
1746 cricket::GetStreamBySsrc(streams, info.ssrc);
1747 if (!params || params->id != info.track_id ||
1748 params->sync_label != info.stream_label) {
1749 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1750 media_type);
1751 track_it = current_tracks->erase(track_it);
1752 } else {
1753 ++track_it;
1754 }
1755 }
1756
1757 // Find new and active tracks.
1758 for (const cricket::StreamParams& params : streams) {
1759 // The sync_label is the MediaStream label and the |stream.id| is the
1760 // track id.
1761 const std::string& stream_label = params.sync_label;
1762 const std::string& track_id = params.id;
1763 uint32_t ssrc = params.first_ssrc();
1764 const TrackInfo* track_info =
1765 FindTrackInfo(*current_tracks, stream_label, track_id);
1766 if (!track_info) {
1767 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1768 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1769 }
1770 }
1771}
1772
1773void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1774 const std::string& track_id,
1775 uint32_t ssrc,
1776 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001777 RtpSenderInterface* sender = FindSenderById(track_id);
1778 if (!sender) {
1779 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1780 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001781 return;
1782 }
1783
deadbeeffac06552015-11-25 11:26:01 -08001784 if (sender->media_type() != media_type) {
1785 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1786 << " description with an unexpected media type.";
1787 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001788 }
deadbeeffac06552015-11-25 11:26:01 -08001789
1790 sender->set_stream_id(stream_label);
1791 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001792}
1793
1794void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1795 const std::string& track_id,
1796 uint32_t ssrc,
1797 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001798 RtpSenderInterface* sender = FindSenderById(track_id);
1799 if (!sender) {
1800 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001801 // SessionDescriptions has been renegotiated.
1802 return;
1803 }
deadbeeffac06552015-11-25 11:26:01 -08001804
1805 // A sender has been removed from the SessionDescription but it's still
1806 // associated with the PeerConnection. This only occurs if the SDP doesn't
1807 // match with the calls to CreateSender, AddStream and RemoveStream.
1808 if (sender->media_type() != media_type) {
1809 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1810 << " description with an unexpected media type.";
1811 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001812 }
deadbeeffac06552015-11-25 11:26:01 -08001813
1814 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001815}
1816
1817void PeerConnection::UpdateLocalRtpDataChannels(
1818 const cricket::StreamParamsVec& streams) {
1819 std::vector<std::string> existing_channels;
1820
1821 // Find new and active data channels.
1822 for (const cricket::StreamParams& params : streams) {
1823 // |it->sync_label| is actually the data channel label. The reason is that
1824 // we use the same naming of data channels as we do for
1825 // MediaStreams and Tracks.
1826 // For MediaStreams, the sync_label is the MediaStream label and the
1827 // track label is the same as |streamid|.
1828 const std::string& channel_label = params.sync_label;
1829 auto data_channel_it = rtp_data_channels_.find(channel_label);
1830 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1831 continue;
1832 }
1833 // Set the SSRC the data channel should use for sending.
1834 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1835 existing_channels.push_back(data_channel_it->first);
1836 }
1837
1838 UpdateClosingRtpDataChannels(existing_channels, true);
1839}
1840
1841void PeerConnection::UpdateRemoteRtpDataChannels(
1842 const cricket::StreamParamsVec& streams) {
1843 std::vector<std::string> existing_channels;
1844
1845 // Find new and active data channels.
1846 for (const cricket::StreamParams& params : streams) {
1847 // The data channel label is either the mslabel or the SSRC if the mslabel
1848 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1849 std::string label = params.sync_label.empty()
1850 ? rtc::ToString(params.first_ssrc())
1851 : params.sync_label;
1852 auto data_channel_it = rtp_data_channels_.find(label);
1853 if (data_channel_it == rtp_data_channels_.end()) {
1854 // This is a new data channel.
1855 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1856 } else {
1857 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1858 }
1859 existing_channels.push_back(label);
1860 }
1861
1862 UpdateClosingRtpDataChannels(existing_channels, false);
1863}
1864
1865void PeerConnection::UpdateClosingRtpDataChannels(
1866 const std::vector<std::string>& active_channels,
1867 bool is_local_update) {
1868 auto it = rtp_data_channels_.begin();
1869 while (it != rtp_data_channels_.end()) {
1870 DataChannel* data_channel = it->second;
1871 if (std::find(active_channels.begin(), active_channels.end(),
1872 data_channel->label()) != active_channels.end()) {
1873 ++it;
1874 continue;
1875 }
1876
1877 if (is_local_update) {
1878 data_channel->SetSendSsrc(0);
1879 } else {
1880 data_channel->RemotePeerRequestClose();
1881 }
1882
1883 if (data_channel->state() == DataChannel::kClosed) {
1884 rtp_data_channels_.erase(it);
1885 it = rtp_data_channels_.begin();
1886 } else {
1887 ++it;
1888 }
1889 }
1890}
1891
1892void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1893 uint32_t remote_ssrc) {
1894 rtc::scoped_refptr<DataChannel> channel(
1895 InternalCreateDataChannel(label, nullptr));
1896 if (!channel.get()) {
1897 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1898 << "CreateDataChannel failed.";
1899 return;
1900 }
1901 channel->SetReceiveSsrc(remote_ssrc);
1902 observer_->OnDataChannel(
1903 DataChannelProxy::Create(signaling_thread(), channel));
1904}
1905
1906rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1907 const std::string& label,
1908 const InternalDataChannelInit* config) {
1909 if (IsClosed()) {
1910 return nullptr;
1911 }
1912 if (session_->data_channel_type() == cricket::DCT_NONE) {
1913 LOG(LS_ERROR)
1914 << "InternalCreateDataChannel: Data is not supported in this call.";
1915 return nullptr;
1916 }
1917 InternalDataChannelInit new_config =
1918 config ? (*config) : InternalDataChannelInit();
1919 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1920 if (new_config.id < 0) {
1921 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001922 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07001923 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1924 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1925 return nullptr;
1926 }
1927 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1928 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1929 << "because the id is already in use or out of range.";
1930 return nullptr;
1931 }
1932 }
1933
1934 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1935 session_.get(), session_->data_channel_type(), label, new_config));
1936 if (!channel) {
1937 sid_allocator_.ReleaseSid(new_config.id);
1938 return nullptr;
1939 }
1940
1941 if (channel->data_channel_type() == cricket::DCT_RTP) {
1942 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1943 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1944 << " already exists.";
1945 return nullptr;
1946 }
1947 rtp_data_channels_[channel->label()] = channel;
1948 } else {
1949 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1950 sctp_data_channels_.push_back(channel);
1951 channel->SignalClosed.connect(this,
1952 &PeerConnection::OnSctpDataChannelClosed);
1953 }
1954
1955 return channel;
1956}
1957
1958bool PeerConnection::HasDataChannels() const {
1959 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1960}
1961
1962void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1963 for (const auto& channel : sctp_data_channels_) {
1964 if (channel->id() < 0) {
1965 int sid;
1966 if (!sid_allocator_.AllocateSid(role, &sid)) {
1967 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1968 continue;
1969 }
1970 channel->SetSctpSid(sid);
1971 }
1972 }
1973}
1974
1975void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08001976 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07001977 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1978 ++it) {
1979 if (it->get() == channel) {
1980 if (channel->id() >= 0) {
1981 sid_allocator_.ReleaseSid(channel->id());
1982 }
deadbeefbd292462015-12-14 18:15:29 -08001983 // Since this method is triggered by a signal from the DataChannel,
1984 // we can't free it directly here; we need to free it asynchronously.
1985 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07001986 sctp_data_channels_.erase(it);
deadbeefbd292462015-12-14 18:15:29 -08001987 signaling_thread()->Post(this, MSG_FREE_DATACHANNELS, nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07001988 return;
1989 }
1990 }
1991}
1992
1993void PeerConnection::OnVoiceChannelDestroyed() {
1994 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1995}
1996
1997void PeerConnection::OnVideoChannelDestroyed() {
1998 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1999}
2000
2001void PeerConnection::OnDataChannelCreated() {
2002 for (const auto& channel : sctp_data_channels_) {
2003 channel->OnTransportChannelCreated();
2004 }
2005}
2006
2007void PeerConnection::OnDataChannelDestroyed() {
2008 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2009 // DataChannel may callback to us and try to modify the list.
2010 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2011 temp_rtp_dcs.swap(rtp_data_channels_);
2012 for (const auto& kv : temp_rtp_dcs) {
2013 kv.second->OnTransportChannelDestroyed();
2014 }
2015
2016 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2017 temp_sctp_dcs.swap(sctp_data_channels_);
2018 for (const auto& channel : temp_sctp_dcs) {
2019 channel->OnTransportChannelDestroyed();
2020 }
2021}
2022
2023void PeerConnection::OnDataChannelOpenMessage(
2024 const std::string& label,
2025 const InternalDataChannelInit& config) {
2026 rtc::scoped_refptr<DataChannel> channel(
2027 InternalCreateDataChannel(label, &config));
2028 if (!channel.get()) {
2029 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2030 return;
2031 }
2032
2033 observer_->OnDataChannel(
2034 DataChannelProxy::Create(signaling_thread(), channel));
2035}
2036
deadbeeffac06552015-11-25 11:26:01 -08002037RtpSenderInterface* PeerConnection::FindSenderById(const std::string& id) {
2038 auto it =
2039 std::find_if(senders_.begin(), senders_.end(),
2040 [id](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
2041 return sender->id() == id;
2042 });
2043 return it != senders_.end() ? it->get() : nullptr;
2044}
2045
deadbeef70ab1a12015-09-28 16:53:55 -07002046std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
2047PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2048 return std::find_if(
2049 senders_.begin(), senders_.end(),
2050 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
2051 return sender->track() == track;
2052 });
2053}
2054
2055std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
2056PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
2057 return std::find_if(
2058 receivers_.begin(), receivers_.end(),
2059 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
2060 return receiver->track() == track;
2061 });
2062}
2063
deadbeefab9b2d12015-10-14 11:33:11 -07002064PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2065 cricket::MediaType media_type) {
2066 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2067 media_type == cricket::MEDIA_TYPE_VIDEO);
2068 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2069 : &remote_video_tracks_;
2070}
2071
2072PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2073 cricket::MediaType media_type) {
2074 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2075 media_type == cricket::MEDIA_TYPE_VIDEO);
2076 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2077 : &local_video_tracks_;
2078}
2079
2080const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2081 const PeerConnection::TrackInfos& infos,
2082 const std::string& stream_label,
2083 const std::string track_id) const {
2084 for (const TrackInfo& track_info : infos) {
2085 if (track_info.stream_label == stream_label &&
2086 track_info.track_id == track_id) {
2087 return &track_info;
2088 }
2089 }
2090 return nullptr;
2091}
2092
2093DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2094 for (const auto& channel : sctp_data_channels_) {
2095 if (channel->id() == sid) {
2096 return channel;
2097 }
2098 }
2099 return nullptr;
2100}
2101
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002102} // namespace webrtc