blob: ccca18af67d9074a03b700a965d730a5615f1909 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00003 * Copyright 2012 Google Inc.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/peerconnection.h"
29
deadbeefeb459812015-12-15 19:24:43 -080030#include <algorithm>
deadbeef0a6c4ca2015-10-06 11:38:28 -070031#include <cctype> // for isdigit
kwiberg0eb15ed2015-12-17 03:04:15 -080032#include <utility>
33#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034
deadbeefab9b2d12015-10-14 11:33:11 -070035#include "talk/app/webrtc/audiotrack.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000036#include "talk/app/webrtc/dtmfsender.h"
37#include "talk/app/webrtc/jsepicecandidate.h"
38#include "talk/app/webrtc/jsepsessiondescription.h"
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +000039#include "talk/app/webrtc/mediaconstraintsinterface.h"
deadbeefab9b2d12015-10-14 11:33:11 -070040#include "talk/app/webrtc/mediastream.h"
deadbeefeb459812015-12-15 19:24:43 -080041#include "talk/app/webrtc/mediastreamobserver.h"
deadbeefab9b2d12015-10-14 11:33:11 -070042#include "talk/app/webrtc/mediastreamproxy.h"
43#include "talk/app/webrtc/mediastreamtrackproxy.h"
44#include "talk/app/webrtc/remoteaudiosource.h"
45#include "talk/app/webrtc/remotevideocapturer.h"
deadbeef70ab1a12015-09-28 16:53:55 -070046#include "talk/app/webrtc/rtpreceiver.h"
47#include "talk/app/webrtc/rtpsender.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000048#include "talk/app/webrtc/streamcollection.h"
deadbeefab9b2d12015-10-14 11:33:11 -070049#include "talk/app/webrtc/videosource.h"
50#include "talk/app/webrtc/videotrack.h"
51#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052#include "talk/session/media/channelmanager.h"
tfarina5237aaf2015-11-10 23:44:30 -080053#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000054#include "webrtc/base/logging.h"
55#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070056#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010057#include "webrtc/base/trace_event.h"
tfarina5237aaf2015-11-10 23:44:30 -080058#include "webrtc/p2p/client/basicportallocator.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010059#include "webrtc/system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
61namespace {
62
deadbeefab9b2d12015-10-14 11:33:11 -070063using webrtc::DataChannel;
64using webrtc::MediaConstraintsInterface;
65using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066using webrtc::PeerConnectionInterface;
deadbeeffac06552015-11-25 11:26:01 -080067using webrtc::RtpSenderInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070068using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069
deadbeefab9b2d12015-10-14 11:33:11 -070070static const char kDefaultStreamLabel[] = "default";
71static const char kDefaultAudioTrackLabel[] = "defaulta0";
72static const char kDefaultVideoTrackLabel[] = "defaultv0";
73
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074// The min number of tokens must present in Turn host uri.
75// e.g. user@turn.example.org
76static const size_t kTurnHostTokensNum = 2;
77// Number of tokens must be preset when TURN uri has transport param.
78static const size_t kTurnTransportTokensNum = 2;
79// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000080static const int kDefaultStunPort = 3478;
81static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082static const char kTransport[] = "transport";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083
84// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070085static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086
deadbeef0a6c4ca2015-10-06 11:38:28 -070087// NOTE: A loop below assumes that the first value of this enum is 0 and all
88// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070090 STUN = 0, // Indicates a STUN server.
91 STUNS, // Indicates a STUN server used with a TLS session.
92 TURN, // Indicates a TURN server
93 TURNS, // Indicates a TURN server used with a TLS session.
94 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095};
tfarina5237aaf2015-11-10 23:44:30 -080096static_assert(INVALID == arraysize(kValidIceServiceTypes),
deadbeef0a6c4ca2015-10-06 11:38:28 -070097 "kValidIceServiceTypes must have as many strings as ServiceType "
98 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099
100enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000101 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700103 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800105 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106};
107
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000108struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 explicit SetSessionDescriptionMsg(
110 webrtc::SetSessionDescriptionObserver* observer)
111 : observer(observer) {
112 }
113
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115 std::string error;
116};
117
deadbeefab9b2d12015-10-14 11:33:11 -0700118struct CreateSessionDescriptionMsg : public rtc::MessageData {
119 explicit CreateSessionDescriptionMsg(
120 webrtc::CreateSessionDescriptionObserver* observer)
121 : observer(observer) {}
122
123 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
124 std::string error;
125};
126
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000127struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000128 GetStatsMsg(webrtc::StatsObserver* observer,
129 webrtc::MediaStreamTrackInterface* track)
130 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000133 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134};
135
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000136// |in_str| should be of format
137// stunURI = scheme ":" stun-host [ ":" stun-port ]
138// scheme = "stun" / "stuns"
139// stun-host = IP-literal / IPv4address / reg-name
140// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700141//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000142// draft-petithuguenin-behave-turn-uris-01
143// turnURI = scheme ":" turn-host [ ":" turn-port ]
144// turn-host = username@IP-literal / IPv4address / reg-name
145bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
146 ServiceType* service_type,
147 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200148 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700149 if (colonpos == std::string::npos) {
150 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000151 return false;
152 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700153 if ((colonpos + 1) == in_str.length()) {
154 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
155 return false;
156 }
157 *service_type = INVALID;
tfarina5237aaf2015-11-10 23:44:30 -0800158 for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700159 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000160 *service_type = static_cast<ServiceType>(i);
161 break;
162 }
163 }
164 if (*service_type == INVALID) {
165 return false;
166 }
167 *hostname = in_str.substr(colonpos + 1, std::string::npos);
168 return true;
169}
170
deadbeef0a6c4ca2015-10-06 11:38:28 -0700171bool ParsePort(const std::string& in_str, int* port) {
172 // Make sure port only contains digits. FromString doesn't check this.
173 for (const char& c : in_str) {
174 if (!std::isdigit(c)) {
175 return false;
176 }
177 }
178 return rtc::FromString(in_str, port);
179}
180
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000181// This method parses IPv6 and IPv4 literal strings, along with hostnames in
182// standard hostname:port format.
183// Consider following formats as correct.
184// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700185// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000186bool ParseHostnameAndPortFromString(const std::string& in_str,
187 std::string* host,
188 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700189 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000190 if (in_str.at(0) == '[') {
191 std::string::size_type closebracket = in_str.rfind(']');
192 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000193 std::string::size_type colonpos = in_str.find(':', closebracket);
194 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700195 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
196 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000197 return false;
198 }
199 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700200 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000201 } else {
202 return false;
203 }
204 } else {
205 std::string::size_type colonpos = in_str.find(':');
206 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700207 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000208 return false;
209 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700210 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000211 } else {
212 *host = in_str;
213 }
214 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700215 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000216}
217
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800218// Adds a STUN or TURN server to the appropriate list,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700219// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200220bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
221 const std::string& url,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800222 cricket::ServerAddresses* stun_servers,
223 std::vector<cricket::RelayServerConfig>* turn_servers) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224 // draft-nandakumar-rtcweb-stun-uri-01
225 // stunURI = scheme ":" stun-host [ ":" stun-port ]
226 // scheme = "stun" / "stuns"
227 // stun-host = IP-literal / IPv4address / reg-name
228 // stun-port = *DIGIT
229
230 // draft-petithuguenin-behave-turn-uris-01
231 // turnURI = scheme ":" turn-host [ ":" turn-port ]
232 // [ "?transport=" transport ]
233 // scheme = "turn" / "turns"
234 // transport = "udp" / "tcp" / transport-ext
235 // transport-ext = 1*unreserved
236 // turn-host = IP-literal / IPv4address / reg-name
237 // turn-port = *DIGIT
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800238 RTC_DCHECK(stun_servers != nullptr);
239 RTC_DCHECK(turn_servers != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200240 std::vector<std::string> tokens;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800241 cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700242 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200243 rtc::tokenize(url, '?', &tokens);
244 std::string uri_without_transport = tokens[0];
245 // Let's look into transport= param, if it exists.
246 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
247 std::string uri_transport_param = tokens[1];
248 rtc::tokenize(uri_transport_param, '=', &tokens);
249 if (tokens[0] == kTransport) {
250 // As per above grammar transport param will be consist of lower case
251 // letters.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800252 if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
253 (turn_transport_type != cricket::PROTO_UDP &&
254 turn_transport_type != cricket::PROTO_TCP)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200255 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700256 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257 }
258 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200259 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200261 std::string hoststring;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262 ServiceType service_type;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200263 if (!GetServiceTypeAndHostnameFromUri(uri_without_transport,
264 &service_type,
265 &hoststring)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700266 LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
267 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200268 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000269
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270 // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
271 RTC_DCHECK(!hoststring.empty());
Tommi77d444a2015-04-24 15:38:38 +0200272
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200273 // Let's break hostname.
274 tokens.clear();
deadbeef0a6c4ca2015-10-06 11:38:28 -0700275 rtc::tokenize_with_empty_tokens(hoststring, '@', &tokens);
276
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200277 std::string username(server.username);
deadbeef0a6c4ca2015-10-06 11:38:28 -0700278 if (tokens.size() > kTurnHostTokensNum) {
279 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
280 return false;
281 }
282 if (tokens.size() == kTurnHostTokensNum) {
283 if (tokens[0].empty() || tokens[1].empty()) {
284 LOG(LS_WARNING) << "Invalid user@hostname format: " << hoststring;
285 return false;
286 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200287 username.assign(rtc::s_url_decode(tokens[0]));
288 hoststring = tokens[1];
289 } else {
290 hoststring = tokens[0];
291 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000292
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200293 int port = kDefaultStunPort;
294 if (service_type == TURNS) {
295 port = kDefaultStunTlsPort;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800296 turn_transport_type = cricket::PROTO_TCP;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200297 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000298
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200299 std::string address;
300 if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700301 LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
302 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200303 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000304
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200305 if (port <= 0 || port > 0xffff) {
306 LOG(WARNING) << "Invalid port: " << port;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700307 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200308 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000309
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200310 switch (service_type) {
311 case STUN:
312 case STUNS:
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800313 stun_servers->insert(rtc::SocketAddress(address, port));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200314 break;
315 case TURN:
316 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200317 bool secure = (service_type == TURNS);
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800318 turn_servers->push_back(
319 cricket::RelayServerConfig(address, port, username, server.password,
320 turn_transport_type, secure));
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200321 break;
322 }
323 case INVALID:
324 default:
325 LOG(WARNING) << "Configuration not supported: " << url;
326 return false;
327 }
328 return true;
329}
330
deadbeefab9b2d12015-10-14 11:33:11 -0700331// Check if we can send |new_stream| on a PeerConnection.
332bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
333 webrtc::MediaStreamInterface* new_stream) {
334 if (!new_stream || !current_streams) {
335 return false;
336 }
337 if (current_streams->find(new_stream->label()) != nullptr) {
338 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
339 << " is already added.";
340 return false;
341 }
342 return true;
343}
344
345bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
346 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
347}
348
deadbeef5e97fb52015-10-15 12:49:08 -0700349// If the direction is "recvonly" or "inactive", treat the description
350// as containing no streams.
351// See: https://code.google.com/p/webrtc/issues/detail?id=5054
352std::vector<cricket::StreamParams> GetActiveStreams(
353 const cricket::MediaContentDescription* desc) {
354 return MediaContentDirectionHasSend(desc->direction())
355 ? desc->streams()
356 : std::vector<cricket::StreamParams>();
357}
358
deadbeefab9b2d12015-10-14 11:33:11 -0700359bool IsValidOfferToReceiveMedia(int value) {
360 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
361 return (value >= Options::kUndefined) &&
362 (value <= Options::kMaxOfferToReceiveMedia);
363}
364
365// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800366void AddSendStreams(
367 cricket::MediaSessionOptions* session_options,
368 const std::vector<rtc::scoped_refptr<RtpSenderInterface>>& senders,
369 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
370 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700371 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800372 for (const auto& sender : senders) {
373 session_options->AddSendStream(sender->media_type(), sender->id(),
374 sender->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700375 }
376
377 // Check for data channels.
378 for (const auto& kv : rtp_data_channels) {
379 const DataChannel* channel = kv.second;
380 if (channel->state() == DataChannel::kConnecting ||
381 channel->state() == DataChannel::kOpen) {
382 // |streamid| and |sync_label| are both set to the DataChannel label
383 // here so they can be signaled the same way as MediaStreams and Tracks.
384 // For MediaStreams, the sync_label is the MediaStream label and the
385 // track label is the same as |streamid|.
386 const std::string& streamid = channel->label();
387 const std::string& sync_label = channel->label();
388 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
389 sync_label);
390 }
391 }
392}
393
deadbeef0a6c4ca2015-10-06 11:38:28 -0700394} // namespace
395
396namespace webrtc {
397
deadbeefab9b2d12015-10-14 11:33:11 -0700398// Factory class for creating remote MediaStreams and MediaStreamTracks.
399class RemoteMediaStreamFactory {
400 public:
401 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
402 cricket::ChannelManager* channel_manager)
403 : signaling_thread_(signaling_thread),
404 channel_manager_(channel_manager) {}
405
406 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
407 const std::string& stream_label) {
408 return MediaStreamProxy::Create(signaling_thread_,
409 MediaStream::Create(stream_label));
410 }
411
Tommif888bb52015-12-12 01:37:01 +0100412 AudioTrackInterface* AddAudioTrack(uint32_t ssrc,
413 AudioProviderInterface* provider,
414 webrtc::MediaStreamInterface* stream,
deadbeefab9b2d12015-10-14 11:33:11 -0700415 const std::string& track_id) {
tommi6eca7e32015-12-15 04:27:11 -0800416 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
Tommif888bb52015-12-12 01:37:01 +0100417 stream, track_id, RemoteAudioSource::Create(ssrc, provider));
deadbeefab9b2d12015-10-14 11:33:11 -0700418 }
419
420 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
421 const std::string& track_id) {
422 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
423 stream, track_id,
424 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
tommi6eca7e32015-12-15 04:27:11 -0800425 nullptr, true)
deadbeefab9b2d12015-10-14 11:33:11 -0700426 .get());
427 }
428
429 private:
430 template <typename TI, typename T, typename TP, typename S>
431 TI* AddTrack(MediaStreamInterface* stream,
432 const std::string& track_id,
Tommif888bb52015-12-12 01:37:01 +0100433 const S& source) {
deadbeefab9b2d12015-10-14 11:33:11 -0700434 rtc::scoped_refptr<TI> track(
435 TP::Create(signaling_thread_, T::Create(track_id, source)));
436 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
437 if (stream->AddTrack(track)) {
438 return track;
439 }
440 return nullptr;
441 }
442
443 rtc::Thread* signaling_thread_;
444 cricket::ChannelManager* channel_manager_;
445};
446
447bool ConvertRtcOptionsForOffer(
448 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
449 cricket::MediaSessionOptions* session_options) {
450 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
451 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
452 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
453 return false;
454 }
455
deadbeefc80741f2015-10-22 13:14:45 -0700456 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700457 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
458 }
deadbeefc80741f2015-10-22 13:14:45 -0700459 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700460 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
461 }
462
463 session_options->vad_enabled = rtc_options.voice_activity_detection;
Taylor Brandstetterf475d362016-01-08 15:35:57 -0800464 session_options->audio_transport_options.ice_restart =
465 rtc_options.ice_restart;
466 session_options->video_transport_options.ice_restart =
467 rtc_options.ice_restart;
468 session_options->data_transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700469 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700470
471 return true;
472}
473
474bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
475 cricket::MediaSessionOptions* session_options) {
476 bool value = false;
477 size_t mandatory_constraints_satisfied = 0;
478
479 // kOfferToReceiveAudio defaults to true according to spec.
480 if (!FindConstraint(constraints,
481 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
482 &mandatory_constraints_satisfied) ||
483 value) {
484 session_options->recv_audio = true;
485 }
486
487 // kOfferToReceiveVideo defaults to false according to spec. But
488 // if it is an answer and video is offered, we should still accept video
489 // per default.
490 value = false;
491 if (!FindConstraint(constraints,
492 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
493 &mandatory_constraints_satisfied) ||
494 value) {
495 session_options->recv_video = true;
496 }
497
498 if (FindConstraint(constraints,
499 MediaConstraintsInterface::kVoiceActivityDetection, &value,
500 &mandatory_constraints_satisfied)) {
501 session_options->vad_enabled = value;
502 }
503
504 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
505 &mandatory_constraints_satisfied)) {
506 session_options->bundle_enabled = value;
507 } else {
508 // kUseRtpMux defaults to true according to spec.
509 session_options->bundle_enabled = true;
510 }
deadbeefab9b2d12015-10-14 11:33:11 -0700511
512 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
513 &value, &mandatory_constraints_satisfied)) {
Taylor Brandstetterf475d362016-01-08 15:35:57 -0800514 session_options->audio_transport_options.ice_restart = value;
515 session_options->video_transport_options.ice_restart = value;
516 session_options->data_transport_options.ice_restart = value;
deadbeefab9b2d12015-10-14 11:33:11 -0700517 } else {
518 // kIceRestart defaults to false according to spec.
Taylor Brandstetterf475d362016-01-08 15:35:57 -0800519 session_options->audio_transport_options.ice_restart = false;
520 session_options->video_transport_options.ice_restart = false;
521 session_options->data_transport_options.ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700522 }
523
524 if (!constraints) {
525 return true;
526 }
527 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
528}
529
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200530bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800531 cricket::ServerAddresses* stun_servers,
532 std::vector<cricket::RelayServerConfig>* turn_servers) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200533 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
534 if (!server.urls.empty()) {
535 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200536 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700537 LOG(LS_ERROR) << "Empty uri.";
538 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200539 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800540 if (!ParseIceServerUrl(server, url, stun_servers, turn_servers)) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200541 return false;
542 }
543 }
544 } else if (!server.uri.empty()) {
545 // Fallback to old .uri if new .urls isn't present.
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800546 if (!ParseIceServerUrl(server, server.uri, stun_servers, turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200548 }
549 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700550 LOG(LS_ERROR) << "Empty uri.";
551 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000552 }
553 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800554 // Candidates must have unique priorities, so that connectivity checks
555 // are performed in a well-defined order.
556 int priority = static_cast<int>(turn_servers->size() - 1);
557 for (cricket::RelayServerConfig& turn_server : *turn_servers) {
558 // First in the list gets highest priority.
559 turn_server.priority = priority--;
560 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000561 return true;
562}
563
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000564PeerConnection::PeerConnection(PeerConnectionFactory* factory)
565 : factory_(factory),
566 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000567 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568 signaling_state_(kStable),
569 ice_state_(kIceNew),
570 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700571 ice_gathering_state_(kIceGatheringNew),
572 local_streams_(StreamCollection::Create()),
573 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000574
575PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100576 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700577 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700578 // Need to detach RTP senders/receivers from WebRtcSession,
579 // since it's about to be destroyed.
580 for (const auto& sender : senders_) {
581 sender->Stop();
582 }
583 for (const auto& receiver : receivers_) {
584 receiver->Stop();
585 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586}
587
588bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000589 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590 const MediaConstraintsInterface* constraints,
deadbeef653b8e02015-11-11 12:55:10 -0800591 rtc::scoped_ptr<cricket::PortAllocator> allocator,
592 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
593 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100594 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef653b8e02015-11-11 12:55:10 -0800595 RTC_DCHECK(observer != nullptr);
596 if (!observer) {
597 return false;
598 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000599 observer_ = observer;
600
kwiberg0eb15ed2015-12-17 03:04:15 -0800601 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800602
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800603 cricket::ServerAddresses stun_servers;
604 std::vector<cricket::RelayServerConfig> turn_servers;
605 if (!ParseIceServers(configuration.servers, &stun_servers, &turn_servers)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000606 return false;
607 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800608 port_allocator_->SetIceServers(stun_servers, turn_servers);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000609
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000611 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000612 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700613 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000614 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000615 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000616 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700617 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
618 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000619 if (!value) {
620 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000621 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000622 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000623 "Disabled") {
624 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000625 }
626
Jiayang Liucac1b382015-04-30 12:35:24 -0700627 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
628 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
629 LOG(LS_INFO) << "TCP candidates are disabled.";
630 }
631
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000632 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000633 // No step delay is used while allocating ports.
634 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
635
stefanc1aeaf02015-10-15 07:26:07 -0700636 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000637
stefanc1aeaf02015-10-15 07:26:07 -0700638 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
639 factory_->signaling_thread(), media_controller_->channel_manager()));
640
641 session_.reset(
642 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
643 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700644 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645
646 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000647 if (!session_->Initialize(factory_->options(), constraints,
kwiberg0eb15ed2015-12-17 03:04:15 -0800648 std::move(dtls_identity_store), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000649 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700650 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000651
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000652 // Register PeerConnection as receiver of local ice candidates.
653 // All the callbacks will be posted to the application from PeerConnection.
654 session_->RegisterIceObserver(this);
655 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700656 session_->SignalVoiceChannelDestroyed.connect(
657 this, &PeerConnection::OnVoiceChannelDestroyed);
658 session_->SignalVideoChannelDestroyed.connect(
659 this, &PeerConnection::OnVideoChannelDestroyed);
660 session_->SignalDataChannelCreated.connect(
661 this, &PeerConnection::OnDataChannelCreated);
662 session_->SignalDataChannelDestroyed.connect(
663 this, &PeerConnection::OnDataChannelDestroyed);
664 session_->SignalDataChannelOpenMessage.connect(
665 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666 return true;
667}
668
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000669rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000670PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700671 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672}
673
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000674rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700676 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677}
678
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000679bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100680 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 if (IsClosed()) {
682 return false;
683 }
deadbeefab9b2d12015-10-14 11:33:11 -0700684 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 return false;
686 }
deadbeefab9b2d12015-10-14 11:33:11 -0700687
688 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800689 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
690 observer->SignalAudioTrackAdded.connect(this,
691 &PeerConnection::OnAudioTrackAdded);
692 observer->SignalAudioTrackRemoved.connect(
693 this, &PeerConnection::OnAudioTrackRemoved);
694 observer->SignalVideoTrackAdded.connect(this,
695 &PeerConnection::OnVideoTrackAdded);
696 observer->SignalVideoTrackRemoved.connect(
697 this, &PeerConnection::OnVideoTrackRemoved);
698 stream_observers_.push_back(rtc::scoped_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700699
deadbeefab9b2d12015-10-14 11:33:11 -0700700 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800701 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700702 }
703 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800704 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700705 }
706
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000707 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708 observer_->OnRenegotiationNeeded();
709 return true;
710}
711
712void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100713 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700714 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800715 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700716 }
717 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800718 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700719 }
720
721 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800722 stream_observers_.erase(
723 std::remove_if(
724 stream_observers_.begin(), stream_observers_.end(),
725 [local_stream](const rtc::scoped_ptr<MediaStreamObserver>& observer) {
726 return observer->stream()->label().compare(local_stream->label()) ==
727 0;
728 }),
729 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700730
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 if (IsClosed()) {
732 return;
733 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734 observer_->OnRenegotiationNeeded();
735}
736
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000737rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000738 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100739 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740 if (!track) {
741 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
742 return NULL;
743 }
deadbeefab9b2d12015-10-14 11:33:11 -0700744 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
746 return NULL;
747 }
748
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000749 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750 DtmfSender::Create(track, signaling_thread(), session_.get()));
751 if (!sender.get()) {
752 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
753 return NULL;
754 }
755 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
756}
757
deadbeeffac06552015-11-25 11:26:01 -0800758rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800759 const std::string& kind,
760 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100761 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
deadbeeffac06552015-11-25 11:26:01 -0800762 RtpSenderInterface* new_sender;
763 if (kind == MediaStreamTrackInterface::kAudioKind) {
764 new_sender = new AudioRtpSender(session_.get(), stats_.get());
765 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
766 new_sender = new VideoRtpSender(session_.get());
767 } else {
768 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
769 return rtc::scoped_refptr<RtpSenderInterface>();
770 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800771 if (!stream_id.empty()) {
772 new_sender->set_stream_id(stream_id);
773 }
deadbeeffac06552015-11-25 11:26:01 -0800774 senders_.push_back(new_sender);
775 return RtpSenderProxy::Create(signaling_thread(), new_sender);
776}
777
deadbeef70ab1a12015-09-28 16:53:55 -0700778std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
779 const {
780 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
781 for (const auto& sender : senders_) {
782 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
783 }
784 return senders;
785}
786
787std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
788PeerConnection::GetReceivers() const {
789 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
790 for (const auto& receiver : receivers_) {
791 receivers.push_back(
792 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
793 }
794 return receivers;
795}
796
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000798 MediaStreamTrackInterface* track,
799 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100800 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700801 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802 if (!VERIFY(observer != NULL)) {
803 LOG(LS_ERROR) << "GetStats - observer is NULL.";
804 return false;
805 }
806
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000807 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000808 signaling_thread()->Post(this, MSG_GETSTATS,
809 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810 return true;
811}
812
813PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
814 return signaling_state_;
815}
816
817PeerConnectionInterface::IceState PeerConnection::ice_state() {
818 return ice_state_;
819}
820
821PeerConnectionInterface::IceConnectionState
822PeerConnection::ice_connection_state() {
823 return ice_connection_state_;
824}
825
826PeerConnectionInterface::IceGatheringState
827PeerConnection::ice_gathering_state() {
828 return ice_gathering_state_;
829}
830
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000831rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832PeerConnection::CreateDataChannel(
833 const std::string& label,
834 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100835 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
deadbeefab9b2d12015-10-14 11:33:11 -0700836 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000837
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000838 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000839 if (config) {
840 internal_config.reset(new InternalDataChannelInit(*config));
841 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000842 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700843 InternalCreateDataChannel(label, internal_config.get()));
844 if (!channel.get()) {
845 return nullptr;
846 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000848 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
849 // the first SCTP DataChannel.
850 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
851 observer_->OnRenegotiationNeeded();
852 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000853
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000854 return DataChannelProxy::Create(signaling_thread(), channel.get());
855}
856
857void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
858 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100859 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700860 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000861 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
862 return;
863 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000864 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000865
866 bool value;
867 size_t mandatory_constraints = 0;
868
869 if (FindConstraint(constraints,
870 MediaConstraintsInterface::kOfferToReceiveAudio,
871 &value,
872 &mandatory_constraints)) {
873 options.offer_to_receive_audio =
874 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
875 }
876
877 if (FindConstraint(constraints,
878 MediaConstraintsInterface::kOfferToReceiveVideo,
879 &value,
880 &mandatory_constraints)) {
881 options.offer_to_receive_video =
882 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
883 }
884
885 if (FindConstraint(constraints,
886 MediaConstraintsInterface::kVoiceActivityDetection,
887 &value,
888 &mandatory_constraints)) {
889 options.voice_activity_detection = value;
890 }
891
892 if (FindConstraint(constraints,
893 MediaConstraintsInterface::kIceRestart,
894 &value,
895 &mandatory_constraints)) {
896 options.ice_restart = value;
897 }
898
899 if (FindConstraint(constraints,
900 MediaConstraintsInterface::kUseRtpMux,
901 &value,
902 &mandatory_constraints)) {
903 options.use_rtp_mux = value;
904 }
905
906 CreateOffer(observer, options);
907}
908
909void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
910 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100911 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
deadbeefab9b2d12015-10-14 11:33:11 -0700912 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000913 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
914 return;
915 }
deadbeefab9b2d12015-10-14 11:33:11 -0700916
917 cricket::MediaSessionOptions session_options;
918 if (!GetOptionsForOffer(options, &session_options)) {
919 std::string error = "CreateOffer called with invalid options.";
920 LOG(LS_ERROR) << error;
921 PostCreateSessionDescriptionFailure(observer, error);
922 return;
923 }
924
925 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926}
927
928void PeerConnection::CreateAnswer(
929 CreateSessionDescriptionObserver* observer,
930 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100931 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
deadbeefab9b2d12015-10-14 11:33:11 -0700932 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
934 return;
935 }
deadbeefab9b2d12015-10-14 11:33:11 -0700936
937 cricket::MediaSessionOptions session_options;
938 if (!GetOptionsForAnswer(constraints, &session_options)) {
939 std::string error = "CreateAnswer called with invalid constraints.";
940 LOG(LS_ERROR) << error;
941 PostCreateSessionDescriptionFailure(observer, error);
942 return;
943 }
944
945 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946}
947
948void PeerConnection::SetLocalDescription(
949 SetSessionDescriptionObserver* observer,
950 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100951 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
deadbeefab9b2d12015-10-14 11:33:11 -0700952 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
954 return;
955 }
956 if (!desc) {
957 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
958 return;
959 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 // Update stats here so that we have the most recent stats for tracks and
961 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000962 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 std::string error;
964 if (!session_->SetLocalDescription(desc, &error)) {
965 PostSetSessionDescriptionFailure(observer, error);
966 return;
967 }
deadbeefab9b2d12015-10-14 11:33:11 -0700968
969 // If setting the description decided our SSL role, allocate any necessary
970 // SCTP sids.
971 rtc::SSLRole role;
972 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -0800973 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700974 AllocateSctpSids(role);
975 }
976
977 // Update state and SSRC of local MediaStreams and DataChannels based on the
978 // local session description.
979 const cricket::ContentInfo* audio_content =
980 GetFirstAudioContent(desc->description());
981 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800982 if (audio_content->rejected) {
983 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
984 } else {
985 const cricket::AudioContentDescription* audio_desc =
986 static_cast<const cricket::AudioContentDescription*>(
987 audio_content->description);
988 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
989 }
deadbeefab9b2d12015-10-14 11:33:11 -0700990 }
991
992 const cricket::ContentInfo* video_content =
993 GetFirstVideoContent(desc->description());
994 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800995 if (video_content->rejected) {
996 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
997 } else {
998 const cricket::VideoContentDescription* video_desc =
999 static_cast<const cricket::VideoContentDescription*>(
1000 video_content->description);
1001 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1002 }
deadbeefab9b2d12015-10-14 11:33:11 -07001003 }
1004
1005 const cricket::ContentInfo* data_content =
1006 GetFirstDataContent(desc->description());
1007 if (data_content) {
1008 const cricket::DataContentDescription* data_desc =
1009 static_cast<const cricket::DataContentDescription*>(
1010 data_content->description);
1011 if (rtc::starts_with(data_desc->protocol().data(),
1012 cricket::kMediaProtocolRtpPrefix)) {
1013 UpdateLocalRtpDataChannels(data_desc->streams());
1014 }
1015 }
1016
1017 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001019
deadbeefcbecd352015-09-23 11:50:27 -07001020 // MaybeStartGathering needs to be called after posting
1021 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1022 // before signaling that SetLocalDescription completed.
1023 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024}
1025
1026void PeerConnection::SetRemoteDescription(
1027 SetSessionDescriptionObserver* observer,
1028 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001029 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
deadbeefab9b2d12015-10-14 11:33:11 -07001030 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1032 return;
1033 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 if (!desc) {
1035 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1036 return;
1037 }
1038 // Update stats here so that we have the most recent stats for tracks and
1039 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001040 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 std::string error;
1042 if (!session_->SetRemoteDescription(desc, &error)) {
1043 PostSetSessionDescriptionFailure(observer, error);
1044 return;
1045 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001046
deadbeefab9b2d12015-10-14 11:33:11 -07001047 // If setting the description decided our SSL role, allocate any necessary
1048 // SCTP sids.
1049 rtc::SSLRole role;
1050 if (session_->data_channel_type() == cricket::DCT_SCTP &&
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001051 session_->GetSslRole(session_->data_channel(), &role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001052 AllocateSctpSids(role);
1053 }
1054
1055 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001056 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1057 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1058 const cricket::AudioContentDescription* audio_desc =
1059 GetFirstAudioContentDescription(remote_desc);
1060 const cricket::VideoContentDescription* video_desc =
1061 GetFirstVideoContentDescription(remote_desc);
1062 const cricket::DataContentDescription* data_desc =
1063 GetFirstDataContentDescription(remote_desc);
1064
1065 // Check if the descriptions include streams, just in case the peer supports
1066 // MSID, but doesn't indicate so with "a=msid-semantic".
1067 if (remote_desc->msid_supported() ||
1068 (audio_desc && !audio_desc->streams().empty()) ||
1069 (video_desc && !video_desc->streams().empty())) {
1070 remote_peer_supports_msid_ = true;
1071 }
deadbeefab9b2d12015-10-14 11:33:11 -07001072
1073 // We wait to signal new streams until we finish processing the description,
1074 // since only at that point will new streams have all their tracks.
1075 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1076
1077 // Find all audio rtp streams and create corresponding remote AudioTracks
1078 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001079 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001080 if (audio_content->rejected) {
1081 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1082 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001083 bool default_audio_track_needed =
1084 !remote_peer_supports_msid_ &&
1085 MediaContentDirectionHasSend(audio_desc->direction());
1086 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1087 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001088 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001089 }
deadbeefab9b2d12015-10-14 11:33:11 -07001090 }
1091
1092 // Find all video rtp streams and create corresponding remote VideoTracks
1093 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001094 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001095 if (video_content->rejected) {
1096 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1097 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001098 bool default_video_track_needed =
1099 !remote_peer_supports_msid_ &&
1100 MediaContentDirectionHasSend(video_desc->direction());
1101 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1102 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001103 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001104 }
deadbeefab9b2d12015-10-14 11:33:11 -07001105 }
1106
1107 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001108 if (data_desc) {
1109 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001110 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001111 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001112 }
1113 }
1114
1115 // Iterate new_streams and notify the observer about new MediaStreams.
1116 for (size_t i = 0; i < new_streams->count(); ++i) {
1117 MediaStreamInterface* new_stream = new_streams->at(i);
1118 stats_->AddStream(new_stream);
1119 observer_->OnAddStream(new_stream);
1120 }
1121
deadbeefbda7e0b2015-12-08 17:13:40 -08001122 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001123
1124 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1125 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001126}
1127
deadbeefa67696b2015-09-29 11:56:26 -07001128bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001129 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001130 if (port_allocator_) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -08001131 cricket::ServerAddresses stun_servers;
1132 std::vector<cricket::RelayServerConfig> turn_servers;
1133 if (!ParseIceServers(config.servers, &stun_servers, &turn_servers)) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001134 return false;
1135 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -08001136 port_allocator_->SetIceServers(stun_servers, turn_servers);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001137 }
honghaiz1f429e32015-09-28 07:57:34 -07001138 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001139 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001140}
1141
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142bool PeerConnection::AddIceCandidate(
1143 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001144 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001145 return session_->ProcessIceMessage(ice_candidate);
1146}
1147
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001148void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001149 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001150 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001151
1152 if (session_) {
1153 session_->set_metrics_observer(uma_observer_);
1154 }
1155
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001156 // Send information about IPv4/IPv6 status.
1157 if (uma_observer_ && port_allocator_) {
1158 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001159 uma_observer_->IncrementEnumCounter(
1160 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1161 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001162 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001163 uma_observer_->IncrementEnumCounter(
1164 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1165 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001166 }
1167 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001168}
1169
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170const SessionDescriptionInterface* PeerConnection::local_description() const {
1171 return session_->local_description();
1172}
1173
1174const SessionDescriptionInterface* PeerConnection::remote_description() const {
1175 return session_->remote_description();
1176}
1177
1178void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001179 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001180 // Update stats here so that we have the most recent stats for tracks and
1181 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001182 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183
deadbeefd59daf82015-10-14 15:02:44 -07001184 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185}
1186
deadbeefd59daf82015-10-14 15:02:44 -07001187void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1188 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001189 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001190 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001192 break;
deadbeefd59daf82015-10-14 15:02:44 -07001193 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1195 break;
deadbeefd59daf82015-10-14 15:02:44 -07001196 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1198 break;
deadbeefd59daf82015-10-14 15:02:44 -07001199 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1201 break;
deadbeefd59daf82015-10-14 15:02:44 -07001202 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1204 break;
deadbeefd59daf82015-10-14 15:02:44 -07001205 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 ChangeSignalingState(PeerConnectionInterface::kStable);
1207 break;
deadbeefd59daf82015-10-14 15:02:44 -07001208 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209 ChangeSignalingState(PeerConnectionInterface::kClosed);
1210 break;
1211 default:
1212 break;
1213 }
1214}
1215
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001216void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001218 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1219 SetSessionDescriptionMsg* param =
1220 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1221 param->observer->OnSuccess();
1222 delete param;
1223 break;
1224 }
1225 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1226 SetSessionDescriptionMsg* param =
1227 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1228 param->observer->OnFailure(param->error);
1229 delete param;
1230 break;
1231 }
deadbeefab9b2d12015-10-14 11:33:11 -07001232 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1233 CreateSessionDescriptionMsg* param =
1234 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1235 param->observer->OnFailure(param->error);
1236 delete param;
1237 break;
1238 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239 case MSG_GETSTATS: {
1240 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001241 StatsReports reports;
1242 stats_->GetStats(param->track, &reports);
1243 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244 delete param;
1245 break;
1246 }
deadbeefbd292462015-12-14 18:15:29 -08001247 case MSG_FREE_DATACHANNELS: {
1248 sctp_data_channels_to_free_.clear();
1249 break;
1250 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001251 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001252 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001253 break;
1254 }
1255}
1256
deadbeefab9b2d12015-10-14 11:33:11 -07001257void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1258 AudioTrackInterface* audio_track,
1259 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001260 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261}
1262
deadbeefab9b2d12015-10-14 11:33:11 -07001263void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1264 VideoTrackInterface* video_track,
1265 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001266 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267}
1268
deadbeef70ab1a12015-09-28 16:53:55 -07001269// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1270// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001271void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1272 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001273 auto it = FindReceiverForTrack(audio_track);
1274 if (it == receivers_.end()) {
1275 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1276 << " doesn't exist.";
1277 } else {
1278 (*it)->Stop();
1279 receivers_.erase(it);
1280 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281}
1282
deadbeefab9b2d12015-10-14 11:33:11 -07001283void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1284 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001285 auto it = FindReceiverForTrack(video_track);
1286 if (it == receivers_.end()) {
1287 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1288 << " doesn't exist.";
1289 } else {
1290 (*it)->Stop();
1291 receivers_.erase(it);
1292 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293}
deadbeef70ab1a12015-09-28 16:53:55 -07001294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295void PeerConnection::OnIceConnectionChange(
1296 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001297 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001298 // After transitioning to "closed", ignore any additional states from
1299 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001300 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001301 return;
1302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001304 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305}
1306
1307void PeerConnection::OnIceGatheringChange(
1308 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001309 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 if (IsClosed()) {
1311 return;
1312 }
1313 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001314 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315}
1316
1317void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001318 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001319 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320}
1321
1322void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001323 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001324 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325}
1326
Peter Thatcher54360512015-07-08 11:08:35 -07001327void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001328 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001329 observer_->OnIceConnectionReceivingChange(receiving);
1330}
1331
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332void PeerConnection::ChangeSignalingState(
1333 PeerConnectionInterface::SignalingState signaling_state) {
1334 signaling_state_ = signaling_state;
1335 if (signaling_state == kClosed) {
1336 ice_connection_state_ = kIceConnectionClosed;
1337 observer_->OnIceConnectionChange(ice_connection_state_);
1338 if (ice_gathering_state_ != kIceGatheringComplete) {
1339 ice_gathering_state_ = kIceGatheringComplete;
1340 observer_->OnIceGatheringChange(ice_gathering_state_);
1341 }
1342 }
1343 observer_->OnSignalingChange(signaling_state_);
1344 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1345}
1346
deadbeefeb459812015-12-15 19:24:43 -08001347void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1348 MediaStreamInterface* stream) {
1349 auto sender = FindSenderForTrack(track);
1350 if (sender != senders_.end()) {
1351 // We already have a sender for this track, so just change the stream_id
1352 // so that it's correct in the next call to CreateOffer.
1353 (*sender)->set_stream_id(stream->label());
1354 return;
1355 }
1356
1357 // Normal case; we've never seen this track before.
1358 AudioRtpSender* new_sender =
1359 new AudioRtpSender(track, stream->label(), session_.get(), stats_.get());
1360 senders_.push_back(new_sender);
1361 // If the sender has already been configured in SDP, we call SetSsrc,
1362 // which will connect the sender to the underlying transport. This can
1363 // occur if a local session description that contains the ID of the sender
1364 // is set before AddStream is called. It can also occur if the local
1365 // session description is not changed and RemoveStream is called, and
1366 // later AddStream is called again with the same stream.
1367 const TrackInfo* track_info =
1368 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1369 if (track_info) {
1370 new_sender->SetSsrc(track_info->ssrc);
1371 }
1372}
1373
1374// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1375// indefinitely, when we have unified plan SDP.
1376void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1377 MediaStreamInterface* stream) {
1378 auto sender = FindSenderForTrack(track);
1379 if (sender == senders_.end()) {
1380 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1381 << " doesn't exist.";
1382 return;
1383 }
1384 (*sender)->Stop();
1385 senders_.erase(sender);
1386}
1387
1388void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1389 MediaStreamInterface* stream) {
1390 auto sender = FindSenderForTrack(track);
1391 if (sender != senders_.end()) {
1392 // We already have a sender for this track, so just change the stream_id
1393 // so that it's correct in the next call to CreateOffer.
1394 (*sender)->set_stream_id(stream->label());
1395 return;
1396 }
1397
1398 // Normal case; we've never seen this track before.
1399 VideoRtpSender* new_sender =
1400 new VideoRtpSender(track, stream->label(), session_.get());
1401 senders_.push_back(new_sender);
1402 const TrackInfo* track_info =
1403 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1404 if (track_info) {
1405 new_sender->SetSsrc(track_info->ssrc);
1406 }
1407}
1408
1409void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1410 MediaStreamInterface* stream) {
1411 auto sender = FindSenderForTrack(track);
1412 if (sender == senders_.end()) {
1413 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1414 << " doesn't exist.";
1415 return;
1416 }
1417 (*sender)->Stop();
1418 senders_.erase(sender);
1419}
1420
deadbeefab9b2d12015-10-14 11:33:11 -07001421void PeerConnection::PostSetSessionDescriptionFailure(
1422 SetSessionDescriptionObserver* observer,
1423 const std::string& error) {
1424 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1425 msg->error = error;
1426 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1427}
1428
1429void PeerConnection::PostCreateSessionDescriptionFailure(
1430 CreateSessionDescriptionObserver* observer,
1431 const std::string& error) {
1432 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1433 msg->error = error;
1434 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1435}
1436
1437bool PeerConnection::GetOptionsForOffer(
1438 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1439 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001440 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1441 return false;
1442 }
1443
deadbeeffac06552015-11-25 11:26:01 -08001444 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001445 // Offer to receive audio/video if the constraint is not set and there are
1446 // send streams, or we're currently receiving.
1447 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1448 session_options->recv_audio =
1449 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1450 !remote_audio_tracks_.empty();
1451 }
1452 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1453 session_options->recv_video =
1454 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1455 !remote_video_tracks_.empty();
1456 }
1457 session_options->bundle_enabled =
1458 session_options->bundle_enabled &&
1459 (session_options->has_audio() || session_options->has_video() ||
1460 session_options->has_data());
1461
deadbeefab9b2d12015-10-14 11:33:11 -07001462 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1463 session_options->data_channel_type = cricket::DCT_SCTP;
1464 }
1465 return true;
1466}
1467
1468bool PeerConnection::GetOptionsForAnswer(
1469 const MediaConstraintsInterface* constraints,
1470 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001471 session_options->recv_audio = false;
1472 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001473 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1474 return false;
1475 }
1476
deadbeeffac06552015-11-25 11:26:01 -08001477 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001478 session_options->bundle_enabled =
1479 session_options->bundle_enabled &&
1480 (session_options->has_audio() || session_options->has_video() ||
1481 session_options->has_data());
1482
deadbeefab9b2d12015-10-14 11:33:11 -07001483 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1484 // are not signaled in the SDP so does not go through that path and must be
1485 // handled here.
1486 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1487 session_options->data_channel_type = cricket::DCT_SCTP;
1488 }
1489 return true;
1490}
1491
deadbeeffaac4972015-11-12 15:33:07 -08001492void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1493 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001494 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1495 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001496}
1497
deadbeefab9b2d12015-10-14 11:33:11 -07001498void PeerConnection::UpdateRemoteStreamsList(
1499 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001500 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001501 cricket::MediaType media_type,
1502 StreamCollection* new_streams) {
1503 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1504
1505 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001506 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001507 auto track_it = current_tracks->begin();
1508 while (track_it != current_tracks->end()) {
1509 const TrackInfo& info = *track_it;
1510 const cricket::StreamParams* params =
1511 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001512 bool track_exists = params && params->id == info.track_id;
1513 // If this is a default track, and we still need it, don't remove it.
1514 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1515 track_exists) {
1516 ++track_it;
1517 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001518 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1519 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001520 }
1521 }
1522
1523 // Find new and active tracks.
1524 for (const cricket::StreamParams& params : streams) {
1525 // The sync_label is the MediaStream label and the |stream.id| is the
1526 // track id.
1527 const std::string& stream_label = params.sync_label;
1528 const std::string& track_id = params.id;
1529 uint32_t ssrc = params.first_ssrc();
1530
1531 rtc::scoped_refptr<MediaStreamInterface> stream =
1532 remote_streams_->find(stream_label);
1533 if (!stream) {
1534 // This is a new MediaStream. Create a new remote MediaStream.
1535 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1536 remote_streams_->AddStream(stream);
1537 new_streams->AddStream(stream);
1538 }
1539
1540 const TrackInfo* track_info =
1541 FindTrackInfo(*current_tracks, stream_label, track_id);
1542 if (!track_info) {
1543 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1544 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1545 }
1546 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001547
1548 // Add default track if necessary.
1549 if (default_track_needed) {
1550 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1551 remote_streams_->find(kDefaultStreamLabel);
1552 if (!default_stream) {
1553 // Create the new default MediaStream.
1554 default_stream =
1555 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1556 remote_streams_->AddStream(default_stream);
1557 new_streams->AddStream(default_stream);
1558 }
1559 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1560 ? kDefaultAudioTrackLabel
1561 : kDefaultVideoTrackLabel;
1562 const TrackInfo* default_track_info =
1563 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1564 if (!default_track_info) {
1565 current_tracks->push_back(
1566 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1567 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1568 }
1569 }
deadbeefab9b2d12015-10-14 11:33:11 -07001570}
1571
1572void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1573 const std::string& track_id,
1574 uint32_t ssrc,
1575 cricket::MediaType media_type) {
1576 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1577
1578 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Tommif888bb52015-12-12 01:37:01 +01001579 AudioTrackInterface* audio_track = remote_stream_factory_->AddAudioTrack(
1580 ssrc, session_.get(), stream, track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001581 CreateAudioReceiver(stream, audio_track, ssrc);
1582 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1583 VideoTrackInterface* video_track =
1584 remote_stream_factory_->AddVideoTrack(stream, track_id);
1585 CreateVideoReceiver(stream, video_track, ssrc);
1586 } else {
1587 RTC_DCHECK(false && "Invalid media type");
1588 }
1589}
1590
1591void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1592 const std::string& track_id,
1593 cricket::MediaType media_type) {
1594 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1595
1596 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1597 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1598 stream->FindAudioTrack(track_id);
1599 if (audio_track) {
1600 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1601 stream->RemoveTrack(audio_track);
1602 DestroyAudioReceiver(stream, audio_track);
1603 }
1604 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1605 rtc::scoped_refptr<VideoTrackInterface> video_track =
1606 stream->FindVideoTrack(track_id);
1607 if (video_track) {
1608 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1609 stream->RemoveTrack(video_track);
1610 DestroyVideoReceiver(stream, video_track);
1611 }
1612 } else {
1613 ASSERT(false && "Invalid media type");
1614 }
1615}
1616
1617void PeerConnection::UpdateEndedRemoteMediaStreams() {
1618 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1619 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1620 MediaStreamInterface* stream = remote_streams_->at(i);
1621 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1622 streams_to_remove.push_back(stream);
1623 }
1624 }
1625
1626 for (const auto& stream : streams_to_remove) {
1627 remote_streams_->RemoveStream(stream);
1628 observer_->OnRemoveStream(stream);
1629 }
1630}
1631
deadbeefab9b2d12015-10-14 11:33:11 -07001632void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1633 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1634 for (TrackInfos::iterator track_it = current_tracks->begin();
1635 track_it != current_tracks->end(); ++track_it) {
1636 const TrackInfo& info = *track_it;
1637 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1638 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1639 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1640 // There's no guarantee the track is still available, e.g. the track may
1641 // have been removed from the stream by javascript.
1642 if (track) {
1643 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1644 }
1645 }
1646 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1647 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1648 // There's no guarantee the track is still available, e.g. the track may
1649 // have been removed from the stream by javascript.
1650 if (track) {
1651 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1652 }
1653 }
1654 }
1655}
1656
1657void PeerConnection::UpdateLocalTracks(
1658 const std::vector<cricket::StreamParams>& streams,
1659 cricket::MediaType media_type) {
1660 TrackInfos* current_tracks = GetLocalTracks(media_type);
1661
1662 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1663 // don't match the new StreamParam.
1664 TrackInfos::iterator track_it = current_tracks->begin();
1665 while (track_it != current_tracks->end()) {
1666 const TrackInfo& info = *track_it;
1667 const cricket::StreamParams* params =
1668 cricket::GetStreamBySsrc(streams, info.ssrc);
1669 if (!params || params->id != info.track_id ||
1670 params->sync_label != info.stream_label) {
1671 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1672 media_type);
1673 track_it = current_tracks->erase(track_it);
1674 } else {
1675 ++track_it;
1676 }
1677 }
1678
1679 // Find new and active tracks.
1680 for (const cricket::StreamParams& params : streams) {
1681 // The sync_label is the MediaStream label and the |stream.id| is the
1682 // track id.
1683 const std::string& stream_label = params.sync_label;
1684 const std::string& track_id = params.id;
1685 uint32_t ssrc = params.first_ssrc();
1686 const TrackInfo* track_info =
1687 FindTrackInfo(*current_tracks, stream_label, track_id);
1688 if (!track_info) {
1689 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1690 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1691 }
1692 }
1693}
1694
1695void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1696 const std::string& track_id,
1697 uint32_t ssrc,
1698 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001699 RtpSenderInterface* sender = FindSenderById(track_id);
1700 if (!sender) {
1701 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1702 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001703 return;
1704 }
1705
deadbeeffac06552015-11-25 11:26:01 -08001706 if (sender->media_type() != media_type) {
1707 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1708 << " description with an unexpected media type.";
1709 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001710 }
deadbeeffac06552015-11-25 11:26:01 -08001711
1712 sender->set_stream_id(stream_label);
1713 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001714}
1715
1716void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1717 const std::string& track_id,
1718 uint32_t ssrc,
1719 cricket::MediaType media_type) {
deadbeeffac06552015-11-25 11:26:01 -08001720 RtpSenderInterface* sender = FindSenderById(track_id);
1721 if (!sender) {
1722 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001723 // SessionDescriptions has been renegotiated.
1724 return;
1725 }
deadbeeffac06552015-11-25 11:26:01 -08001726
1727 // A sender has been removed from the SessionDescription but it's still
1728 // associated with the PeerConnection. This only occurs if the SDP doesn't
1729 // match with the calls to CreateSender, AddStream and RemoveStream.
1730 if (sender->media_type() != media_type) {
1731 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1732 << " description with an unexpected media type.";
1733 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001734 }
deadbeeffac06552015-11-25 11:26:01 -08001735
1736 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001737}
1738
1739void PeerConnection::UpdateLocalRtpDataChannels(
1740 const cricket::StreamParamsVec& streams) {
1741 std::vector<std::string> existing_channels;
1742
1743 // Find new and active data channels.
1744 for (const cricket::StreamParams& params : streams) {
1745 // |it->sync_label| is actually the data channel label. The reason is that
1746 // we use the same naming of data channels as we do for
1747 // MediaStreams and Tracks.
1748 // For MediaStreams, the sync_label is the MediaStream label and the
1749 // track label is the same as |streamid|.
1750 const std::string& channel_label = params.sync_label;
1751 auto data_channel_it = rtp_data_channels_.find(channel_label);
1752 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1753 continue;
1754 }
1755 // Set the SSRC the data channel should use for sending.
1756 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1757 existing_channels.push_back(data_channel_it->first);
1758 }
1759
1760 UpdateClosingRtpDataChannels(existing_channels, true);
1761}
1762
1763void PeerConnection::UpdateRemoteRtpDataChannels(
1764 const cricket::StreamParamsVec& streams) {
1765 std::vector<std::string> existing_channels;
1766
1767 // Find new and active data channels.
1768 for (const cricket::StreamParams& params : streams) {
1769 // The data channel label is either the mslabel or the SSRC if the mslabel
1770 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1771 std::string label = params.sync_label.empty()
1772 ? rtc::ToString(params.first_ssrc())
1773 : params.sync_label;
1774 auto data_channel_it = rtp_data_channels_.find(label);
1775 if (data_channel_it == rtp_data_channels_.end()) {
1776 // This is a new data channel.
1777 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1778 } else {
1779 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1780 }
1781 existing_channels.push_back(label);
1782 }
1783
1784 UpdateClosingRtpDataChannels(existing_channels, false);
1785}
1786
1787void PeerConnection::UpdateClosingRtpDataChannels(
1788 const std::vector<std::string>& active_channels,
1789 bool is_local_update) {
1790 auto it = rtp_data_channels_.begin();
1791 while (it != rtp_data_channels_.end()) {
1792 DataChannel* data_channel = it->second;
1793 if (std::find(active_channels.begin(), active_channels.end(),
1794 data_channel->label()) != active_channels.end()) {
1795 ++it;
1796 continue;
1797 }
1798
1799 if (is_local_update) {
1800 data_channel->SetSendSsrc(0);
1801 } else {
1802 data_channel->RemotePeerRequestClose();
1803 }
1804
1805 if (data_channel->state() == DataChannel::kClosed) {
1806 rtp_data_channels_.erase(it);
1807 it = rtp_data_channels_.begin();
1808 } else {
1809 ++it;
1810 }
1811 }
1812}
1813
1814void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1815 uint32_t remote_ssrc) {
1816 rtc::scoped_refptr<DataChannel> channel(
1817 InternalCreateDataChannel(label, nullptr));
1818 if (!channel.get()) {
1819 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1820 << "CreateDataChannel failed.";
1821 return;
1822 }
1823 channel->SetReceiveSsrc(remote_ssrc);
1824 observer_->OnDataChannel(
1825 DataChannelProxy::Create(signaling_thread(), channel));
1826}
1827
1828rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1829 const std::string& label,
1830 const InternalDataChannelInit* config) {
1831 if (IsClosed()) {
1832 return nullptr;
1833 }
1834 if (session_->data_channel_type() == cricket::DCT_NONE) {
1835 LOG(LS_ERROR)
1836 << "InternalCreateDataChannel: Data is not supported in this call.";
1837 return nullptr;
1838 }
1839 InternalDataChannelInit new_config =
1840 config ? (*config) : InternalDataChannelInit();
1841 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1842 if (new_config.id < 0) {
1843 rtc::SSLRole role;
Taylor Brandstetterf475d362016-01-08 15:35:57 -08001844 if ((session_->GetSslRole(session_->data_channel(), &role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07001845 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1846 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1847 return nullptr;
1848 }
1849 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1850 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1851 << "because the id is already in use or out of range.";
1852 return nullptr;
1853 }
1854 }
1855
1856 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1857 session_.get(), session_->data_channel_type(), label, new_config));
1858 if (!channel) {
1859 sid_allocator_.ReleaseSid(new_config.id);
1860 return nullptr;
1861 }
1862
1863 if (channel->data_channel_type() == cricket::DCT_RTP) {
1864 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1865 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1866 << " already exists.";
1867 return nullptr;
1868 }
1869 rtp_data_channels_[channel->label()] = channel;
1870 } else {
1871 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1872 sctp_data_channels_.push_back(channel);
1873 channel->SignalClosed.connect(this,
1874 &PeerConnection::OnSctpDataChannelClosed);
1875 }
1876
1877 return channel;
1878}
1879
1880bool PeerConnection::HasDataChannels() const {
1881 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1882}
1883
1884void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1885 for (const auto& channel : sctp_data_channels_) {
1886 if (channel->id() < 0) {
1887 int sid;
1888 if (!sid_allocator_.AllocateSid(role, &sid)) {
1889 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1890 continue;
1891 }
1892 channel->SetSctpSid(sid);
1893 }
1894 }
1895}
1896
1897void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08001898 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07001899 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1900 ++it) {
1901 if (it->get() == channel) {
1902 if (channel->id() >= 0) {
1903 sid_allocator_.ReleaseSid(channel->id());
1904 }
deadbeefbd292462015-12-14 18:15:29 -08001905 // Since this method is triggered by a signal from the DataChannel,
1906 // we can't free it directly here; we need to free it asynchronously.
1907 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07001908 sctp_data_channels_.erase(it);
deadbeefbd292462015-12-14 18:15:29 -08001909 signaling_thread()->Post(this, MSG_FREE_DATACHANNELS, nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07001910 return;
1911 }
1912 }
1913}
1914
1915void PeerConnection::OnVoiceChannelDestroyed() {
1916 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1917}
1918
1919void PeerConnection::OnVideoChannelDestroyed() {
1920 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1921}
1922
1923void PeerConnection::OnDataChannelCreated() {
1924 for (const auto& channel : sctp_data_channels_) {
1925 channel->OnTransportChannelCreated();
1926 }
1927}
1928
1929void PeerConnection::OnDataChannelDestroyed() {
1930 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1931 // DataChannel may callback to us and try to modify the list.
1932 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1933 temp_rtp_dcs.swap(rtp_data_channels_);
1934 for (const auto& kv : temp_rtp_dcs) {
1935 kv.second->OnTransportChannelDestroyed();
1936 }
1937
1938 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1939 temp_sctp_dcs.swap(sctp_data_channels_);
1940 for (const auto& channel : temp_sctp_dcs) {
1941 channel->OnTransportChannelDestroyed();
1942 }
1943}
1944
1945void PeerConnection::OnDataChannelOpenMessage(
1946 const std::string& label,
1947 const InternalDataChannelInit& config) {
1948 rtc::scoped_refptr<DataChannel> channel(
1949 InternalCreateDataChannel(label, &config));
1950 if (!channel.get()) {
1951 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1952 return;
1953 }
1954
1955 observer_->OnDataChannel(
1956 DataChannelProxy::Create(signaling_thread(), channel));
1957}
1958
deadbeeffac06552015-11-25 11:26:01 -08001959RtpSenderInterface* PeerConnection::FindSenderById(const std::string& id) {
1960 auto it =
1961 std::find_if(senders_.begin(), senders_.end(),
1962 [id](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1963 return sender->id() == id;
1964 });
1965 return it != senders_.end() ? it->get() : nullptr;
1966}
1967
deadbeef70ab1a12015-09-28 16:53:55 -07001968std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1969PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1970 return std::find_if(
1971 senders_.begin(), senders_.end(),
1972 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1973 return sender->track() == track;
1974 });
1975}
1976
1977std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1978PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1979 return std::find_if(
1980 receivers_.begin(), receivers_.end(),
1981 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1982 return receiver->track() == track;
1983 });
1984}
1985
deadbeefab9b2d12015-10-14 11:33:11 -07001986PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1987 cricket::MediaType media_type) {
1988 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1989 media_type == cricket::MEDIA_TYPE_VIDEO);
1990 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1991 : &remote_video_tracks_;
1992}
1993
1994PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
1995 cricket::MediaType media_type) {
1996 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1997 media_type == cricket::MEDIA_TYPE_VIDEO);
1998 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
1999 : &local_video_tracks_;
2000}
2001
2002const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2003 const PeerConnection::TrackInfos& infos,
2004 const std::string& stream_label,
2005 const std::string track_id) const {
2006 for (const TrackInfo& track_info : infos) {
2007 if (track_info.stream_label == stream_label &&
2008 track_info.track_id == track_id) {
2009 return &track_info;
2010 }
2011 }
2012 return nullptr;
2013}
2014
2015DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2016 for (const auto& channel : sctp_data_channels_) {
2017 if (channel->id() == sid) {
2018 return channel;
2019 }
2020 }
2021 return nullptr;
2022}
2023
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002024} // namespace webrtc