blob: 3ddb3560de6ac7dff5c89f70442ec2ff94c0d2b3 [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
deadbeef5e97fb52015-10-15 12:49:08 -0700351// If the direction is "recvonly" or "inactive", treat the description
352// as containing no streams.
353// See: https://code.google.com/p/webrtc/issues/detail?id=5054
354std::vector<cricket::StreamParams> GetActiveStreams(
355 const cricket::MediaContentDescription* desc) {
356 return MediaContentDirectionHasSend(desc->direction())
357 ? desc->streams()
358 : std::vector<cricket::StreamParams>();
359}
360
deadbeefab9b2d12015-10-14 11:33:11 -0700361bool IsValidOfferToReceiveMedia(int value) {
362 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
363 return (value >= Options::kUndefined) &&
364 (value <= Options::kMaxOfferToReceiveMedia);
365}
366
367// Add the stream and RTP data channel info to |session_options|.
368void SetStreams(cricket::MediaSessionOptions* session_options,
369 rtc::scoped_refptr<StreamCollection> streams,
370 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
371 rtp_data_channels) {
372 session_options->streams.clear();
373 if (streams != nullptr) {
374 for (size_t i = 0; i < streams->count(); ++i) {
375 MediaStreamInterface* stream = streams->at(i);
376 // For each audio track in the stream, add it to the MediaSessionOptions.
377 for (const auto& track : stream->GetAudioTracks()) {
378 session_options->AddSendStream(cricket::MEDIA_TYPE_AUDIO, track->id(),
379 stream->label());
380 }
381 // For each video track in the stream, add it to the MediaSessionOptions.
382 for (const auto& track : stream->GetVideoTracks()) {
383 session_options->AddSendStream(cricket::MEDIA_TYPE_VIDEO, track->id(),
384 stream->label());
385 }
386 }
387 }
388
389 // Check for data channels.
390 for (const auto& kv : rtp_data_channels) {
391 const DataChannel* channel = kv.second;
392 if (channel->state() == DataChannel::kConnecting ||
393 channel->state() == DataChannel::kOpen) {
394 // |streamid| and |sync_label| are both set to the DataChannel label
395 // here so they can be signaled the same way as MediaStreams and Tracks.
396 // For MediaStreams, the sync_label is the MediaStream label and the
397 // track label is the same as |streamid|.
398 const std::string& streamid = channel->label();
399 const std::string& sync_label = channel->label();
400 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
401 sync_label);
402 }
403 }
404}
405
deadbeef0a6c4ca2015-10-06 11:38:28 -0700406} // namespace
407
408namespace webrtc {
409
deadbeefab9b2d12015-10-14 11:33:11 -0700410// Factory class for creating remote MediaStreams and MediaStreamTracks.
411class RemoteMediaStreamFactory {
412 public:
413 explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
414 cricket::ChannelManager* channel_manager)
415 : signaling_thread_(signaling_thread),
416 channel_manager_(channel_manager) {}
417
418 rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
419 const std::string& stream_label) {
420 return MediaStreamProxy::Create(signaling_thread_,
421 MediaStream::Create(stream_label));
422 }
423
424 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
425 const std::string& track_id) {
426 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
427 stream, track_id, RemoteAudioSource::Create().get());
428 }
429
430 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
431 const std::string& track_id) {
432 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
433 stream, track_id,
434 VideoSource::Create(channel_manager_, new RemoteVideoCapturer(),
435 nullptr)
436 .get());
437 }
438
439 private:
440 template <typename TI, typename T, typename TP, typename S>
441 TI* AddTrack(MediaStreamInterface* stream,
442 const std::string& track_id,
443 S* source) {
444 rtc::scoped_refptr<TI> track(
445 TP::Create(signaling_thread_, T::Create(track_id, source)));
446 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
447 if (stream->AddTrack(track)) {
448 return track;
449 }
450 return nullptr;
451 }
452
453 rtc::Thread* signaling_thread_;
454 cricket::ChannelManager* channel_manager_;
455};
456
457bool ConvertRtcOptionsForOffer(
458 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
459 cricket::MediaSessionOptions* session_options) {
460 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
461 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
462 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
463 return false;
464 }
465
466 // According to the spec, offer to receive audio/video if the constraint is
467 // not set and there are send streams.
468 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
469 session_options->recv_audio =
470 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO);
471 } else {
472 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
473 }
474 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
475 session_options->recv_video =
476 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO);
477 } else {
478 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
479 }
480
481 session_options->vad_enabled = rtc_options.voice_activity_detection;
482 session_options->transport_options.ice_restart = rtc_options.ice_restart;
483 session_options->bundle_enabled =
484 rtc_options.use_rtp_mux &&
485 (session_options->has_audio() || session_options->has_video() ||
486 session_options->has_data());
487
488 return true;
489}
490
491bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
492 cricket::MediaSessionOptions* session_options) {
493 bool value = false;
494 size_t mandatory_constraints_satisfied = 0;
495
496 // kOfferToReceiveAudio defaults to true according to spec.
497 if (!FindConstraint(constraints,
498 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
499 &mandatory_constraints_satisfied) ||
500 value) {
501 session_options->recv_audio = true;
502 }
503
504 // kOfferToReceiveVideo defaults to false according to spec. But
505 // if it is an answer and video is offered, we should still accept video
506 // per default.
507 value = false;
508 if (!FindConstraint(constraints,
509 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
510 &mandatory_constraints_satisfied) ||
511 value) {
512 session_options->recv_video = true;
513 }
514
515 if (FindConstraint(constraints,
516 MediaConstraintsInterface::kVoiceActivityDetection, &value,
517 &mandatory_constraints_satisfied)) {
518 session_options->vad_enabled = value;
519 }
520
521 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
522 &mandatory_constraints_satisfied)) {
523 session_options->bundle_enabled = value;
524 } else {
525 // kUseRtpMux defaults to true according to spec.
526 session_options->bundle_enabled = true;
527 }
528 session_options->bundle_enabled =
529 session_options->bundle_enabled &&
530 (session_options->has_audio() || session_options->has_video() ||
531 session_options->has_data());
532
533 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
534 &value, &mandatory_constraints_satisfied)) {
535 session_options->transport_options.ice_restart = value;
536 } else {
537 // kIceRestart defaults to false according to spec.
538 session_options->transport_options.ice_restart = false;
539 }
540
541 if (!constraints) {
542 return true;
543 }
544 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
545}
546
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200547bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700548 StunConfigurations* stun_config,
549 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200550 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
551 if (!server.urls.empty()) {
552 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200553 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700554 LOG(LS_ERROR) << "Empty uri.";
555 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200556 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200557 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
558 return false;
559 }
560 }
561 } else if (!server.uri.empty()) {
562 // Fallback to old .uri if new .urls isn't present.
563 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000564 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200565 }
566 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700567 LOG(LS_ERROR) << "Empty uri.";
568 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000569 }
570 }
571 return true;
572}
573
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000574PeerConnection::PeerConnection(PeerConnectionFactory* factory)
575 : factory_(factory),
576 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000577 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578 signaling_state_(kStable),
579 ice_state_(kIceNew),
580 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700581 ice_gathering_state_(kIceGatheringNew),
582 local_streams_(StreamCollection::Create()),
583 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000584
585PeerConnection::~PeerConnection() {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700586 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700587 // Need to detach RTP senders/receivers from WebRtcSession,
588 // since it's about to be destroyed.
589 for (const auto& sender : senders_) {
590 sender->Stop();
591 }
592 for (const auto& receiver : receivers_) {
593 receiver->Stop();
594 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595}
596
597bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000598 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000600 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200601 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700603 RTC_DCHECK(observer != nullptr);
604 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000605 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700606 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000607 observer_ = observer;
608
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000609 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
610 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000611 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 return false;
613 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000614 port_allocator_.reset(
615 allocator_factory->CreatePortAllocator(stun_config, turn_config));
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000616
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000617 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000618 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000619 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700620 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000621 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000622 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000623 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700624 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
625 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000626 if (!value) {
627 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000628 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000629 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000630 "Disabled") {
631 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000632 }
633
Jiayang Liucac1b382015-04-30 12:35:24 -0700634 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
635 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
636 LOG(LS_INFO) << "TCP candidates are disabled.";
637 }
638
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000639 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 // No step delay is used while allocating ports.
641 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
642
stefanc1aeaf02015-10-15 07:26:07 -0700643 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644
stefanc1aeaf02015-10-15 07:26:07 -0700645 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
646 factory_->signaling_thread(), media_controller_->channel_manager()));
647
648 session_.reset(
649 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
650 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700651 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000652
653 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000654 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700655 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000656 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700657 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659 // Register PeerConnection as receiver of local ice candidates.
660 // All the callbacks will be posted to the application from PeerConnection.
661 session_->RegisterIceObserver(this);
662 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700663 session_->SignalVoiceChannelDestroyed.connect(
664 this, &PeerConnection::OnVoiceChannelDestroyed);
665 session_->SignalVideoChannelDestroyed.connect(
666 this, &PeerConnection::OnVideoChannelDestroyed);
667 session_->SignalDataChannelCreated.connect(
668 this, &PeerConnection::OnDataChannelCreated);
669 session_->SignalDataChannelDestroyed.connect(
670 this, &PeerConnection::OnDataChannelDestroyed);
671 session_->SignalDataChannelOpenMessage.connect(
672 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 return true;
674}
675
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000676rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700678 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000679}
680
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000681rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700683 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684}
685
deadbeef70ab1a12015-09-28 16:53:55 -0700686// TODO(deadbeef): Create RtpSenders immediately here, even if local
687// description hasn't yet been set.
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000688bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 if (IsClosed()) {
690 return false;
691 }
deadbeefab9b2d12015-10-14 11:33:11 -0700692 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693 return false;
694 }
deadbeefab9b2d12015-10-14 11:33:11 -0700695
696 local_streams_->AddStream(local_stream);
697
698 // Find tracks that have already been configured in SDP. This can occur if a
699 // local session description that contains the MSID of these tracks is set
700 // before AddLocalStream is called. It can also occur if the local session
701 // description is not changed and RemoveLocalStream is called and later
702 // AddLocalStream is called again with the same stream.
703 for (const auto& track : local_stream->GetAudioTracks()) {
704 const TrackInfo* track_info =
705 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
706 if (track_info) {
707 CreateAudioSender(local_stream, track.get(), track_info->ssrc);
708 }
709 }
710 for (const auto& track : local_stream->GetVideoTracks()) {
711 const TrackInfo* track_info =
712 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
713 if (track_info) {
714 CreateVideoSender(local_stream, track.get(), track_info->ssrc);
715 }
716 }
717
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000718 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000719 observer_->OnRenegotiationNeeded();
720 return true;
721}
722
deadbeefab9b2d12015-10-14 11:33:11 -0700723// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
724// indefinitely.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
deadbeefab9b2d12015-10-14 11:33:11 -0700726 for (const auto& track : local_stream->GetAudioTracks()) {
727 const TrackInfo* track_info =
728 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
729 if (track_info) {
730 DestroyAudioSender(local_stream, track.get(), track_info->ssrc);
731 }
732 }
733 for (const auto& track : local_stream->GetVideoTracks()) {
734 const TrackInfo* track_info =
735 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
736 if (track_info) {
737 DestroyVideoSender(local_stream, track.get());
738 }
739 }
740
741 local_streams_->RemoveStream(local_stream);
742
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 if (IsClosed()) {
744 return;
745 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746 observer_->OnRenegotiationNeeded();
747}
748
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000749rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750 AudioTrackInterface* track) {
751 if (!track) {
752 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
753 return NULL;
754 }
deadbeefab9b2d12015-10-14 11:33:11 -0700755 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
757 return NULL;
758 }
759
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000760 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 DtmfSender::Create(track, signaling_thread(), session_.get()));
762 if (!sender.get()) {
763 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
764 return NULL;
765 }
766 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
767}
768
deadbeef70ab1a12015-09-28 16:53:55 -0700769std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
770 const {
771 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
772 for (const auto& sender : senders_) {
773 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
774 }
775 return senders;
776}
777
778std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
779PeerConnection::GetReceivers() const {
780 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
781 for (const auto& receiver : receivers_) {
782 receivers.push_back(
783 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
784 }
785 return receivers;
786}
787
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000788bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000789 MediaStreamTrackInterface* track,
790 StatsOutputLevel level) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700791 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000792 if (!VERIFY(observer != NULL)) {
793 LOG(LS_ERROR) << "GetStats - observer is NULL.";
794 return false;
795 }
796
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000797 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000798 signaling_thread()->Post(this, MSG_GETSTATS,
799 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800 return true;
801}
802
803PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
804 return signaling_state_;
805}
806
807PeerConnectionInterface::IceState PeerConnection::ice_state() {
808 return ice_state_;
809}
810
811PeerConnectionInterface::IceConnectionState
812PeerConnection::ice_connection_state() {
813 return ice_connection_state_;
814}
815
816PeerConnectionInterface::IceGatheringState
817PeerConnection::ice_gathering_state() {
818 return ice_gathering_state_;
819}
820
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000821rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822PeerConnection::CreateDataChannel(
823 const std::string& label,
824 const DataChannelInit* config) {
deadbeefab9b2d12015-10-14 11:33:11 -0700825 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000826
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000827 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000828 if (config) {
829 internal_config.reset(new InternalDataChannelInit(*config));
830 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000831 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700832 InternalCreateDataChannel(label, internal_config.get()));
833 if (!channel.get()) {
834 return nullptr;
835 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000836
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000837 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
838 // the first SCTP DataChannel.
839 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
840 observer_->OnRenegotiationNeeded();
841 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000842
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 return DataChannelProxy::Create(signaling_thread(), channel.get());
844}
845
846void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
847 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700848 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
850 return;
851 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000852 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000853
854 bool value;
855 size_t mandatory_constraints = 0;
856
857 if (FindConstraint(constraints,
858 MediaConstraintsInterface::kOfferToReceiveAudio,
859 &value,
860 &mandatory_constraints)) {
861 options.offer_to_receive_audio =
862 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
863 }
864
865 if (FindConstraint(constraints,
866 MediaConstraintsInterface::kOfferToReceiveVideo,
867 &value,
868 &mandatory_constraints)) {
869 options.offer_to_receive_video =
870 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
871 }
872
873 if (FindConstraint(constraints,
874 MediaConstraintsInterface::kVoiceActivityDetection,
875 &value,
876 &mandatory_constraints)) {
877 options.voice_activity_detection = value;
878 }
879
880 if (FindConstraint(constraints,
881 MediaConstraintsInterface::kIceRestart,
882 &value,
883 &mandatory_constraints)) {
884 options.ice_restart = value;
885 }
886
887 if (FindConstraint(constraints,
888 MediaConstraintsInterface::kUseRtpMux,
889 &value,
890 &mandatory_constraints)) {
891 options.use_rtp_mux = value;
892 }
893
894 CreateOffer(observer, options);
895}
896
897void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
898 const RTCOfferAnswerOptions& options) {
deadbeefab9b2d12015-10-14 11:33:11 -0700899 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000900 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
901 return;
902 }
deadbeefab9b2d12015-10-14 11:33:11 -0700903
904 cricket::MediaSessionOptions session_options;
905 if (!GetOptionsForOffer(options, &session_options)) {
906 std::string error = "CreateOffer called with invalid options.";
907 LOG(LS_ERROR) << error;
908 PostCreateSessionDescriptionFailure(observer, error);
909 return;
910 }
911
912 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913}
914
915void PeerConnection::CreateAnswer(
916 CreateSessionDescriptionObserver* observer,
917 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700918 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
920 return;
921 }
deadbeefab9b2d12015-10-14 11:33:11 -0700922
923 cricket::MediaSessionOptions session_options;
924 if (!GetOptionsForAnswer(constraints, &session_options)) {
925 std::string error = "CreateAnswer called with invalid constraints.";
926 LOG(LS_ERROR) << error;
927 PostCreateSessionDescriptionFailure(observer, error);
928 return;
929 }
930
931 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932}
933
934void PeerConnection::SetLocalDescription(
935 SetSessionDescriptionObserver* observer,
936 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -0700937 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
939 return;
940 }
941 if (!desc) {
942 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
943 return;
944 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 // Update stats here so that we have the most recent stats for tracks and
946 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000947 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948 std::string error;
949 if (!session_->SetLocalDescription(desc, &error)) {
950 PostSetSessionDescriptionFailure(observer, error);
951 return;
952 }
deadbeefab9b2d12015-10-14 11:33:11 -0700953
954 // If setting the description decided our SSL role, allocate any necessary
955 // SCTP sids.
956 rtc::SSLRole role;
957 if (session_->data_channel_type() == cricket::DCT_SCTP &&
958 session_->GetSslRole(&role)) {
959 AllocateSctpSids(role);
960 }
961
962 // Update state and SSRC of local MediaStreams and DataChannels based on the
963 // local session description.
964 const cricket::ContentInfo* audio_content =
965 GetFirstAudioContent(desc->description());
966 if (audio_content) {
967 const cricket::AudioContentDescription* audio_desc =
968 static_cast<const cricket::AudioContentDescription*>(
969 audio_content->description);
970 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
971 }
972
973 const cricket::ContentInfo* video_content =
974 GetFirstVideoContent(desc->description());
975 if (video_content) {
976 const cricket::VideoContentDescription* video_desc =
977 static_cast<const cricket::VideoContentDescription*>(
978 video_content->description);
979 UpdateLocalTracks(video_desc->streams(), video_desc->type());
980 }
981
982 const cricket::ContentInfo* data_content =
983 GetFirstDataContent(desc->description());
984 if (data_content) {
985 const cricket::DataContentDescription* data_desc =
986 static_cast<const cricket::DataContentDescription*>(
987 data_content->description);
988 if (rtc::starts_with(data_desc->protocol().data(),
989 cricket::kMediaProtocolRtpPrefix)) {
990 UpdateLocalRtpDataChannels(data_desc->streams());
991 }
992 }
993
994 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700996
deadbeefcbecd352015-09-23 11:50:27 -0700997 // MaybeStartGathering needs to be called after posting
998 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
999 // before signaling that SetLocalDescription completed.
1000 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001}
1002
1003void PeerConnection::SetRemoteDescription(
1004 SetSessionDescriptionObserver* observer,
1005 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -07001006 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1008 return;
1009 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 if (!desc) {
1011 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1012 return;
1013 }
1014 // Update stats here so that we have the most recent stats for tracks and
1015 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001016 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017 std::string error;
1018 if (!session_->SetRemoteDescription(desc, &error)) {
1019 PostSetSessionDescriptionFailure(observer, error);
1020 return;
1021 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022
deadbeefab9b2d12015-10-14 11:33:11 -07001023 // If setting the description decided our SSL role, allocate any necessary
1024 // SCTP sids.
1025 rtc::SSLRole role;
1026 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1027 session_->GetSslRole(&role)) {
1028 AllocateSctpSids(role);
1029 }
1030
1031 const cricket::SessionDescription* remote_desc = desc->description();
1032
1033 // We wait to signal new streams until we finish processing the description,
1034 // since only at that point will new streams have all their tracks.
1035 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1036
1037 // Find all audio rtp streams and create corresponding remote AudioTracks
1038 // and MediaStreams.
1039 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1040 if (audio_content) {
1041 const cricket::AudioContentDescription* desc =
1042 static_cast<const cricket::AudioContentDescription*>(
1043 audio_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001044 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(), new_streams);
deadbeefab9b2d12015-10-14 11:33:11 -07001045 remote_info_.default_audio_track_needed =
1046 MediaContentDirectionHasSend(desc->direction()) &&
1047 desc->streams().empty();
1048 }
1049
1050 // Find all video rtp streams and create corresponding remote VideoTracks
1051 // and MediaStreams.
1052 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1053 if (video_content) {
1054 const cricket::VideoContentDescription* desc =
1055 static_cast<const cricket::VideoContentDescription*>(
1056 video_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001057 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(), new_streams);
deadbeefab9b2d12015-10-14 11:33:11 -07001058 remote_info_.default_video_track_needed =
1059 MediaContentDirectionHasSend(desc->direction()) &&
1060 desc->streams().empty();
1061 }
1062
1063 // Update the DataChannels with the information from the remote peer.
1064 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
1065 if (data_content) {
deadbeef5e97fb52015-10-15 12:49:08 -07001066 const cricket::DataContentDescription* desc =
deadbeefab9b2d12015-10-14 11:33:11 -07001067 static_cast<const cricket::DataContentDescription*>(
1068 data_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001069 if (rtc::starts_with(desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001070 cricket::kMediaProtocolRtpPrefix)) {
deadbeef5e97fb52015-10-15 12:49:08 -07001071 UpdateRemoteRtpDataChannels(GetActiveStreams(desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001072 }
1073 }
1074
1075 // Iterate new_streams and notify the observer about new MediaStreams.
1076 for (size_t i = 0; i < new_streams->count(); ++i) {
1077 MediaStreamInterface* new_stream = new_streams->at(i);
1078 stats_->AddStream(new_stream);
1079 observer_->OnAddStream(new_stream);
1080 }
1081
1082 // Find removed MediaStreams.
1083 if (remote_info_.IsDefaultMediaStreamNeeded() &&
1084 remote_streams_->find(kDefaultStreamLabel) != nullptr) {
1085 // The default media stream already exists. No need to do anything.
1086 } else {
1087 UpdateEndedRemoteMediaStreams();
1088 remote_info_.msid_supported |= remote_streams_->count() > 0;
1089 }
1090 MaybeCreateDefaultStream();
1091
1092 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1093 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001094}
1095
deadbeefa67696b2015-09-29 11:56:26 -07001096bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001097 if (port_allocator_) {
1098 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1099 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1100 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1101 return false;
1102 }
1103
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001104 std::vector<rtc::SocketAddress> stun_hosts;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001105 typedef std::vector<StunConfiguration>::const_iterator StunIt;
1106 for (StunIt stun_it = stuns.begin(); stun_it != stuns.end(); ++stun_it) {
1107 stun_hosts.push_back(stun_it->server);
1108 }
1109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001110 rtc::SocketAddress stun_addr;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001111 if (!stun_hosts.empty()) {
1112 stun_addr = stun_hosts.front();
deadbeefa67696b2015-09-29 11:56:26 -07001113 LOG(LS_INFO) << "SetConfiguration: StunServer Address: "
1114 << stun_addr.ToString();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001115 }
1116
1117 for (size_t i = 0; i < turns.size(); ++i) {
1118 cricket::RelayCredentials credentials(turns[i].username,
1119 turns[i].password);
1120 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
1121 cricket::ProtocolType protocol;
1122 if (cricket::StringToProto(turns[i].transport_type.c_str(), &protocol)) {
1123 relay_server.ports.push_back(cricket::ProtocolAddress(
1124 turns[i].server, protocol, turns[i].secure));
1125 relay_server.credentials = credentials;
deadbeefa67696b2015-09-29 11:56:26 -07001126 LOG(LS_INFO) << "SetConfiguration: TurnServer Address: "
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001127 << turns[i].server.ToString();
1128 } else {
1129 LOG(LS_WARNING) << "Ignoring TURN server " << turns[i].server << ". "
1130 << "Reason= Incorrect " << turns[i].transport_type
1131 << " transport parameter.";
1132 }
1133 }
1134 }
honghaiz1f429e32015-09-28 07:57:34 -07001135 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001136 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001137}
1138
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001139bool PeerConnection::AddIceCandidate(
1140 const IceCandidateInterface* ice_candidate) {
1141 return session_->ProcessIceMessage(ice_candidate);
1142}
1143
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001144void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
1145 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001146
1147 if (session_) {
1148 session_->set_metrics_observer(uma_observer_);
1149 }
1150
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001151 // Send information about IPv4/IPv6 status.
1152 if (uma_observer_ && port_allocator_) {
1153 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001154 uma_observer_->IncrementEnumCounter(
1155 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1156 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001157 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001158 uma_observer_->IncrementEnumCounter(
1159 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1160 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001161 }
1162 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001163}
1164
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165const SessionDescriptionInterface* PeerConnection::local_description() const {
1166 return session_->local_description();
1167}
1168
1169const SessionDescriptionInterface* PeerConnection::remote_description() const {
1170 return session_->remote_description();
1171}
1172
1173void PeerConnection::Close() {
1174 // Update stats here so that we have the most recent stats for tracks and
1175 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001176 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001177
deadbeefd59daf82015-10-14 15:02:44 -07001178 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001179}
1180
deadbeefd59daf82015-10-14 15:02:44 -07001181void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1182 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001184 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001186 break;
deadbeefd59daf82015-10-14 15:02:44 -07001187 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1189 break;
deadbeefd59daf82015-10-14 15:02:44 -07001190 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1192 break;
deadbeefd59daf82015-10-14 15:02:44 -07001193 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1195 break;
deadbeefd59daf82015-10-14 15:02:44 -07001196 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1198 break;
deadbeefd59daf82015-10-14 15:02:44 -07001199 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200 ChangeSignalingState(PeerConnectionInterface::kStable);
1201 break;
deadbeefd59daf82015-10-14 15:02:44 -07001202 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203 ChangeSignalingState(PeerConnectionInterface::kClosed);
1204 break;
1205 default:
1206 break;
1207 }
1208}
1209
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001210void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1213 SetSessionDescriptionMsg* param =
1214 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1215 param->observer->OnSuccess();
1216 delete param;
1217 break;
1218 }
1219 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1220 SetSessionDescriptionMsg* param =
1221 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1222 param->observer->OnFailure(param->error);
1223 delete param;
1224 break;
1225 }
deadbeefab9b2d12015-10-14 11:33:11 -07001226 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1227 CreateSessionDescriptionMsg* param =
1228 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1229 param->observer->OnFailure(param->error);
1230 delete param;
1231 break;
1232 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 case MSG_GETSTATS: {
1234 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001235 StatsReports reports;
1236 stats_->GetStats(param->track, &reports);
1237 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001238 delete param;
1239 break;
1240 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001241 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001242 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001243 break;
1244 }
1245}
1246
deadbeefab9b2d12015-10-14 11:33:11 -07001247void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1248 AudioTrackInterface* audio_track,
1249 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001250 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001251}
1252
deadbeefab9b2d12015-10-14 11:33:11 -07001253void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1254 VideoTrackInterface* video_track,
1255 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001256 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001257}
1258
deadbeef70ab1a12015-09-28 16:53:55 -07001259// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1260// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001261void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1262 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001263 auto it = FindReceiverForTrack(audio_track);
1264 if (it == receivers_.end()) {
1265 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1266 << " doesn't exist.";
1267 } else {
1268 (*it)->Stop();
1269 receivers_.erase(it);
1270 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271}
1272
deadbeefab9b2d12015-10-14 11:33:11 -07001273void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1274 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001275 auto it = FindReceiverForTrack(video_track);
1276 if (it == receivers_.end()) {
1277 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1278 << " doesn't exist.";
1279 } else {
1280 (*it)->Stop();
1281 receivers_.erase(it);
1282 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283}
deadbeef70ab1a12015-09-28 16:53:55 -07001284
deadbeefab9b2d12015-10-14 11:33:11 -07001285void PeerConnection::CreateAudioSender(MediaStreamInterface* stream,
1286 AudioTrackInterface* audio_track,
1287 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001288 senders_.push_back(new AudioRtpSender(audio_track, ssrc, session_.get()));
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001289 stats_->AddLocalAudioTrack(audio_track, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290}
deadbeef70ab1a12015-09-28 16:53:55 -07001291
deadbeefab9b2d12015-10-14 11:33:11 -07001292void PeerConnection::CreateVideoSender(MediaStreamInterface* stream,
1293 VideoTrackInterface* video_track,
1294 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001295 senders_.push_back(new VideoRtpSender(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296}
1297
deadbeef70ab1a12015-09-28 16:53:55 -07001298// TODO(deadbeef): Keep RtpSenders around even if track goes away in local
1299// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001300void PeerConnection::DestroyAudioSender(MediaStreamInterface* stream,
1301 AudioTrackInterface* audio_track,
1302 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001303 auto it = FindSenderForTrack(audio_track);
1304 if (it == senders_.end()) {
1305 LOG(LS_WARNING) << "RtpSender for track with id " << audio_track->id()
1306 << " doesn't exist.";
1307 return;
1308 } else {
1309 (*it)->Stop();
1310 senders_.erase(it);
1311 }
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001312 stats_->RemoveLocalAudioTrack(audio_track, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313}
1314
deadbeefab9b2d12015-10-14 11:33:11 -07001315void PeerConnection::DestroyVideoSender(MediaStreamInterface* stream,
1316 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001317 auto it = FindSenderForTrack(video_track);
1318 if (it == senders_.end()) {
1319 LOG(LS_WARNING) << "RtpSender for track with id " << video_track->id()
1320 << " doesn't exist.";
1321 return;
1322 } else {
1323 (*it)->Stop();
1324 senders_.erase(it);
1325 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326}
1327
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328void PeerConnection::OnIceConnectionChange(
1329 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001330 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001331 // After transitioning to "closed", ignore any additional states from
1332 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001333 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001334 return;
1335 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001336 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001337 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338}
1339
1340void PeerConnection::OnIceGatheringChange(
1341 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001342 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 if (IsClosed()) {
1344 return;
1345 }
1346 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001347 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348}
1349
1350void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001351 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001352 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353}
1354
1355void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001356 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001357 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358}
1359
Peter Thatcher54360512015-07-08 11:08:35 -07001360void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001361 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001362 observer_->OnIceConnectionReceivingChange(receiving);
1363}
1364
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365void PeerConnection::ChangeSignalingState(
1366 PeerConnectionInterface::SignalingState signaling_state) {
1367 signaling_state_ = signaling_state;
1368 if (signaling_state == kClosed) {
1369 ice_connection_state_ = kIceConnectionClosed;
1370 observer_->OnIceConnectionChange(ice_connection_state_);
1371 if (ice_gathering_state_ != kIceGatheringComplete) {
1372 ice_gathering_state_ = kIceGatheringComplete;
1373 observer_->OnIceGatheringChange(ice_gathering_state_);
1374 }
1375 }
1376 observer_->OnSignalingChange(signaling_state_);
1377 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1378}
1379
deadbeefab9b2d12015-10-14 11:33:11 -07001380void PeerConnection::PostSetSessionDescriptionFailure(
1381 SetSessionDescriptionObserver* observer,
1382 const std::string& error) {
1383 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1384 msg->error = error;
1385 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1386}
1387
1388void PeerConnection::PostCreateSessionDescriptionFailure(
1389 CreateSessionDescriptionObserver* observer,
1390 const std::string& error) {
1391 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1392 msg->error = error;
1393 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1394}
1395
1396bool PeerConnection::GetOptionsForOffer(
1397 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1398 cricket::MediaSessionOptions* session_options) {
1399 SetStreams(session_options, local_streams_, rtp_data_channels_);
1400
1401 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1402 return false;
1403 }
1404
1405 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1406 session_options->data_channel_type = cricket::DCT_SCTP;
1407 }
1408 return true;
1409}
1410
1411bool PeerConnection::GetOptionsForAnswer(
1412 const MediaConstraintsInterface* constraints,
1413 cricket::MediaSessionOptions* session_options) {
1414 SetStreams(session_options, local_streams_, rtp_data_channels_);
1415 session_options->recv_audio = false;
1416 session_options->recv_video = false;
1417
1418 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1419 return false;
1420 }
1421
1422 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1423 // are not signaled in the SDP so does not go through that path and must be
1424 // handled here.
1425 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1426 session_options->data_channel_type = cricket::DCT_SCTP;
1427 }
1428 return true;
1429}
1430
1431void PeerConnection::UpdateRemoteStreamsList(
1432 const cricket::StreamParamsVec& streams,
1433 cricket::MediaType media_type,
1434 StreamCollection* new_streams) {
1435 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1436
1437 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
1438 // the
1439 // new StreamParam.
1440 auto track_it = current_tracks->begin();
1441 while (track_it != current_tracks->end()) {
1442 const TrackInfo& info = *track_it;
1443 const cricket::StreamParams* params =
1444 cricket::GetStreamBySsrc(streams, info.ssrc);
1445 if (!params || params->id != info.track_id) {
1446 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1447 track_it = current_tracks->erase(track_it);
1448 } else {
1449 ++track_it;
1450 }
1451 }
1452
1453 // Find new and active tracks.
1454 for (const cricket::StreamParams& params : streams) {
1455 // The sync_label is the MediaStream label and the |stream.id| is the
1456 // track id.
1457 const std::string& stream_label = params.sync_label;
1458 const std::string& track_id = params.id;
1459 uint32_t ssrc = params.first_ssrc();
1460
1461 rtc::scoped_refptr<MediaStreamInterface> stream =
1462 remote_streams_->find(stream_label);
1463 if (!stream) {
1464 // This is a new MediaStream. Create a new remote MediaStream.
1465 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1466 remote_streams_->AddStream(stream);
1467 new_streams->AddStream(stream);
1468 }
1469
1470 const TrackInfo* track_info =
1471 FindTrackInfo(*current_tracks, stream_label, track_id);
1472 if (!track_info) {
1473 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1474 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1475 }
1476 }
1477}
1478
1479void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1480 const std::string& track_id,
1481 uint32_t ssrc,
1482 cricket::MediaType media_type) {
1483 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1484
1485 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1486 AudioTrackInterface* audio_track =
1487 remote_stream_factory_->AddAudioTrack(stream, track_id);
1488 CreateAudioReceiver(stream, audio_track, ssrc);
1489 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1490 VideoTrackInterface* video_track =
1491 remote_stream_factory_->AddVideoTrack(stream, track_id);
1492 CreateVideoReceiver(stream, video_track, ssrc);
1493 } else {
1494 RTC_DCHECK(false && "Invalid media type");
1495 }
1496}
1497
1498void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1499 const std::string& track_id,
1500 cricket::MediaType media_type) {
1501 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1502
1503 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1504 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1505 stream->FindAudioTrack(track_id);
1506 if (audio_track) {
1507 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1508 stream->RemoveTrack(audio_track);
1509 DestroyAudioReceiver(stream, audio_track);
1510 }
1511 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1512 rtc::scoped_refptr<VideoTrackInterface> video_track =
1513 stream->FindVideoTrack(track_id);
1514 if (video_track) {
1515 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1516 stream->RemoveTrack(video_track);
1517 DestroyVideoReceiver(stream, video_track);
1518 }
1519 } else {
1520 ASSERT(false && "Invalid media type");
1521 }
1522}
1523
1524void PeerConnection::UpdateEndedRemoteMediaStreams() {
1525 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1526 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1527 MediaStreamInterface* stream = remote_streams_->at(i);
1528 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1529 streams_to_remove.push_back(stream);
1530 }
1531 }
1532
1533 for (const auto& stream : streams_to_remove) {
1534 remote_streams_->RemoveStream(stream);
1535 observer_->OnRemoveStream(stream);
1536 }
1537}
1538
1539void PeerConnection::MaybeCreateDefaultStream() {
1540 if (!remote_info_.IsDefaultMediaStreamNeeded()) {
1541 return;
1542 }
1543
1544 bool default_created = false;
1545
1546 rtc::scoped_refptr<MediaStreamInterface> default_remote_stream =
1547 remote_streams_->find(kDefaultStreamLabel);
1548 if (default_remote_stream == nullptr) {
1549 default_created = true;
1550 default_remote_stream =
1551 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1552 remote_streams_->AddStream(default_remote_stream);
1553 }
1554 if (remote_info_.default_audio_track_needed &&
1555 default_remote_stream->GetAudioTracks().size() == 0) {
1556 remote_audio_tracks_.push_back(
1557 TrackInfo(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0));
1558 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
1559 cricket::MEDIA_TYPE_AUDIO);
1560 }
1561 if (remote_info_.default_video_track_needed &&
1562 default_remote_stream->GetVideoTracks().size() == 0) {
1563 remote_video_tracks_.push_back(
1564 TrackInfo(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0));
1565 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
1566 cricket::MEDIA_TYPE_VIDEO);
1567 }
1568 if (default_created) {
1569 stats_->AddStream(default_remote_stream);
1570 observer_->OnAddStream(default_remote_stream);
1571 }
1572}
1573
1574void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1575 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1576 for (TrackInfos::iterator track_it = current_tracks->begin();
1577 track_it != current_tracks->end(); ++track_it) {
1578 const TrackInfo& info = *track_it;
1579 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1580 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1581 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1582 // There's no guarantee the track is still available, e.g. the track may
1583 // have been removed from the stream by javascript.
1584 if (track) {
1585 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1586 }
1587 }
1588 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1589 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1590 // There's no guarantee the track is still available, e.g. the track may
1591 // have been removed from the stream by javascript.
1592 if (track) {
1593 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1594 }
1595 }
1596 }
1597}
1598
1599void PeerConnection::UpdateLocalTracks(
1600 const std::vector<cricket::StreamParams>& streams,
1601 cricket::MediaType media_type) {
1602 TrackInfos* current_tracks = GetLocalTracks(media_type);
1603
1604 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1605 // don't match the new StreamParam.
1606 TrackInfos::iterator track_it = current_tracks->begin();
1607 while (track_it != current_tracks->end()) {
1608 const TrackInfo& info = *track_it;
1609 const cricket::StreamParams* params =
1610 cricket::GetStreamBySsrc(streams, info.ssrc);
1611 if (!params || params->id != info.track_id ||
1612 params->sync_label != info.stream_label) {
1613 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1614 media_type);
1615 track_it = current_tracks->erase(track_it);
1616 } else {
1617 ++track_it;
1618 }
1619 }
1620
1621 // Find new and active tracks.
1622 for (const cricket::StreamParams& params : streams) {
1623 // The sync_label is the MediaStream label and the |stream.id| is the
1624 // track id.
1625 const std::string& stream_label = params.sync_label;
1626 const std::string& track_id = params.id;
1627 uint32_t ssrc = params.first_ssrc();
1628 const TrackInfo* track_info =
1629 FindTrackInfo(*current_tracks, stream_label, track_id);
1630 if (!track_info) {
1631 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1632 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1633 }
1634 }
1635}
1636
1637void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1638 const std::string& track_id,
1639 uint32_t ssrc,
1640 cricket::MediaType media_type) {
1641 MediaStreamInterface* stream = local_streams_->find(stream_label);
1642 if (!stream) {
1643 LOG(LS_WARNING) << "An unknown local MediaStream with label "
1644 << stream_label << " has been configured.";
1645 return;
1646 }
1647
1648 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1649 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1650 if (!audio_track) {
1651 LOG(LS_WARNING) << "An unknown local AudioTrack with id , " << track_id
1652 << " has been configured.";
1653 return;
1654 }
1655 CreateAudioSender(stream, audio_track, ssrc);
1656 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1657 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1658 if (!video_track) {
1659 LOG(LS_WARNING) << "An unknown local VideoTrack with id , " << track_id
1660 << " has been configured.";
1661 return;
1662 }
1663 CreateVideoSender(stream, video_track, ssrc);
1664 } else {
1665 RTC_DCHECK(false && "Invalid media type");
1666 }
1667}
1668
1669void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1670 const std::string& track_id,
1671 uint32_t ssrc,
1672 cricket::MediaType media_type) {
1673 MediaStreamInterface* stream = local_streams_->find(stream_label);
1674 if (!stream) {
1675 // This is the normal case. I.e., RemoveLocalStream has been called and the
1676 // SessionDescriptions has been renegotiated.
1677 return;
1678 }
1679 // A track has been removed from the SessionDescription but the MediaStream
1680 // is still associated with PeerConnection. This only occurs if the SDP
1681 // doesn't match with the calls to AddLocalStream and RemoveLocalStream.
1682 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1683 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1684 if (!audio_track) {
1685 return;
1686 }
1687 DestroyAudioSender(stream, audio_track, ssrc);
1688 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1689 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1690 if (!video_track) {
1691 return;
1692 }
1693 DestroyVideoSender(stream, video_track);
1694 } else {
1695 RTC_DCHECK(false && "Invalid media type.");
1696 }
1697}
1698
1699void PeerConnection::UpdateLocalRtpDataChannels(
1700 const cricket::StreamParamsVec& streams) {
1701 std::vector<std::string> existing_channels;
1702
1703 // Find new and active data channels.
1704 for (const cricket::StreamParams& params : streams) {
1705 // |it->sync_label| is actually the data channel label. The reason is that
1706 // we use the same naming of data channels as we do for
1707 // MediaStreams and Tracks.
1708 // For MediaStreams, the sync_label is the MediaStream label and the
1709 // track label is the same as |streamid|.
1710 const std::string& channel_label = params.sync_label;
1711 auto data_channel_it = rtp_data_channels_.find(channel_label);
1712 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1713 continue;
1714 }
1715 // Set the SSRC the data channel should use for sending.
1716 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1717 existing_channels.push_back(data_channel_it->first);
1718 }
1719
1720 UpdateClosingRtpDataChannels(existing_channels, true);
1721}
1722
1723void PeerConnection::UpdateRemoteRtpDataChannels(
1724 const cricket::StreamParamsVec& streams) {
1725 std::vector<std::string> existing_channels;
1726
1727 // Find new and active data channels.
1728 for (const cricket::StreamParams& params : streams) {
1729 // The data channel label is either the mslabel or the SSRC if the mslabel
1730 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1731 std::string label = params.sync_label.empty()
1732 ? rtc::ToString(params.first_ssrc())
1733 : params.sync_label;
1734 auto data_channel_it = rtp_data_channels_.find(label);
1735 if (data_channel_it == rtp_data_channels_.end()) {
1736 // This is a new data channel.
1737 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1738 } else {
1739 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1740 }
1741 existing_channels.push_back(label);
1742 }
1743
1744 UpdateClosingRtpDataChannels(existing_channels, false);
1745}
1746
1747void PeerConnection::UpdateClosingRtpDataChannels(
1748 const std::vector<std::string>& active_channels,
1749 bool is_local_update) {
1750 auto it = rtp_data_channels_.begin();
1751 while (it != rtp_data_channels_.end()) {
1752 DataChannel* data_channel = it->second;
1753 if (std::find(active_channels.begin(), active_channels.end(),
1754 data_channel->label()) != active_channels.end()) {
1755 ++it;
1756 continue;
1757 }
1758
1759 if (is_local_update) {
1760 data_channel->SetSendSsrc(0);
1761 } else {
1762 data_channel->RemotePeerRequestClose();
1763 }
1764
1765 if (data_channel->state() == DataChannel::kClosed) {
1766 rtp_data_channels_.erase(it);
1767 it = rtp_data_channels_.begin();
1768 } else {
1769 ++it;
1770 }
1771 }
1772}
1773
1774void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1775 uint32_t remote_ssrc) {
1776 rtc::scoped_refptr<DataChannel> channel(
1777 InternalCreateDataChannel(label, nullptr));
1778 if (!channel.get()) {
1779 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1780 << "CreateDataChannel failed.";
1781 return;
1782 }
1783 channel->SetReceiveSsrc(remote_ssrc);
1784 observer_->OnDataChannel(
1785 DataChannelProxy::Create(signaling_thread(), channel));
1786}
1787
1788rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1789 const std::string& label,
1790 const InternalDataChannelInit* config) {
1791 if (IsClosed()) {
1792 return nullptr;
1793 }
1794 if (session_->data_channel_type() == cricket::DCT_NONE) {
1795 LOG(LS_ERROR)
1796 << "InternalCreateDataChannel: Data is not supported in this call.";
1797 return nullptr;
1798 }
1799 InternalDataChannelInit new_config =
1800 config ? (*config) : InternalDataChannelInit();
1801 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1802 if (new_config.id < 0) {
1803 rtc::SSLRole role;
1804 if (session_->GetSslRole(&role) &&
1805 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1806 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1807 return nullptr;
1808 }
1809 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1810 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1811 << "because the id is already in use or out of range.";
1812 return nullptr;
1813 }
1814 }
1815
1816 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1817 session_.get(), session_->data_channel_type(), label, new_config));
1818 if (!channel) {
1819 sid_allocator_.ReleaseSid(new_config.id);
1820 return nullptr;
1821 }
1822
1823 if (channel->data_channel_type() == cricket::DCT_RTP) {
1824 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1825 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1826 << " already exists.";
1827 return nullptr;
1828 }
1829 rtp_data_channels_[channel->label()] = channel;
1830 } else {
1831 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1832 sctp_data_channels_.push_back(channel);
1833 channel->SignalClosed.connect(this,
1834 &PeerConnection::OnSctpDataChannelClosed);
1835 }
1836
1837 return channel;
1838}
1839
1840bool PeerConnection::HasDataChannels() const {
1841 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1842}
1843
1844void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1845 for (const auto& channel : sctp_data_channels_) {
1846 if (channel->id() < 0) {
1847 int sid;
1848 if (!sid_allocator_.AllocateSid(role, &sid)) {
1849 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1850 continue;
1851 }
1852 channel->SetSctpSid(sid);
1853 }
1854 }
1855}
1856
1857void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1858 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1859 ++it) {
1860 if (it->get() == channel) {
1861 if (channel->id() >= 0) {
1862 sid_allocator_.ReleaseSid(channel->id());
1863 }
1864 sctp_data_channels_.erase(it);
1865 return;
1866 }
1867 }
1868}
1869
1870void PeerConnection::OnVoiceChannelDestroyed() {
1871 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1872}
1873
1874void PeerConnection::OnVideoChannelDestroyed() {
1875 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1876}
1877
1878void PeerConnection::OnDataChannelCreated() {
1879 for (const auto& channel : sctp_data_channels_) {
1880 channel->OnTransportChannelCreated();
1881 }
1882}
1883
1884void PeerConnection::OnDataChannelDestroyed() {
1885 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1886 // DataChannel may callback to us and try to modify the list.
1887 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1888 temp_rtp_dcs.swap(rtp_data_channels_);
1889 for (const auto& kv : temp_rtp_dcs) {
1890 kv.second->OnTransportChannelDestroyed();
1891 }
1892
1893 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1894 temp_sctp_dcs.swap(sctp_data_channels_);
1895 for (const auto& channel : temp_sctp_dcs) {
1896 channel->OnTransportChannelDestroyed();
1897 }
1898}
1899
1900void PeerConnection::OnDataChannelOpenMessage(
1901 const std::string& label,
1902 const InternalDataChannelInit& config) {
1903 rtc::scoped_refptr<DataChannel> channel(
1904 InternalCreateDataChannel(label, &config));
1905 if (!channel.get()) {
1906 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1907 return;
1908 }
1909
1910 observer_->OnDataChannel(
1911 DataChannelProxy::Create(signaling_thread(), channel));
1912}
1913
deadbeef70ab1a12015-09-28 16:53:55 -07001914std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1915PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1916 return std::find_if(
1917 senders_.begin(), senders_.end(),
1918 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1919 return sender->track() == track;
1920 });
1921}
1922
1923std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1924PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1925 return std::find_if(
1926 receivers_.begin(), receivers_.end(),
1927 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1928 return receiver->track() == track;
1929 });
1930}
1931
deadbeefab9b2d12015-10-14 11:33:11 -07001932PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1933 cricket::MediaType media_type) {
1934 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1935 media_type == cricket::MEDIA_TYPE_VIDEO);
1936 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1937 : &remote_video_tracks_;
1938}
1939
1940PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
1941 cricket::MediaType media_type) {
1942 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1943 media_type == cricket::MEDIA_TYPE_VIDEO);
1944 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
1945 : &local_video_tracks_;
1946}
1947
1948const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
1949 const PeerConnection::TrackInfos& infos,
1950 const std::string& stream_label,
1951 const std::string track_id) const {
1952 for (const TrackInfo& track_info : infos) {
1953 if (track_info.stream_label == stream_label &&
1954 track_info.track_id == track_id) {
1955 return &track_info;
1956 }
1957 }
1958 return nullptr;
1959}
1960
1961DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
1962 for (const auto& channel : sctp_data_channels_) {
1963 if (channel->id() == sid) {
1964 return channel;
1965 }
1966 }
1967 return nullptr;
1968}
1969
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970} // namespace webrtc