blob: 3c0dc83aa387c21994fb0962308e39c86c9599a5 [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
30#include <vector>
deadbeef0a6c4ca2015-10-06 11:38:28 -070031#include <cctype> // for isdigit
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032
deadbeefab9b2d12015-10-14 11:33:11 -070033#include "talk/app/webrtc/audiotrack.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034#include "talk/app/webrtc/dtmfsender.h"
35#include "talk/app/webrtc/jsepicecandidate.h"
36#include "talk/app/webrtc/jsepsessiondescription.h"
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +000037#include "talk/app/webrtc/mediaconstraintsinterface.h"
deadbeefab9b2d12015-10-14 11:33:11 -070038#include "talk/app/webrtc/mediastream.h"
39#include "talk/app/webrtc/mediastreamproxy.h"
40#include "talk/app/webrtc/mediastreamtrackproxy.h"
41#include "talk/app/webrtc/remoteaudiosource.h"
42#include "talk/app/webrtc/remotevideocapturer.h"
deadbeef70ab1a12015-09-28 16:53:55 -070043#include "talk/app/webrtc/rtpreceiver.h"
44#include "talk/app/webrtc/rtpsender.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045#include "talk/app/webrtc/streamcollection.h"
deadbeefab9b2d12015-10-14 11:33:11 -070046#include "talk/app/webrtc/videosource.h"
47#include "talk/app/webrtc/videotrack.h"
48#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000049#include "webrtc/p2p/client/basicportallocator.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050#include "talk/session/media/channelmanager.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000051#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070053#include "webrtc/base/stringutils.h"
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +000054#include "webrtc/system_wrappers/interface/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
56namespace {
57
deadbeefab9b2d12015-10-14 11:33:11 -070058using webrtc::DataChannel;
59using webrtc::MediaConstraintsInterface;
60using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000061using webrtc::PeerConnectionInterface;
deadbeefab9b2d12015-10-14 11:33:11 -070062using webrtc::StreamCollection;
deadbeef0a6c4ca2015-10-06 11:38:28 -070063using webrtc::StunConfigurations;
64using webrtc::TurnConfigurations;
65typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
66 StunConfiguration;
67typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
68 TurnConfiguration;
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";
wu@webrtc.org91053e72013-08-10 07:18:04 +000083static const char kUdpTransportType[] = "udp";
84static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085
86// NOTE: Must be in the same order as the ServiceType enum.
deadbeef0a6c4ca2015-10-06 11:38:28 -070087static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088
deadbeef0a6c4ca2015-10-06 11:38:28 -070089// NOTE: A loop below assumes that the first value of this enum is 0 and all
90// other values are incremental.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091enum ServiceType {
deadbeef0a6c4ca2015-10-06 11:38:28 -070092 STUN = 0, // Indicates a STUN server.
93 STUNS, // Indicates a STUN server used with a TLS session.
94 TURN, // Indicates a TURN server
95 TURNS, // Indicates a TURN server used with a TLS session.
96 INVALID, // Unknown.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097};
deadbeef0a6c4ca2015-10-06 11:38:28 -070098static_assert(INVALID == ARRAY_SIZE(kValidIceServiceTypes),
99 "kValidIceServiceTypes must have as many strings as ServiceType "
100 "has values.");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101
102enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_GETSTATS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107};
108
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000109struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 explicit SetSessionDescriptionMsg(
111 webrtc::SetSessionDescriptionObserver* observer)
112 : observer(observer) {
113 }
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 std::string error;
117};
118
deadbeefab9b2d12015-10-14 11:33:11 -0700119struct CreateSessionDescriptionMsg : public rtc::MessageData {
120 explicit CreateSessionDescriptionMsg(
121 webrtc::CreateSessionDescriptionObserver* observer)
122 : observer(observer) {}
123
124 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
125 std::string error;
126};
127
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000128struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000129 GetStatsMsg(webrtc::StatsObserver* observer,
130 webrtc::MediaStreamTrackInterface* track)
131 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135};
136
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000137// |in_str| should be of format
138// stunURI = scheme ":" stun-host [ ":" stun-port ]
139// scheme = "stun" / "stuns"
140// stun-host = IP-literal / IPv4address / reg-name
141// stun-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700142//
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000143// draft-petithuguenin-behave-turn-uris-01
144// turnURI = scheme ":" turn-host [ ":" turn-port ]
145// turn-host = username@IP-literal / IPv4address / reg-name
146bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
147 ServiceType* service_type,
148 std::string* hostname) {
Tommi77d444a2015-04-24 15:38:38 +0200149 const std::string::size_type colonpos = in_str.find(':');
deadbeef0a6c4ca2015-10-06 11:38:28 -0700150 if (colonpos == std::string::npos) {
151 LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000152 return false;
153 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700154 if ((colonpos + 1) == in_str.length()) {
155 LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
156 return false;
157 }
158 *service_type = INVALID;
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000159 for (size_t i = 0; i < ARRAY_SIZE(kValidIceServiceTypes); ++i) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700160 if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000161 *service_type = static_cast<ServiceType>(i);
162 break;
163 }
164 }
165 if (*service_type == INVALID) {
166 return false;
167 }
168 *hostname = in_str.substr(colonpos + 1, std::string::npos);
169 return true;
170}
171
deadbeef0a6c4ca2015-10-06 11:38:28 -0700172bool ParsePort(const std::string& in_str, int* port) {
173 // Make sure port only contains digits. FromString doesn't check this.
174 for (const char& c : in_str) {
175 if (!std::isdigit(c)) {
176 return false;
177 }
178 }
179 return rtc::FromString(in_str, port);
180}
181
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000182// This method parses IPv6 and IPv4 literal strings, along with hostnames in
183// standard hostname:port format.
184// Consider following formats as correct.
185// |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700186// |hostname|, |[IPv6 address]|, |IPv4 address|.
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000187bool ParseHostnameAndPortFromString(const std::string& in_str,
188 std::string* host,
189 int* port) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700190 RTC_DCHECK(host->empty());
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000191 if (in_str.at(0) == '[') {
192 std::string::size_type closebracket = in_str.rfind(']');
193 if (closebracket != std::string::npos) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000194 std::string::size_type colonpos = in_str.find(':', closebracket);
195 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700196 if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
197 port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000198 return false;
199 }
200 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700201 *host = in_str.substr(1, closebracket - 1);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000202 } else {
203 return false;
204 }
205 } else {
206 std::string::size_type colonpos = in_str.find(':');
207 if (std::string::npos != colonpos) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700208 if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000209 return false;
210 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700211 *host = in_str.substr(0, colonpos);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000212 } else {
213 *host = in_str;
214 }
215 }
deadbeef0a6c4ca2015-10-06 11:38:28 -0700216 return !host->empty();
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000217}
218
deadbeef0a6c4ca2015-10-06 11:38:28 -0700219// Adds a StunConfiguration or TurnConfiguration to the appropriate list,
220// by parsing |url| and using the username/password in |server|.
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200221bool ParseIceServerUrl(const PeerConnectionInterface::IceServer& server,
222 const std::string& url,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700223 StunConfigurations* stun_config,
224 TurnConfigurations* turn_config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000225 // draft-nandakumar-rtcweb-stun-uri-01
226 // stunURI = scheme ":" stun-host [ ":" stun-port ]
227 // scheme = "stun" / "stuns"
228 // stun-host = IP-literal / IPv4address / reg-name
229 // stun-port = *DIGIT
230
231 // draft-petithuguenin-behave-turn-uris-01
232 // turnURI = scheme ":" turn-host [ ":" turn-port ]
233 // [ "?transport=" transport ]
234 // scheme = "turn" / "turns"
235 // transport = "udp" / "tcp" / transport-ext
236 // transport-ext = 1*unreserved
237 // turn-host = IP-literal / IPv4address / reg-name
238 // turn-port = *DIGIT
deadbeef0a6c4ca2015-10-06 11:38:28 -0700239 RTC_DCHECK(stun_config != nullptr);
240 RTC_DCHECK(turn_config != nullptr);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200241 std::vector<std::string> tokens;
242 std::string turn_transport_type = kUdpTransportType;
deadbeef0a6c4ca2015-10-06 11:38:28 -0700243 RTC_DCHECK(!url.empty());
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200244 rtc::tokenize(url, '?', &tokens);
245 std::string uri_without_transport = tokens[0];
246 // Let's look into transport= param, if it exists.
247 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
248 std::string uri_transport_param = tokens[1];
249 rtc::tokenize(uri_transport_param, '=', &tokens);
250 if (tokens[0] == kTransport) {
251 // As per above grammar transport param will be consist of lower case
252 // letters.
253 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
254 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
deadbeef0a6c4ca2015-10-06 11:38:28 -0700255 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200257 turn_transport_type = tokens[1];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 }
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;
296 turn_transport_type = kTcpTransportType;
297 }
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:
313 stun_config->push_back(StunConfiguration(address, port));
314 break;
315 case TURN:
316 case TURNS: {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200317 bool secure = (service_type == TURNS);
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200318 turn_config->push_back(TurnConfiguration(address, port,
319 username,
320 server.password,
321 turn_transport_type,
322 secure));
323 break;
324 }
325 case INVALID:
326 default:
327 LOG(WARNING) << "Configuration not supported: " << url;
328 return false;
329 }
330 return true;
331}
332
deadbeefab9b2d12015-10-14 11:33:11 -0700333// Check if we can send |new_stream| on a PeerConnection.
334bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
335 webrtc::MediaStreamInterface* new_stream) {
336 if (!new_stream || !current_streams) {
337 return false;
338 }
339 if (current_streams->find(new_stream->label()) != nullptr) {
340 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
341 << " is already added.";
342 return false;
343 }
344 return true;
345}
346
347bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
348 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
349}
350
351bool IsValidOfferToReceiveMedia(int value) {
352 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
353 return (value >= Options::kUndefined) &&
354 (value <= Options::kMaxOfferToReceiveMedia);
355}
356
357// Add the stream and RTP data channel info to |session_options|.
358void SetStreams(cricket::MediaSessionOptions* session_options,
359 rtc::scoped_refptr<StreamCollection> streams,
360 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
361 rtp_data_channels) {
362 session_options->streams.clear();
363 if (streams != nullptr) {
364 for (size_t i = 0; i < streams->count(); ++i) {
365 MediaStreamInterface* stream = streams->at(i);
366 // For each audio track in the stream, add it to the MediaSessionOptions.
367 for (const auto& track : stream->GetAudioTracks()) {
368 session_options->AddSendStream(cricket::MEDIA_TYPE_AUDIO, track->id(),
369 stream->label());
370 }
371 // For each video track in the stream, add it to the MediaSessionOptions.
372 for (const auto& track : stream->GetVideoTracks()) {
373 session_options->AddSendStream(cricket::MEDIA_TYPE_VIDEO, track->id(),
374 stream->label());
375 }
376 }
377 }
378
379 // Check for data channels.
380 for (const auto& kv : rtp_data_channels) {
381 const DataChannel* channel = kv.second;
382 if (channel->state() == DataChannel::kConnecting ||
383 channel->state() == DataChannel::kOpen) {
384 // |streamid| and |sync_label| are both set to the DataChannel label
385 // here so they can be signaled the same way as MediaStreams and Tracks.
386 // For MediaStreams, the sync_label is the MediaStream label and the
387 // track label is the same as |streamid|.
388 const std::string& streamid = channel->label();
389 const std::string& sync_label = channel->label();
390 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
391 sync_label);
392 }
393 }
394}
395
deadbeef0a6c4ca2015-10-06 11:38:28 -0700396} // namespace
397
398namespace webrtc {
399
deadbeefab9b2d12015-10-14 11:33:11 -0700400// Factory class for creating remote MediaStreams and MediaStreamTracks.
401class RemoteMediaStreamFactory {
402 public:
403 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
404 cricket::ChannelManager* channel_manager)
405 : signaling_thread_(signaling_thread),
406 channel_manager_(channel_manager) {}
407
408 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
409 const std::string& stream_label) {
410 return MediaStreamProxy::Create(signaling_thread_,
411 MediaStream::Create(stream_label));
412 }
413
414 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
415 const std::string& track_id) {
416 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
417 stream, track_id, RemoteAudioSource::Create().get());
418 }
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(),
425 nullptr)
426 .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,
433 S* source) {
434 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
456 // According to the spec, offer to receive audio/video if the constraint is
457 // not set and there are send streams.
458 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
459 session_options->recv_audio =
460 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO);
461 } else {
462 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
463 }
464 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
465 session_options->recv_video =
466 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO);
467 } else {
468 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
469 }
470
471 session_options->vad_enabled = rtc_options.voice_activity_detection;
472 session_options->transport_options.ice_restart = rtc_options.ice_restart;
473 session_options->bundle_enabled =
474 rtc_options.use_rtp_mux &&
475 (session_options->has_audio() || session_options->has_video() ||
476 session_options->has_data());
477
478 return true;
479}
480
481bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
482 cricket::MediaSessionOptions* session_options) {
483 bool value = false;
484 size_t mandatory_constraints_satisfied = 0;
485
486 // kOfferToReceiveAudio defaults to true according to spec.
487 if (!FindConstraint(constraints,
488 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
489 &mandatory_constraints_satisfied) ||
490 value) {
491 session_options->recv_audio = true;
492 }
493
494 // kOfferToReceiveVideo defaults to false according to spec. But
495 // if it is an answer and video is offered, we should still accept video
496 // per default.
497 value = false;
498 if (!FindConstraint(constraints,
499 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
500 &mandatory_constraints_satisfied) ||
501 value) {
502 session_options->recv_video = true;
503 }
504
505 if (FindConstraint(constraints,
506 MediaConstraintsInterface::kVoiceActivityDetection, &value,
507 &mandatory_constraints_satisfied)) {
508 session_options->vad_enabled = value;
509 }
510
511 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
512 &mandatory_constraints_satisfied)) {
513 session_options->bundle_enabled = value;
514 } else {
515 // kUseRtpMux defaults to true according to spec.
516 session_options->bundle_enabled = true;
517 }
518 session_options->bundle_enabled =
519 session_options->bundle_enabled &&
520 (session_options->has_audio() || session_options->has_video() ||
521 session_options->has_data());
522
523 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
524 &value, &mandatory_constraints_satisfied)) {
525 session_options->transport_options.ice_restart = value;
526 } else {
527 // kIceRestart defaults to false according to spec.
528 session_options->transport_options.ice_restart = false;
529 }
530
531 if (!constraints) {
532 return true;
533 }
534 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
535}
536
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200537bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700538 StunConfigurations* stun_config,
539 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200540 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
541 if (!server.urls.empty()) {
542 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200543 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700544 LOG(LS_ERROR) << "Empty uri.";
545 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200546 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200547 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
548 return false;
549 }
550 }
551 } else if (!server.uri.empty()) {
552 // Fallback to old .uri if new .urls isn't present.
553 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000554 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200555 }
556 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700557 LOG(LS_ERROR) << "Empty uri.";
558 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000559 }
560 }
561 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() {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700576 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700577 // Need to detach RTP senders/receivers from WebRtcSession,
578 // since it's about to be destroyed.
579 for (const auto& sender : senders_) {
580 sender->Stop();
581 }
582 for (const auto& receiver : receivers_) {
583 receiver->Stop();
584 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585}
586
587bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000588 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000590 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200591 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700593 RTC_DCHECK(observer != nullptr);
594 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000595 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700596 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000597 observer_ = observer;
598
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
600 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000601 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 return false;
603 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000604 port_allocator_.reset(
605 allocator_factory->CreatePortAllocator(stun_config, turn_config));
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000606
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000608 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000609 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700610 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000611 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000612 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000613 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700614 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
615 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000616 if (!value) {
617 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000618 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000619 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000620 "Disabled") {
621 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000622 }
623
Jiayang Liucac1b382015-04-30 12:35:24 -0700624 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
625 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
626 LOG(LS_INFO) << "TCP candidates are disabled.";
627 }
628
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000629 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000630 // No step delay is used while allocating ports.
631 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
632
stefanc1aeaf02015-10-15 07:26:07 -0700633 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000634
stefanc1aeaf02015-10-15 07:26:07 -0700635 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
636 factory_->signaling_thread(), media_controller_->channel_manager()));
637
638 session_.reset(
639 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
640 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700641 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000642
643 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000644 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700645 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000646 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700647 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000648
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000649 // Register PeerConnection as receiver of local ice candidates.
650 // All the callbacks will be posted to the application from PeerConnection.
651 session_->RegisterIceObserver(this);
652 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700653 session_->SignalVoiceChannelDestroyed.connect(
654 this, &PeerConnection::OnVoiceChannelDestroyed);
655 session_->SignalVideoChannelDestroyed.connect(
656 this, &PeerConnection::OnVideoChannelDestroyed);
657 session_->SignalDataChannelCreated.connect(
658 this, &PeerConnection::OnDataChannelCreated);
659 session_->SignalDataChannelDestroyed.connect(
660 this, &PeerConnection::OnDataChannelDestroyed);
661 session_->SignalDataChannelOpenMessage.connect(
662 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663 return true;
664}
665
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000666rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700668 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669}
670
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000671rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700673 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674}
675
deadbeef70ab1a12015-09-28 16:53:55 -0700676// TODO(deadbeef): Create RtpSenders immediately here, even if local
677// description hasn't yet been set.
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000678bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000679 if (IsClosed()) {
680 return false;
681 }
deadbeefab9b2d12015-10-14 11:33:11 -0700682 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683 return false;
684 }
deadbeefab9b2d12015-10-14 11:33:11 -0700685
686 local_streams_->AddStream(local_stream);
687
688 // Find tracks that have already been configured in SDP. This can occur if a
689 // local session description that contains the MSID of these tracks is set
690 // before AddLocalStream is called. It can also occur if the local session
691 // description is not changed and RemoveLocalStream is called and later
692 // AddLocalStream is called again with the same stream.
693 for (const auto& track : local_stream->GetAudioTracks()) {
694 const TrackInfo* track_info =
695 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
696 if (track_info) {
697 CreateAudioSender(local_stream, track.get(), track_info->ssrc);
698 }
699 }
700 for (const auto& track : local_stream->GetVideoTracks()) {
701 const TrackInfo* track_info =
702 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
703 if (track_info) {
704 CreateVideoSender(local_stream, track.get(), track_info->ssrc);
705 }
706 }
707
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000708 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000709 observer_->OnRenegotiationNeeded();
710 return true;
711}
712
deadbeefab9b2d12015-10-14 11:33:11 -0700713// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
714// indefinitely.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000715void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
deadbeefab9b2d12015-10-14 11:33:11 -0700716 for (const auto& track : local_stream->GetAudioTracks()) {
717 const TrackInfo* track_info =
718 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
719 if (track_info) {
720 DestroyAudioSender(local_stream, track.get(), track_info->ssrc);
721 }
722 }
723 for (const auto& track : local_stream->GetVideoTracks()) {
724 const TrackInfo* track_info =
725 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
726 if (track_info) {
727 DestroyVideoSender(local_stream, track.get());
728 }
729 }
730
731 local_streams_->RemoveStream(local_stream);
732
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 if (IsClosed()) {
734 return;
735 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 observer_->OnRenegotiationNeeded();
737}
738
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000739rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740 AudioTrackInterface* track) {
741 if (!track) {
742 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
743 return NULL;
744 }
deadbeefab9b2d12015-10-14 11:33:11 -0700745 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
747 return NULL;
748 }
749
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000750 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000751 DtmfSender::Create(track, signaling_thread(), session_.get()));
752 if (!sender.get()) {
753 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
754 return NULL;
755 }
756 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
757}
758
deadbeef70ab1a12015-09-28 16:53:55 -0700759std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
760 const {
761 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
762 for (const auto& sender : senders_) {
763 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
764 }
765 return senders;
766}
767
768std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
769PeerConnection::GetReceivers() const {
770 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
771 for (const auto& receiver : receivers_) {
772 receivers.push_back(
773 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
774 }
775 return receivers;
776}
777
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000779 MediaStreamTrackInterface* track,
780 StatsOutputLevel level) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700781 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000782 if (!VERIFY(observer != NULL)) {
783 LOG(LS_ERROR) << "GetStats - observer is NULL.";
784 return false;
785 }
786
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000787 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000788 signaling_thread()->Post(this, MSG_GETSTATS,
789 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790 return true;
791}
792
793PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
794 return signaling_state_;
795}
796
797PeerConnectionInterface::IceState PeerConnection::ice_state() {
798 return ice_state_;
799}
800
801PeerConnectionInterface::IceConnectionState
802PeerConnection::ice_connection_state() {
803 return ice_connection_state_;
804}
805
806PeerConnectionInterface::IceGatheringState
807PeerConnection::ice_gathering_state() {
808 return ice_gathering_state_;
809}
810
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000811rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812PeerConnection::CreateDataChannel(
813 const std::string& label,
814 const DataChannelInit* config) {
deadbeefab9b2d12015-10-14 11:33:11 -0700815 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000816
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000817 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000818 if (config) {
819 internal_config.reset(new InternalDataChannelInit(*config));
820 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000821 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700822 InternalCreateDataChannel(label, internal_config.get()));
823 if (!channel.get()) {
824 return nullptr;
825 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000827 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
828 // the first SCTP DataChannel.
829 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
830 observer_->OnRenegotiationNeeded();
831 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000832
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 return DataChannelProxy::Create(signaling_thread(), channel.get());
834}
835
836void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
837 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700838 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
840 return;
841 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000842 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000843
844 bool value;
845 size_t mandatory_constraints = 0;
846
847 if (FindConstraint(constraints,
848 MediaConstraintsInterface::kOfferToReceiveAudio,
849 &value,
850 &mandatory_constraints)) {
851 options.offer_to_receive_audio =
852 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
853 }
854
855 if (FindConstraint(constraints,
856 MediaConstraintsInterface::kOfferToReceiveVideo,
857 &value,
858 &mandatory_constraints)) {
859 options.offer_to_receive_video =
860 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
861 }
862
863 if (FindConstraint(constraints,
864 MediaConstraintsInterface::kVoiceActivityDetection,
865 &value,
866 &mandatory_constraints)) {
867 options.voice_activity_detection = value;
868 }
869
870 if (FindConstraint(constraints,
871 MediaConstraintsInterface::kIceRestart,
872 &value,
873 &mandatory_constraints)) {
874 options.ice_restart = value;
875 }
876
877 if (FindConstraint(constraints,
878 MediaConstraintsInterface::kUseRtpMux,
879 &value,
880 &mandatory_constraints)) {
881 options.use_rtp_mux = value;
882 }
883
884 CreateOffer(observer, options);
885}
886
887void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
888 const RTCOfferAnswerOptions& options) {
deadbeefab9b2d12015-10-14 11:33:11 -0700889 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000890 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
891 return;
892 }
deadbeefab9b2d12015-10-14 11:33:11 -0700893
894 cricket::MediaSessionOptions session_options;
895 if (!GetOptionsForOffer(options, &session_options)) {
896 std::string error = "CreateOffer called with invalid options.";
897 LOG(LS_ERROR) << error;
898 PostCreateSessionDescriptionFailure(observer, error);
899 return;
900 }
901
902 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000903}
904
905void PeerConnection::CreateAnswer(
906 CreateSessionDescriptionObserver* observer,
907 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700908 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
910 return;
911 }
deadbeefab9b2d12015-10-14 11:33:11 -0700912
913 cricket::MediaSessionOptions session_options;
914 if (!GetOptionsForAnswer(constraints, &session_options)) {
915 std::string error = "CreateAnswer called with invalid constraints.";
916 LOG(LS_ERROR) << error;
917 PostCreateSessionDescriptionFailure(observer, error);
918 return;
919 }
920
921 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922}
923
924void PeerConnection::SetLocalDescription(
925 SetSessionDescriptionObserver* observer,
926 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -0700927 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
929 return;
930 }
931 if (!desc) {
932 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
933 return;
934 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 // Update stats here so that we have the most recent stats for tracks and
936 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000937 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 std::string error;
939 if (!session_->SetLocalDescription(desc, &error)) {
940 PostSetSessionDescriptionFailure(observer, error);
941 return;
942 }
deadbeefab9b2d12015-10-14 11:33:11 -0700943
944 // If setting the description decided our SSL role, allocate any necessary
945 // SCTP sids.
946 rtc::SSLRole role;
947 if (session_->data_channel_type() == cricket::DCT_SCTP &&
948 session_->GetSslRole(&role)) {
949 AllocateSctpSids(role);
950 }
951
952 // Update state and SSRC of local MediaStreams and DataChannels based on the
953 // local session description.
954 const cricket::ContentInfo* audio_content =
955 GetFirstAudioContent(desc->description());
956 if (audio_content) {
957 const cricket::AudioContentDescription* audio_desc =
958 static_cast<const cricket::AudioContentDescription*>(
959 audio_content->description);
960 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
961 }
962
963 const cricket::ContentInfo* video_content =
964 GetFirstVideoContent(desc->description());
965 if (video_content) {
966 const cricket::VideoContentDescription* video_desc =
967 static_cast<const cricket::VideoContentDescription*>(
968 video_content->description);
969 UpdateLocalTracks(video_desc->streams(), video_desc->type());
970 }
971
972 const cricket::ContentInfo* data_content =
973 GetFirstDataContent(desc->description());
974 if (data_content) {
975 const cricket::DataContentDescription* data_desc =
976 static_cast<const cricket::DataContentDescription*>(
977 data_content->description);
978 if (rtc::starts_with(data_desc->protocol().data(),
979 cricket::kMediaProtocolRtpPrefix)) {
980 UpdateLocalRtpDataChannels(data_desc->streams());
981 }
982 }
983
984 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700986
deadbeefcbecd352015-09-23 11:50:27 -0700987 // MaybeStartGathering needs to be called after posting
988 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
989 // before signaling that SetLocalDescription completed.
990 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991}
992
993void PeerConnection::SetRemoteDescription(
994 SetSessionDescriptionObserver* observer,
995 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -0700996 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
998 return;
999 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 if (!desc) {
1001 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1002 return;
1003 }
1004 // Update stats here so that we have the most recent stats for tracks and
1005 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001006 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007 std::string error;
1008 if (!session_->SetRemoteDescription(desc, &error)) {
1009 PostSetSessionDescriptionFailure(observer, error);
1010 return;
1011 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012
deadbeefab9b2d12015-10-14 11:33:11 -07001013 // If setting the description decided our SSL role, allocate any necessary
1014 // SCTP sids.
1015 rtc::SSLRole role;
1016 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1017 session_->GetSslRole(&role)) {
1018 AllocateSctpSids(role);
1019 }
1020
1021 const cricket::SessionDescription* remote_desc = desc->description();
1022
1023 // We wait to signal new streams until we finish processing the description,
1024 // since only at that point will new streams have all their tracks.
1025 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1026
1027 // Find all audio rtp streams and create corresponding remote AudioTracks
1028 // and MediaStreams.
1029 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1030 if (audio_content) {
1031 const cricket::AudioContentDescription* desc =
1032 static_cast<const cricket::AudioContentDescription*>(
1033 audio_content->description);
1034 UpdateRemoteStreamsList(desc->streams(), desc->type(), new_streams);
1035 remote_info_.default_audio_track_needed =
1036 MediaContentDirectionHasSend(desc->direction()) &&
1037 desc->streams().empty();
1038 }
1039
1040 // Find all video rtp streams and create corresponding remote VideoTracks
1041 // and MediaStreams.
1042 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1043 if (video_content) {
1044 const cricket::VideoContentDescription* desc =
1045 static_cast<const cricket::VideoContentDescription*>(
1046 video_content->description);
1047 UpdateRemoteStreamsList(desc->streams(), desc->type(), new_streams);
1048 remote_info_.default_video_track_needed =
1049 MediaContentDirectionHasSend(desc->direction()) &&
1050 desc->streams().empty();
1051 }
1052
1053 // Update the DataChannels with the information from the remote peer.
1054 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
1055 if (data_content) {
1056 const cricket::DataContentDescription* data_desc =
1057 static_cast<const cricket::DataContentDescription*>(
1058 data_content->description);
1059 if (rtc::starts_with(data_desc->protocol().data(),
1060 cricket::kMediaProtocolRtpPrefix)) {
1061 UpdateRemoteRtpDataChannels(data_desc->streams());
1062 }
1063 }
1064
1065 // Iterate new_streams and notify the observer about new MediaStreams.
1066 for (size_t i = 0; i < new_streams->count(); ++i) {
1067 MediaStreamInterface* new_stream = new_streams->at(i);
1068 stats_->AddStream(new_stream);
1069 observer_->OnAddStream(new_stream);
1070 }
1071
1072 // Find removed MediaStreams.
1073 if (remote_info_.IsDefaultMediaStreamNeeded() &&
1074 remote_streams_->find(kDefaultStreamLabel) != nullptr) {
1075 // The default media stream already exists. No need to do anything.
1076 } else {
1077 UpdateEndedRemoteMediaStreams();
1078 remote_info_.msid_supported |= remote_streams_->count() > 0;
1079 }
1080 MaybeCreateDefaultStream();
1081
1082 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1083 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001084}
1085
deadbeefa67696b2015-09-29 11:56:26 -07001086bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001087 if (port_allocator_) {
1088 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1089 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1090 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1091 return false;
1092 }
1093
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001094 std::vector<rtc::SocketAddress> stun_hosts;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001095 typedef std::vector<StunConfiguration>::const_iterator StunIt;
1096 for (StunIt stun_it = stuns.begin(); stun_it != stuns.end(); ++stun_it) {
1097 stun_hosts.push_back(stun_it->server);
1098 }
1099
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001100 rtc::SocketAddress stun_addr;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001101 if (!stun_hosts.empty()) {
1102 stun_addr = stun_hosts.front();
deadbeefa67696b2015-09-29 11:56:26 -07001103 LOG(LS_INFO) << "SetConfiguration: StunServer Address: "
1104 << stun_addr.ToString();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001105 }
1106
1107 for (size_t i = 0; i < turns.size(); ++i) {
1108 cricket::RelayCredentials credentials(turns[i].username,
1109 turns[i].password);
1110 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
1111 cricket::ProtocolType protocol;
1112 if (cricket::StringToProto(turns[i].transport_type.c_str(), &protocol)) {
1113 relay_server.ports.push_back(cricket::ProtocolAddress(
1114 turns[i].server, protocol, turns[i].secure));
1115 relay_server.credentials = credentials;
deadbeefa67696b2015-09-29 11:56:26 -07001116 LOG(LS_INFO) << "SetConfiguration: TurnServer Address: "
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001117 << turns[i].server.ToString();
1118 } else {
1119 LOG(LS_WARNING) << "Ignoring TURN server " << turns[i].server << ". "
1120 << "Reason= Incorrect " << turns[i].transport_type
1121 << " transport parameter.";
1122 }
1123 }
1124 }
honghaiz1f429e32015-09-28 07:57:34 -07001125 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001126 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001127}
1128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129bool PeerConnection::AddIceCandidate(
1130 const IceCandidateInterface* ice_candidate) {
1131 return session_->ProcessIceMessage(ice_candidate);
1132}
1133
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001134void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
1135 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001136
1137 if (session_) {
1138 session_->set_metrics_observer(uma_observer_);
1139 }
1140
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001141 // Send information about IPv4/IPv6 status.
1142 if (uma_observer_ && port_allocator_) {
1143 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001144 uma_observer_->IncrementEnumCounter(
1145 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1146 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001147 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001148 uma_observer_->IncrementEnumCounter(
1149 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1150 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001151 }
1152 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001153}
1154
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001155const SessionDescriptionInterface* PeerConnection::local_description() const {
1156 return session_->local_description();
1157}
1158
1159const SessionDescriptionInterface* PeerConnection::remote_description() const {
1160 return session_->remote_description();
1161}
1162
1163void PeerConnection::Close() {
1164 // Update stats here so that we have the most recent stats for tracks and
1165 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001166 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167
deadbeefd59daf82015-10-14 15:02:44 -07001168 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169}
1170
deadbeefd59daf82015-10-14 15:02:44 -07001171void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1172 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001174 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001175 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001176 break;
deadbeefd59daf82015-10-14 15:02:44 -07001177 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1179 break;
deadbeefd59daf82015-10-14 15:02:44 -07001180 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001181 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1182 break;
deadbeefd59daf82015-10-14 15:02:44 -07001183 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001184 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1185 break;
deadbeefd59daf82015-10-14 15:02:44 -07001186 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1188 break;
deadbeefd59daf82015-10-14 15:02:44 -07001189 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190 ChangeSignalingState(PeerConnectionInterface::kStable);
1191 break;
deadbeefd59daf82015-10-14 15:02:44 -07001192 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193 ChangeSignalingState(PeerConnectionInterface::kClosed);
1194 break;
1195 default:
1196 break;
1197 }
1198}
1199
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001200void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1203 SetSessionDescriptionMsg* param =
1204 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1205 param->observer->OnSuccess();
1206 delete param;
1207 break;
1208 }
1209 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1210 SetSessionDescriptionMsg* param =
1211 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1212 param->observer->OnFailure(param->error);
1213 delete param;
1214 break;
1215 }
deadbeefab9b2d12015-10-14 11:33:11 -07001216 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1217 CreateSessionDescriptionMsg* param =
1218 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1219 param->observer->OnFailure(param->error);
1220 delete param;
1221 break;
1222 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223 case MSG_GETSTATS: {
1224 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001225 StatsReports reports;
1226 stats_->GetStats(param->track, &reports);
1227 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 delete param;
1229 break;
1230 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001232 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 break;
1234 }
1235}
1236
deadbeefab9b2d12015-10-14 11:33:11 -07001237void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1238 AudioTrackInterface* audio_track,
1239 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001240 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241}
1242
deadbeefab9b2d12015-10-14 11:33:11 -07001243void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1244 VideoTrackInterface* video_track,
1245 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001246 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247}
1248
deadbeef70ab1a12015-09-28 16:53:55 -07001249// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1250// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001251void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1252 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001253 auto it = FindReceiverForTrack(audio_track);
1254 if (it == receivers_.end()) {
1255 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1256 << " doesn't exist.";
1257 } else {
1258 (*it)->Stop();
1259 receivers_.erase(it);
1260 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261}
1262
deadbeefab9b2d12015-10-14 11:33:11 -07001263void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1264 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001265 auto it = FindReceiverForTrack(video_track);
1266 if (it == receivers_.end()) {
1267 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1268 << " doesn't exist.";
1269 } else {
1270 (*it)->Stop();
1271 receivers_.erase(it);
1272 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273}
deadbeef70ab1a12015-09-28 16:53:55 -07001274
deadbeefab9b2d12015-10-14 11:33:11 -07001275void PeerConnection::CreateAudioSender(MediaStreamInterface* stream,
1276 AudioTrackInterface* audio_track,
1277 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001278 senders_.push_back(new AudioRtpSender(audio_track, ssrc, session_.get()));
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001279 stats_->AddLocalAudioTrack(audio_track, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280}
deadbeef70ab1a12015-09-28 16:53:55 -07001281
deadbeefab9b2d12015-10-14 11:33:11 -07001282void PeerConnection::CreateVideoSender(MediaStreamInterface* stream,
1283 VideoTrackInterface* video_track,
1284 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001285 senders_.push_back(new VideoRtpSender(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286}
1287
deadbeef70ab1a12015-09-28 16:53:55 -07001288// TODO(deadbeef): Keep RtpSenders around even if track goes away in local
1289// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001290void PeerConnection::DestroyAudioSender(MediaStreamInterface* stream,
1291 AudioTrackInterface* audio_track,
1292 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001293 auto it = FindSenderForTrack(audio_track);
1294 if (it == senders_.end()) {
1295 LOG(LS_WARNING) << "RtpSender for track with id " << audio_track->id()
1296 << " doesn't exist.";
1297 return;
1298 } else {
1299 (*it)->Stop();
1300 senders_.erase(it);
1301 }
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001302 stats_->RemoveLocalAudioTrack(audio_track, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303}
1304
deadbeefab9b2d12015-10-14 11:33:11 -07001305void PeerConnection::DestroyVideoSender(MediaStreamInterface* stream,
1306 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001307 auto it = FindSenderForTrack(video_track);
1308 if (it == senders_.end()) {
1309 LOG(LS_WARNING) << "RtpSender for track with id " << video_track->id()
1310 << " doesn't exist.";
1311 return;
1312 } else {
1313 (*it)->Stop();
1314 senders_.erase(it);
1315 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316}
1317
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318void PeerConnection::OnIceConnectionChange(
1319 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001320 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001321 // After transitioning to "closed", ignore any additional states from
1322 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001323 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001324 return;
1325 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001327 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328}
1329
1330void PeerConnection::OnIceGatheringChange(
1331 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001332 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333 if (IsClosed()) {
1334 return;
1335 }
1336 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001337 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338}
1339
1340void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001341 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001342 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343}
1344
1345void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001346 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001347 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348}
1349
Peter Thatcher54360512015-07-08 11:08:35 -07001350void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001351 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001352 observer_->OnIceConnectionReceivingChange(receiving);
1353}
1354
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001355void PeerConnection::ChangeSignalingState(
1356 PeerConnectionInterface::SignalingState signaling_state) {
1357 signaling_state_ = signaling_state;
1358 if (signaling_state == kClosed) {
1359 ice_connection_state_ = kIceConnectionClosed;
1360 observer_->OnIceConnectionChange(ice_connection_state_);
1361 if (ice_gathering_state_ != kIceGatheringComplete) {
1362 ice_gathering_state_ = kIceGatheringComplete;
1363 observer_->OnIceGatheringChange(ice_gathering_state_);
1364 }
1365 }
1366 observer_->OnSignalingChange(signaling_state_);
1367 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1368}
1369
deadbeefab9b2d12015-10-14 11:33:11 -07001370void PeerConnection::PostSetSessionDescriptionFailure(
1371 SetSessionDescriptionObserver* observer,
1372 const std::string& error) {
1373 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1374 msg->error = error;
1375 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1376}
1377
1378void PeerConnection::PostCreateSessionDescriptionFailure(
1379 CreateSessionDescriptionObserver* observer,
1380 const std::string& error) {
1381 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1382 msg->error = error;
1383 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1384}
1385
1386bool PeerConnection::GetOptionsForOffer(
1387 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1388 cricket::MediaSessionOptions* session_options) {
1389 SetStreams(session_options, local_streams_, rtp_data_channels_);
1390
1391 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1392 return false;
1393 }
1394
1395 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1396 session_options->data_channel_type = cricket::DCT_SCTP;
1397 }
1398 return true;
1399}
1400
1401bool PeerConnection::GetOptionsForAnswer(
1402 const MediaConstraintsInterface* constraints,
1403 cricket::MediaSessionOptions* session_options) {
1404 SetStreams(session_options, local_streams_, rtp_data_channels_);
1405 session_options->recv_audio = false;
1406 session_options->recv_video = false;
1407
1408 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1409 return false;
1410 }
1411
1412 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1413 // are not signaled in the SDP so does not go through that path and must be
1414 // handled here.
1415 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1416 session_options->data_channel_type = cricket::DCT_SCTP;
1417 }
1418 return true;
1419}
1420
1421void PeerConnection::UpdateRemoteStreamsList(
1422 const cricket::StreamParamsVec& streams,
1423 cricket::MediaType media_type,
1424 StreamCollection* new_streams) {
1425 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1426
1427 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
1428 // the
1429 // new StreamParam.
1430 auto track_it = current_tracks->begin();
1431 while (track_it != current_tracks->end()) {
1432 const TrackInfo& info = *track_it;
1433 const cricket::StreamParams* params =
1434 cricket::GetStreamBySsrc(streams, info.ssrc);
1435 if (!params || params->id != info.track_id) {
1436 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1437 track_it = current_tracks->erase(track_it);
1438 } else {
1439 ++track_it;
1440 }
1441 }
1442
1443 // Find new and active tracks.
1444 for (const cricket::StreamParams& params : streams) {
1445 // The sync_label is the MediaStream label and the |stream.id| is the
1446 // track id.
1447 const std::string& stream_label = params.sync_label;
1448 const std::string& track_id = params.id;
1449 uint32_t ssrc = params.first_ssrc();
1450
1451 rtc::scoped_refptr<MediaStreamInterface> stream =
1452 remote_streams_->find(stream_label);
1453 if (!stream) {
1454 // This is a new MediaStream. Create a new remote MediaStream.
1455 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1456 remote_streams_->AddStream(stream);
1457 new_streams->AddStream(stream);
1458 }
1459
1460 const TrackInfo* track_info =
1461 FindTrackInfo(*current_tracks, stream_label, track_id);
1462 if (!track_info) {
1463 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1464 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1465 }
1466 }
1467}
1468
1469void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1470 const std::string& track_id,
1471 uint32_t ssrc,
1472 cricket::MediaType media_type) {
1473 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1474
1475 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1476 AudioTrackInterface* audio_track =
1477 remote_stream_factory_->AddAudioTrack(stream, track_id);
1478 CreateAudioReceiver(stream, audio_track, ssrc);
1479 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1480 VideoTrackInterface* video_track =
1481 remote_stream_factory_->AddVideoTrack(stream, track_id);
1482 CreateVideoReceiver(stream, video_track, ssrc);
1483 } else {
1484 RTC_DCHECK(false && "Invalid media type");
1485 }
1486}
1487
1488void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1489 const std::string& track_id,
1490 cricket::MediaType media_type) {
1491 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1492
1493 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1494 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1495 stream->FindAudioTrack(track_id);
1496 if (audio_track) {
1497 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1498 stream->RemoveTrack(audio_track);
1499 DestroyAudioReceiver(stream, audio_track);
1500 }
1501 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1502 rtc::scoped_refptr<VideoTrackInterface> video_track =
1503 stream->FindVideoTrack(track_id);
1504 if (video_track) {
1505 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1506 stream->RemoveTrack(video_track);
1507 DestroyVideoReceiver(stream, video_track);
1508 }
1509 } else {
1510 ASSERT(false && "Invalid media type");
1511 }
1512}
1513
1514void PeerConnection::UpdateEndedRemoteMediaStreams() {
1515 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1516 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1517 MediaStreamInterface* stream = remote_streams_->at(i);
1518 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1519 streams_to_remove.push_back(stream);
1520 }
1521 }
1522
1523 for (const auto& stream : streams_to_remove) {
1524 remote_streams_->RemoveStream(stream);
1525 observer_->OnRemoveStream(stream);
1526 }
1527}
1528
1529void PeerConnection::MaybeCreateDefaultStream() {
1530 if (!remote_info_.IsDefaultMediaStreamNeeded()) {
1531 return;
1532 }
1533
1534 bool default_created = false;
1535
1536 rtc::scoped_refptr<MediaStreamInterface> default_remote_stream =
1537 remote_streams_->find(kDefaultStreamLabel);
1538 if (default_remote_stream == nullptr) {
1539 default_created = true;
1540 default_remote_stream =
1541 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1542 remote_streams_->AddStream(default_remote_stream);
1543 }
1544 if (remote_info_.default_audio_track_needed &&
1545 default_remote_stream->GetAudioTracks().size() == 0) {
1546 remote_audio_tracks_.push_back(
1547 TrackInfo(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0));
1548 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
1549 cricket::MEDIA_TYPE_AUDIO);
1550 }
1551 if (remote_info_.default_video_track_needed &&
1552 default_remote_stream->GetVideoTracks().size() == 0) {
1553 remote_video_tracks_.push_back(
1554 TrackInfo(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0));
1555 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
1556 cricket::MEDIA_TYPE_VIDEO);
1557 }
1558 if (default_created) {
1559 stats_->AddStream(default_remote_stream);
1560 observer_->OnAddStream(default_remote_stream);
1561 }
1562}
1563
1564void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1565 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1566 for (TrackInfos::iterator track_it = current_tracks->begin();
1567 track_it != current_tracks->end(); ++track_it) {
1568 const TrackInfo& info = *track_it;
1569 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1570 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1571 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1572 // There's no guarantee the track is still available, e.g. the track may
1573 // have been removed from the stream by javascript.
1574 if (track) {
1575 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1576 }
1577 }
1578 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1579 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1580 // There's no guarantee the track is still available, e.g. the track may
1581 // have been removed from the stream by javascript.
1582 if (track) {
1583 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1584 }
1585 }
1586 }
1587}
1588
1589void PeerConnection::UpdateLocalTracks(
1590 const std::vector<cricket::StreamParams>& streams,
1591 cricket::MediaType media_type) {
1592 TrackInfos* current_tracks = GetLocalTracks(media_type);
1593
1594 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1595 // don't match the new StreamParam.
1596 TrackInfos::iterator track_it = current_tracks->begin();
1597 while (track_it != current_tracks->end()) {
1598 const TrackInfo& info = *track_it;
1599 const cricket::StreamParams* params =
1600 cricket::GetStreamBySsrc(streams, info.ssrc);
1601 if (!params || params->id != info.track_id ||
1602 params->sync_label != info.stream_label) {
1603 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1604 media_type);
1605 track_it = current_tracks->erase(track_it);
1606 } else {
1607 ++track_it;
1608 }
1609 }
1610
1611 // Find new and active tracks.
1612 for (const cricket::StreamParams& params : streams) {
1613 // The sync_label is the MediaStream label and the |stream.id| is the
1614 // track id.
1615 const std::string& stream_label = params.sync_label;
1616 const std::string& track_id = params.id;
1617 uint32_t ssrc = params.first_ssrc();
1618 const TrackInfo* track_info =
1619 FindTrackInfo(*current_tracks, stream_label, track_id);
1620 if (!track_info) {
1621 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1622 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1623 }
1624 }
1625}
1626
1627void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1628 const std::string& track_id,
1629 uint32_t ssrc,
1630 cricket::MediaType media_type) {
1631 MediaStreamInterface* stream = local_streams_->find(stream_label);
1632 if (!stream) {
1633 LOG(LS_WARNING) << "An unknown local MediaStream with label "
1634 << stream_label << " has been configured.";
1635 return;
1636 }
1637
1638 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1639 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1640 if (!audio_track) {
1641 LOG(LS_WARNING) << "An unknown local AudioTrack with id , " << track_id
1642 << " has been configured.";
1643 return;
1644 }
1645 CreateAudioSender(stream, audio_track, ssrc);
1646 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1647 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1648 if (!video_track) {
1649 LOG(LS_WARNING) << "An unknown local VideoTrack with id , " << track_id
1650 << " has been configured.";
1651 return;
1652 }
1653 CreateVideoSender(stream, video_track, ssrc);
1654 } else {
1655 RTC_DCHECK(false && "Invalid media type");
1656 }
1657}
1658
1659void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1660 const std::string& track_id,
1661 uint32_t ssrc,
1662 cricket::MediaType media_type) {
1663 MediaStreamInterface* stream = local_streams_->find(stream_label);
1664 if (!stream) {
1665 // This is the normal case. I.e., RemoveLocalStream has been called and the
1666 // SessionDescriptions has been renegotiated.
1667 return;
1668 }
1669 // A track has been removed from the SessionDescription but the MediaStream
1670 // is still associated with PeerConnection. This only occurs if the SDP
1671 // doesn't match with the calls to AddLocalStream and RemoveLocalStream.
1672 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1673 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1674 if (!audio_track) {
1675 return;
1676 }
1677 DestroyAudioSender(stream, audio_track, ssrc);
1678 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1679 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1680 if (!video_track) {
1681 return;
1682 }
1683 DestroyVideoSender(stream, video_track);
1684 } else {
1685 RTC_DCHECK(false && "Invalid media type.");
1686 }
1687}
1688
1689void PeerConnection::UpdateLocalRtpDataChannels(
1690 const cricket::StreamParamsVec& streams) {
1691 std::vector<std::string> existing_channels;
1692
1693 // Find new and active data channels.
1694 for (const cricket::StreamParams& params : streams) {
1695 // |it->sync_label| is actually the data channel label. The reason is that
1696 // we use the same naming of data channels as we do for
1697 // MediaStreams and Tracks.
1698 // For MediaStreams, the sync_label is the MediaStream label and the
1699 // track label is the same as |streamid|.
1700 const std::string& channel_label = params.sync_label;
1701 auto data_channel_it = rtp_data_channels_.find(channel_label);
1702 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1703 continue;
1704 }
1705 // Set the SSRC the data channel should use for sending.
1706 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1707 existing_channels.push_back(data_channel_it->first);
1708 }
1709
1710 UpdateClosingRtpDataChannels(existing_channels, true);
1711}
1712
1713void PeerConnection::UpdateRemoteRtpDataChannels(
1714 const cricket::StreamParamsVec& streams) {
1715 std::vector<std::string> existing_channels;
1716
1717 // Find new and active data channels.
1718 for (const cricket::StreamParams& params : streams) {
1719 // The data channel label is either the mslabel or the SSRC if the mslabel
1720 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1721 std::string label = params.sync_label.empty()
1722 ? rtc::ToString(params.first_ssrc())
1723 : params.sync_label;
1724 auto data_channel_it = rtp_data_channels_.find(label);
1725 if (data_channel_it == rtp_data_channels_.end()) {
1726 // This is a new data channel.
1727 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1728 } else {
1729 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1730 }
1731 existing_channels.push_back(label);
1732 }
1733
1734 UpdateClosingRtpDataChannels(existing_channels, false);
1735}
1736
1737void PeerConnection::UpdateClosingRtpDataChannels(
1738 const std::vector<std::string>& active_channels,
1739 bool is_local_update) {
1740 auto it = rtp_data_channels_.begin();
1741 while (it != rtp_data_channels_.end()) {
1742 DataChannel* data_channel = it->second;
1743 if (std::find(active_channels.begin(), active_channels.end(),
1744 data_channel->label()) != active_channels.end()) {
1745 ++it;
1746 continue;
1747 }
1748
1749 if (is_local_update) {
1750 data_channel->SetSendSsrc(0);
1751 } else {
1752 data_channel->RemotePeerRequestClose();
1753 }
1754
1755 if (data_channel->state() == DataChannel::kClosed) {
1756 rtp_data_channels_.erase(it);
1757 it = rtp_data_channels_.begin();
1758 } else {
1759 ++it;
1760 }
1761 }
1762}
1763
1764void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1765 uint32_t remote_ssrc) {
1766 rtc::scoped_refptr<DataChannel> channel(
1767 InternalCreateDataChannel(label, nullptr));
1768 if (!channel.get()) {
1769 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1770 << "CreateDataChannel failed.";
1771 return;
1772 }
1773 channel->SetReceiveSsrc(remote_ssrc);
1774 observer_->OnDataChannel(
1775 DataChannelProxy::Create(signaling_thread(), channel));
1776}
1777
1778rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1779 const std::string& label,
1780 const InternalDataChannelInit* config) {
1781 if (IsClosed()) {
1782 return nullptr;
1783 }
1784 if (session_->data_channel_type() == cricket::DCT_NONE) {
1785 LOG(LS_ERROR)
1786 << "InternalCreateDataChannel: Data is not supported in this call.";
1787 return nullptr;
1788 }
1789 InternalDataChannelInit new_config =
1790 config ? (*config) : InternalDataChannelInit();
1791 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1792 if (new_config.id < 0) {
1793 rtc::SSLRole role;
1794 if (session_->GetSslRole(&role) &&
1795 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1796 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1797 return nullptr;
1798 }
1799 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1800 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1801 << "because the id is already in use or out of range.";
1802 return nullptr;
1803 }
1804 }
1805
1806 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1807 session_.get(), session_->data_channel_type(), label, new_config));
1808 if (!channel) {
1809 sid_allocator_.ReleaseSid(new_config.id);
1810 return nullptr;
1811 }
1812
1813 if (channel->data_channel_type() == cricket::DCT_RTP) {
1814 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1815 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1816 << " already exists.";
1817 return nullptr;
1818 }
1819 rtp_data_channels_[channel->label()] = channel;
1820 } else {
1821 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1822 sctp_data_channels_.push_back(channel);
1823 channel->SignalClosed.connect(this,
1824 &PeerConnection::OnSctpDataChannelClosed);
1825 }
1826
1827 return channel;
1828}
1829
1830bool PeerConnection::HasDataChannels() const {
1831 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1832}
1833
1834void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1835 for (const auto& channel : sctp_data_channels_) {
1836 if (channel->id() < 0) {
1837 int sid;
1838 if (!sid_allocator_.AllocateSid(role, &sid)) {
1839 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1840 continue;
1841 }
1842 channel->SetSctpSid(sid);
1843 }
1844 }
1845}
1846
1847void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1848 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1849 ++it) {
1850 if (it->get() == channel) {
1851 if (channel->id() >= 0) {
1852 sid_allocator_.ReleaseSid(channel->id());
1853 }
1854 sctp_data_channels_.erase(it);
1855 return;
1856 }
1857 }
1858}
1859
1860void PeerConnection::OnVoiceChannelDestroyed() {
1861 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1862}
1863
1864void PeerConnection::OnVideoChannelDestroyed() {
1865 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1866}
1867
1868void PeerConnection::OnDataChannelCreated() {
1869 for (const auto& channel : sctp_data_channels_) {
1870 channel->OnTransportChannelCreated();
1871 }
1872}
1873
1874void PeerConnection::OnDataChannelDestroyed() {
1875 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1876 // DataChannel may callback to us and try to modify the list.
1877 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1878 temp_rtp_dcs.swap(rtp_data_channels_);
1879 for (const auto& kv : temp_rtp_dcs) {
1880 kv.second->OnTransportChannelDestroyed();
1881 }
1882
1883 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1884 temp_sctp_dcs.swap(sctp_data_channels_);
1885 for (const auto& channel : temp_sctp_dcs) {
1886 channel->OnTransportChannelDestroyed();
1887 }
1888}
1889
1890void PeerConnection::OnDataChannelOpenMessage(
1891 const std::string& label,
1892 const InternalDataChannelInit& config) {
1893 rtc::scoped_refptr<DataChannel> channel(
1894 InternalCreateDataChannel(label, &config));
1895 if (!channel.get()) {
1896 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1897 return;
1898 }
1899
1900 observer_->OnDataChannel(
1901 DataChannelProxy::Create(signaling_thread(), channel));
1902}
1903
deadbeef70ab1a12015-09-28 16:53:55 -07001904std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1905PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1906 return std::find_if(
1907 senders_.begin(), senders_.end(),
1908 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1909 return sender->track() == track;
1910 });
1911}
1912
1913std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1914PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1915 return std::find_if(
1916 receivers_.begin(), receivers_.end(),
1917 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1918 return receiver->track() == track;
1919 });
1920}
1921
deadbeefab9b2d12015-10-14 11:33:11 -07001922PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1923 cricket::MediaType media_type) {
1924 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1925 media_type == cricket::MEDIA_TYPE_VIDEO);
1926 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1927 : &remote_video_tracks_;
1928}
1929
1930PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
1931 cricket::MediaType media_type) {
1932 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1933 media_type == cricket::MEDIA_TYPE_VIDEO);
1934 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
1935 : &local_video_tracks_;
1936}
1937
1938const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
1939 const PeerConnection::TrackInfos& infos,
1940 const std::string& stream_label,
1941 const std::string track_id) const {
1942 for (const TrackInfo& track_info : infos) {
1943 if (track_info.stream_label == stream_label &&
1944 track_info.track_id == track_id) {
1945 return &track_info;
1946 }
1947 }
1948 return nullptr;
1949}
1950
1951DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
1952 for (const auto& channel : sctp_data_channels_) {
1953 if (channel->id() == sid) {
1954 return channel;
1955 }
1956 }
1957 return nullptr;
1958}
1959
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960} // namespace webrtc