blob: fecc19ba0ebce95bd9a911eac9ef280fa80302ee [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|.
deadbeef8f46c632015-10-26 14:11:17 -0700368void 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) {
deadbeefab9b2d12015-10-14 11:33:11 -0700372 session_options->streams.clear();
deadbeef8f46c632015-10-26 14:11:17 -0700373 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 }
deadbeefab9b2d12015-10-14 11:33:11 -0700387 }
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
deadbeefc80741f2015-10-22 13:14:45 -0700466 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700467 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
468 }
deadbeefc80741f2015-10-22 13:14:45 -0700469 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700470 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
471 }
472
473 session_options->vad_enabled = rtc_options.voice_activity_detection;
474 session_options->transport_options.ice_restart = rtc_options.ice_restart;
deadbeefc80741f2015-10-22 13:14:45 -0700475 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeefab9b2d12015-10-14 11:33:11 -0700476
477 return true;
478}
479
480bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
481 cricket::MediaSessionOptions* session_options) {
482 bool value = false;
483 size_t mandatory_constraints_satisfied = 0;
484
485 // kOfferToReceiveAudio defaults to true according to spec.
486 if (!FindConstraint(constraints,
487 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
488 &mandatory_constraints_satisfied) ||
489 value) {
490 session_options->recv_audio = true;
491 }
492
493 // kOfferToReceiveVideo defaults to false according to spec. But
494 // if it is an answer and video is offered, we should still accept video
495 // per default.
496 value = false;
497 if (!FindConstraint(constraints,
498 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
499 &mandatory_constraints_satisfied) ||
500 value) {
501 session_options->recv_video = true;
502 }
503
504 if (FindConstraint(constraints,
505 MediaConstraintsInterface::kVoiceActivityDetection, &value,
506 &mandatory_constraints_satisfied)) {
507 session_options->vad_enabled = value;
508 }
509
510 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
511 &mandatory_constraints_satisfied)) {
512 session_options->bundle_enabled = value;
513 } else {
514 // kUseRtpMux defaults to true according to spec.
515 session_options->bundle_enabled = true;
516 }
deadbeefab9b2d12015-10-14 11:33:11 -0700517
518 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
519 &value, &mandatory_constraints_satisfied)) {
520 session_options->transport_options.ice_restart = value;
521 } else {
522 // kIceRestart defaults to false according to spec.
523 session_options->transport_options.ice_restart = false;
524 }
525
526 if (!constraints) {
527 return true;
528 }
529 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
530}
531
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200532bool ParseIceServers(const PeerConnectionInterface::IceServers& servers,
deadbeef0a6c4ca2015-10-06 11:38:28 -0700533 StunConfigurations* stun_config,
534 TurnConfigurations* turn_config) {
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200535 for (const webrtc::PeerConnectionInterface::IceServer& server : servers) {
536 if (!server.urls.empty()) {
537 for (const std::string& url : server.urls) {
Joachim Bauchd935f912015-05-29 22:14:21 +0200538 if (url.empty()) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700539 LOG(LS_ERROR) << "Empty uri.";
540 return false;
Joachim Bauchd935f912015-05-29 22:14:21 +0200541 }
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200542 if (!ParseIceServerUrl(server, url, stun_config, turn_config)) {
543 return false;
544 }
545 }
546 } else if (!server.uri.empty()) {
547 // Fallback to old .uri if new .urls isn't present.
548 if (!ParseIceServerUrl(server, server.uri, stun_config, turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000549 return false;
Joachim Bauch7c4e7452015-05-28 23:06:30 +0200550 }
551 } else {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700552 LOG(LS_ERROR) << "Empty uri.";
553 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000554 }
555 }
556 return true;
557}
558
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000559PeerConnection::PeerConnection(PeerConnectionFactory* factory)
560 : factory_(factory),
561 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000562 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000563 signaling_state_(kStable),
564 ice_state_(kIceNew),
565 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700566 ice_gathering_state_(kIceGatheringNew),
567 local_streams_(StreamCollection::Create()),
568 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000569
570PeerConnection::~PeerConnection() {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700571 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700572 // Need to detach RTP senders/receivers from WebRtcSession,
573 // since it's about to be destroyed.
574 for (const auto& sender : senders_) {
575 sender->Stop();
576 }
577 for (const auto& receiver : receivers_) {
578 receiver->Stop();
579 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000580}
581
582bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000583 const PeerConnectionInterface::RTCConfiguration& configuration,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000584 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000585 PortAllocatorFactoryInterface* allocator_factory,
Henrik Boström5e56c592015-08-11 10:33:13 +0200586 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587 PeerConnectionObserver* observer) {
deadbeefab9b2d12015-10-14 11:33:11 -0700588 RTC_DCHECK(observer != nullptr);
589 if (!observer) {
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000590 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700591 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000592 observer_ = observer;
593
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000594 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
595 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000596 if (!ParseIceServers(configuration.servers, &stun_config, &turn_config)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597 return false;
598 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599 port_allocator_.reset(
600 allocator_factory->CreatePortAllocator(stun_config, turn_config));
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000601
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 // To handle both internal and externally created port allocator, we will
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000603 // enable BUNDLE here.
braveyao@webrtc.org1732df62014-10-27 03:01:37 +0000604 int portallocator_flags = port_allocator_->flags();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700605 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000606 cricket::PORTALLOCATOR_ENABLE_IPV6;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000607 bool value;
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000608 // If IPv6 flag was specified, we'll not override it by experiment.
deadbeefab9b2d12015-10-14 11:33:11 -0700609 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableIPv6,
610 &value, nullptr)) {
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000611 if (!value) {
612 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
guoweis@webrtc.org97ed3932014-09-19 21:06:12 +0000613 }
guoweis@webrtc.org2c1bcea2014-09-23 16:23:02 +0000614 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
guoweis@webrtc.orgbbce5ef2015-03-05 04:38:29 +0000615 "Disabled") {
616 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000617 }
618
Jiayang Liucac1b382015-04-30 12:35:24 -0700619 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
620 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
621 LOG(LS_INFO) << "TCP candidates are disabled.";
622 }
623
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000624 port_allocator_->set_flags(portallocator_flags);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000625 // No step delay is used while allocating ports.
626 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
627
stefanc1aeaf02015-10-15 07:26:07 -0700628 media_controller_.reset(factory_->CreateMediaController());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000629
stefanc1aeaf02015-10-15 07:26:07 -0700630 remote_stream_factory_.reset(new RemoteMediaStreamFactory(
631 factory_->signaling_thread(), media_controller_->channel_manager()));
632
633 session_.reset(
634 new WebRtcSession(media_controller_.get(), factory_->signaling_thread(),
635 factory_->worker_thread(), port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -0700636 stats_.reset(new StatsCollector(this));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000637
638 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000639 if (!session_->Initialize(factory_->options(), constraints,
deadbeefab9b2d12015-10-14 11:33:11 -0700640 dtls_identity_store.Pass(), configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700642 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644 // Register PeerConnection as receiver of local ice candidates.
645 // All the callbacks will be posted to the application from PeerConnection.
646 session_->RegisterIceObserver(this);
647 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
deadbeefab9b2d12015-10-14 11:33:11 -0700648 session_->SignalVoiceChannelDestroyed.connect(
649 this, &PeerConnection::OnVoiceChannelDestroyed);
650 session_->SignalVideoChannelDestroyed.connect(
651 this, &PeerConnection::OnVideoChannelDestroyed);
652 session_->SignalDataChannelCreated.connect(
653 this, &PeerConnection::OnDataChannelCreated);
654 session_->SignalDataChannelDestroyed.connect(
655 this, &PeerConnection::OnDataChannelDestroyed);
656 session_->SignalDataChannelOpenMessage.connect(
657 this, &PeerConnection::OnDataChannelOpenMessage);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000658 return true;
659}
660
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000661rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700663 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000664}
665
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000666rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700668 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669}
670
deadbeef8f46c632015-10-26 14:11:17 -0700671// TODO(deadbeef): Create RtpSenders immediately here, even if local
672// description hasn't yet been set.
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000673bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674 if (IsClosed()) {
675 return false;
676 }
deadbeefab9b2d12015-10-14 11:33:11 -0700677 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678 return false;
679 }
deadbeefab9b2d12015-10-14 11:33:11 -0700680
681 local_streams_->AddStream(local_stream);
682
deadbeef8f46c632015-10-26 14:11:17 -0700683 // Find tracks that have already been configured in SDP. This can occur if a
684 // local session description that contains the MSID of these tracks is set
685 // before AddLocalStream is called. It can also occur if the local session
686 // description is not changed and RemoveLocalStream is called and later
687 // AddLocalStream is called again with the same stream.
deadbeefab9b2d12015-10-14 11:33:11 -0700688 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700689 const TrackInfo* track_info =
690 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
691 if (track_info) {
692 CreateAudioSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700693 }
694 }
695 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700696 const TrackInfo* track_info =
697 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
698 if (track_info) {
699 CreateVideoSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700700 }
701 }
702
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000703 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 observer_->OnRenegotiationNeeded();
705 return true;
706}
707
deadbeefab9b2d12015-10-14 11:33:11 -0700708// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
deadbeef8f46c632015-10-26 14:11:17 -0700709// indefinitely.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
deadbeefab9b2d12015-10-14 11:33:11 -0700711 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700712 const TrackInfo* track_info =
713 FindTrackInfo(local_audio_tracks_, local_stream->label(), track->id());
714 if (track_info) {
715 DestroyAudioSender(local_stream, track.get(), track_info->ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -0700716 }
717 }
718 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeef8f46c632015-10-26 14:11:17 -0700719 const TrackInfo* track_info =
720 FindTrackInfo(local_video_tracks_, local_stream->label(), track->id());
721 if (track_info) {
722 DestroyVideoSender(local_stream, track.get());
deadbeefab9b2d12015-10-14 11:33:11 -0700723 }
724 }
725
726 local_streams_->RemoveStream(local_stream);
727
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 if (IsClosed()) {
729 return;
730 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 observer_->OnRenegotiationNeeded();
732}
733
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000734rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 AudioTrackInterface* track) {
736 if (!track) {
737 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
738 return NULL;
739 }
deadbeefab9b2d12015-10-14 11:33:11 -0700740 if (!local_streams_->FindAudioTrack(track->id())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
742 return NULL;
743 }
744
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000745 rtc::scoped_refptr<DtmfSenderInterface> sender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746 DtmfSender::Create(track, signaling_thread(), session_.get()));
747 if (!sender.get()) {
748 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
749 return NULL;
750 }
751 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
752}
753
deadbeef70ab1a12015-09-28 16:53:55 -0700754std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
755 const {
756 std::vector<rtc::scoped_refptr<RtpSenderInterface>> senders;
757 for (const auto& sender : senders_) {
758 senders.push_back(RtpSenderProxy::Create(signaling_thread(), sender.get()));
759 }
760 return senders;
761}
762
763std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
764PeerConnection::GetReceivers() const {
765 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
766 for (const auto& receiver : receivers_) {
767 receivers.push_back(
768 RtpReceiverProxy::Create(signaling_thread(), receiver.get()));
769 }
770 return receivers;
771}
772
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000773bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000774 MediaStreamTrackInterface* track,
775 StatsOutputLevel level) {
deadbeef0a6c4ca2015-10-06 11:38:28 -0700776 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000777 if (!VERIFY(observer != NULL)) {
778 LOG(LS_ERROR) << "GetStats - observer is NULL.";
779 return false;
780 }
781
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000782 stats_->UpdateStats(level);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000783 signaling_thread()->Post(this, MSG_GETSTATS,
784 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785 return true;
786}
787
788PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
789 return signaling_state_;
790}
791
792PeerConnectionInterface::IceState PeerConnection::ice_state() {
793 return ice_state_;
794}
795
796PeerConnectionInterface::IceConnectionState
797PeerConnection::ice_connection_state() {
798 return ice_connection_state_;
799}
800
801PeerConnectionInterface::IceGatheringState
802PeerConnection::ice_gathering_state() {
803 return ice_gathering_state_;
804}
805
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000806rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807PeerConnection::CreateDataChannel(
808 const std::string& label,
809 const DataChannelInit* config) {
deadbeefab9b2d12015-10-14 11:33:11 -0700810 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000811
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000812 rtc::scoped_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000813 if (config) {
814 internal_config.reset(new InternalDataChannelInit(*config));
815 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000816 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700817 InternalCreateDataChannel(label, internal_config.get()));
818 if (!channel.get()) {
819 return nullptr;
820 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000822 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
823 // the first SCTP DataChannel.
824 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
825 observer_->OnRenegotiationNeeded();
826 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000827
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828 return DataChannelProxy::Create(signaling_thread(), channel.get());
829}
830
831void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
832 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700833 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
835 return;
836 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000837 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000838
839 bool value;
840 size_t mandatory_constraints = 0;
841
842 if (FindConstraint(constraints,
843 MediaConstraintsInterface::kOfferToReceiveAudio,
844 &value,
845 &mandatory_constraints)) {
846 options.offer_to_receive_audio =
847 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
848 }
849
850 if (FindConstraint(constraints,
851 MediaConstraintsInterface::kOfferToReceiveVideo,
852 &value,
853 &mandatory_constraints)) {
854 options.offer_to_receive_video =
855 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
856 }
857
858 if (FindConstraint(constraints,
859 MediaConstraintsInterface::kVoiceActivityDetection,
860 &value,
861 &mandatory_constraints)) {
862 options.voice_activity_detection = value;
863 }
864
865 if (FindConstraint(constraints,
866 MediaConstraintsInterface::kIceRestart,
867 &value,
868 &mandatory_constraints)) {
869 options.ice_restart = value;
870 }
871
872 if (FindConstraint(constraints,
873 MediaConstraintsInterface::kUseRtpMux,
874 &value,
875 &mandatory_constraints)) {
876 options.use_rtp_mux = value;
877 }
878
879 CreateOffer(observer, options);
880}
881
882void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
883 const RTCOfferAnswerOptions& options) {
deadbeefab9b2d12015-10-14 11:33:11 -0700884 if (!VERIFY(observer != nullptr)) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000885 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
886 return;
887 }
deadbeefab9b2d12015-10-14 11:33:11 -0700888
889 cricket::MediaSessionOptions session_options;
890 if (!GetOptionsForOffer(options, &session_options)) {
891 std::string error = "CreateOffer called with invalid options.";
892 LOG(LS_ERROR) << error;
893 PostCreateSessionDescriptionFailure(observer, error);
894 return;
895 }
896
897 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898}
899
900void PeerConnection::CreateAnswer(
901 CreateSessionDescriptionObserver* observer,
902 const MediaConstraintsInterface* constraints) {
deadbeefab9b2d12015-10-14 11:33:11 -0700903 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
905 return;
906 }
deadbeefab9b2d12015-10-14 11:33:11 -0700907
908 cricket::MediaSessionOptions session_options;
909 if (!GetOptionsForAnswer(constraints, &session_options)) {
910 std::string error = "CreateAnswer called with invalid constraints.";
911 LOG(LS_ERROR) << error;
912 PostCreateSessionDescriptionFailure(observer, error);
913 return;
914 }
915
916 session_->CreateAnswer(observer, constraints, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917}
918
919void PeerConnection::SetLocalDescription(
920 SetSessionDescriptionObserver* observer,
921 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -0700922 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
924 return;
925 }
926 if (!desc) {
927 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
928 return;
929 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 // Update stats here so that we have the most recent stats for tracks and
931 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000932 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933 std::string error;
934 if (!session_->SetLocalDescription(desc, &error)) {
935 PostSetSessionDescriptionFailure(observer, error);
936 return;
937 }
deadbeefab9b2d12015-10-14 11:33:11 -0700938
939 // If setting the description decided our SSL role, allocate any necessary
940 // SCTP sids.
941 rtc::SSLRole role;
942 if (session_->data_channel_type() == cricket::DCT_SCTP &&
943 session_->GetSslRole(&role)) {
944 AllocateSctpSids(role);
945 }
946
947 // Update state and SSRC of local MediaStreams and DataChannels based on the
948 // local session description.
949 const cricket::ContentInfo* audio_content =
950 GetFirstAudioContent(desc->description());
951 if (audio_content) {
952 const cricket::AudioContentDescription* audio_desc =
953 static_cast<const cricket::AudioContentDescription*>(
954 audio_content->description);
955 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
956 }
957
958 const cricket::ContentInfo* video_content =
959 GetFirstVideoContent(desc->description());
960 if (video_content) {
961 const cricket::VideoContentDescription* video_desc =
962 static_cast<const cricket::VideoContentDescription*>(
963 video_content->description);
964 UpdateLocalTracks(video_desc->streams(), video_desc->type());
965 }
966
967 const cricket::ContentInfo* data_content =
968 GetFirstDataContent(desc->description());
969 if (data_content) {
970 const cricket::DataContentDescription* data_desc =
971 static_cast<const cricket::DataContentDescription*>(
972 data_content->description);
973 if (rtc::starts_with(data_desc->protocol().data(),
974 cricket::kMediaProtocolRtpPrefix)) {
975 UpdateLocalRtpDataChannels(data_desc->streams());
976 }
977 }
978
979 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700981
deadbeefcbecd352015-09-23 11:50:27 -0700982 // MaybeStartGathering needs to be called after posting
983 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
984 // before signaling that SetLocalDescription completed.
985 session_->MaybeStartGathering();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986}
987
988void PeerConnection::SetRemoteDescription(
989 SetSessionDescriptionObserver* observer,
990 SessionDescriptionInterface* desc) {
deadbeefab9b2d12015-10-14 11:33:11 -0700991 if (!VERIFY(observer != nullptr)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
993 return;
994 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995 if (!desc) {
996 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
997 return;
998 }
999 // Update stats here so that we have the most recent stats for tracks and
1000 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001001 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 std::string error;
1003 if (!session_->SetRemoteDescription(desc, &error)) {
1004 PostSetSessionDescriptionFailure(observer, error);
1005 return;
1006 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007
deadbeefab9b2d12015-10-14 11:33:11 -07001008 // If setting the description decided our SSL role, allocate any necessary
1009 // SCTP sids.
1010 rtc::SSLRole role;
1011 if (session_->data_channel_type() == cricket::DCT_SCTP &&
1012 session_->GetSslRole(&role)) {
1013 AllocateSctpSids(role);
1014 }
1015
1016 const cricket::SessionDescription* remote_desc = desc->description();
1017
1018 // We wait to signal new streams until we finish processing the description,
1019 // since only at that point will new streams have all their tracks.
1020 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1021
1022 // Find all audio rtp streams and create corresponding remote AudioTracks
1023 // and MediaStreams.
1024 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1025 if (audio_content) {
1026 const cricket::AudioContentDescription* desc =
1027 static_cast<const cricket::AudioContentDescription*>(
1028 audio_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001029 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(), new_streams);
deadbeefab9b2d12015-10-14 11:33:11 -07001030 remote_info_.default_audio_track_needed =
deadbeefc80741f2015-10-22 13:14:45 -07001031 !remote_desc->msid_supported() && desc->streams().empty() &&
1032 MediaContentDirectionHasSend(desc->direction());
deadbeefab9b2d12015-10-14 11:33:11 -07001033 }
1034
1035 // Find all video rtp streams and create corresponding remote VideoTracks
1036 // and MediaStreams.
1037 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1038 if (video_content) {
1039 const cricket::VideoContentDescription* desc =
1040 static_cast<const cricket::VideoContentDescription*>(
1041 video_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001042 UpdateRemoteStreamsList(GetActiveStreams(desc), desc->type(), new_streams);
deadbeefab9b2d12015-10-14 11:33:11 -07001043 remote_info_.default_video_track_needed =
deadbeefc80741f2015-10-22 13:14:45 -07001044 !remote_desc->msid_supported() && desc->streams().empty() &&
1045 MediaContentDirectionHasSend(desc->direction());
deadbeefab9b2d12015-10-14 11:33:11 -07001046 }
1047
1048 // Update the DataChannels with the information from the remote peer.
1049 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
1050 if (data_content) {
deadbeef5e97fb52015-10-15 12:49:08 -07001051 const cricket::DataContentDescription* desc =
deadbeefab9b2d12015-10-14 11:33:11 -07001052 static_cast<const cricket::DataContentDescription*>(
1053 data_content->description);
deadbeef5e97fb52015-10-15 12:49:08 -07001054 if (rtc::starts_with(desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001055 cricket::kMediaProtocolRtpPrefix)) {
deadbeef5e97fb52015-10-15 12:49:08 -07001056 UpdateRemoteRtpDataChannels(GetActiveStreams(desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001057 }
1058 }
1059
1060 // Iterate new_streams and notify the observer about new MediaStreams.
1061 for (size_t i = 0; i < new_streams->count(); ++i) {
1062 MediaStreamInterface* new_stream = new_streams->at(i);
1063 stats_->AddStream(new_stream);
1064 observer_->OnAddStream(new_stream);
1065 }
1066
1067 // Find removed MediaStreams.
1068 if (remote_info_.IsDefaultMediaStreamNeeded() &&
1069 remote_streams_->find(kDefaultStreamLabel) != nullptr) {
1070 // The default media stream already exists. No need to do anything.
1071 } else {
1072 UpdateEndedRemoteMediaStreams();
1073 remote_info_.msid_supported |= remote_streams_->count() > 0;
1074 }
1075 MaybeCreateDefaultStream();
1076
1077 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1078 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeeffc648b62015-10-13 16:42:33 -07001079}
1080
deadbeefa67696b2015-09-29 11:56:26 -07001081bool PeerConnection::SetConfiguration(const RTCConfiguration& config) {
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001082 if (port_allocator_) {
1083 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stuns;
1084 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turns;
1085 if (!ParseIceServers(config.servers, &stuns, &turns)) {
1086 return false;
1087 }
1088
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001089 std::vector<rtc::SocketAddress> stun_hosts;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001090 typedef std::vector<StunConfiguration>::const_iterator StunIt;
1091 for (StunIt stun_it = stuns.begin(); stun_it != stuns.end(); ++stun_it) {
1092 stun_hosts.push_back(stun_it->server);
1093 }
1094
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001095 rtc::SocketAddress stun_addr;
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001096 if (!stun_hosts.empty()) {
1097 stun_addr = stun_hosts.front();
deadbeefa67696b2015-09-29 11:56:26 -07001098 LOG(LS_INFO) << "SetConfiguration: StunServer Address: "
1099 << stun_addr.ToString();
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001100 }
1101
1102 for (size_t i = 0; i < turns.size(); ++i) {
1103 cricket::RelayCredentials credentials(turns[i].username,
1104 turns[i].password);
1105 cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
1106 cricket::ProtocolType protocol;
1107 if (cricket::StringToProto(turns[i].transport_type.c_str(), &protocol)) {
1108 relay_server.ports.push_back(cricket::ProtocolAddress(
1109 turns[i].server, protocol, turns[i].secure));
1110 relay_server.credentials = credentials;
deadbeefa67696b2015-09-29 11:56:26 -07001111 LOG(LS_INFO) << "SetConfiguration: TurnServer Address: "
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001112 << turns[i].server.ToString();
1113 } else {
1114 LOG(LS_WARNING) << "Ignoring TURN server " << turns[i].server << ". "
1115 << "Reason= Incorrect " << turns[i].transport_type
1116 << " transport parameter.";
1117 }
1118 }
1119 }
honghaiz1f429e32015-09-28 07:57:34 -07001120 session_->SetIceConfig(session_->ParseIceConfig(config));
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001121 return session_->SetIceTransports(config.type);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001122}
1123
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001124bool PeerConnection::AddIceCandidate(
1125 const IceCandidateInterface* ice_candidate) {
1126 return session_->ProcessIceMessage(ice_candidate);
1127}
1128
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001129void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
1130 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001131
1132 if (session_) {
1133 session_->set_metrics_observer(uma_observer_);
1134 }
1135
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001136 // Send information about IPv4/IPv6 status.
1137 if (uma_observer_ && port_allocator_) {
1138 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001139 uma_observer_->IncrementEnumCounter(
1140 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1141 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001142 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001143 uma_observer_->IncrementEnumCounter(
1144 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1145 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001146 }
1147 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001148}
1149
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150const SessionDescriptionInterface* PeerConnection::local_description() const {
1151 return session_->local_description();
1152}
1153
1154const SessionDescriptionInterface* PeerConnection::remote_description() const {
1155 return session_->remote_description();
1156}
1157
1158void PeerConnection::Close() {
1159 // Update stats here so that we have the most recent stats for tracks and
1160 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001161 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162
deadbeefd59daf82015-10-14 15:02:44 -07001163 session_->Close();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001164}
1165
deadbeefd59daf82015-10-14 15:02:44 -07001166void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1167 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001169 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001171 break;
deadbeefd59daf82015-10-14 15:02:44 -07001172 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1174 break;
deadbeefd59daf82015-10-14 15:02:44 -07001175 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001176 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1177 break;
deadbeefd59daf82015-10-14 15:02:44 -07001178 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001179 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1180 break;
deadbeefd59daf82015-10-14 15:02:44 -07001181 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001182 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1183 break;
deadbeefd59daf82015-10-14 15:02:44 -07001184 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185 ChangeSignalingState(PeerConnectionInterface::kStable);
1186 break;
deadbeefd59daf82015-10-14 15:02:44 -07001187 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 ChangeSignalingState(PeerConnectionInterface::kClosed);
1189 break;
1190 default:
1191 break;
1192 }
1193}
1194
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001195void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001196 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1198 SetSessionDescriptionMsg* param =
1199 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1200 param->observer->OnSuccess();
1201 delete param;
1202 break;
1203 }
1204 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1205 SetSessionDescriptionMsg* param =
1206 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1207 param->observer->OnFailure(param->error);
1208 delete param;
1209 break;
1210 }
deadbeefab9b2d12015-10-14 11:33:11 -07001211 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1212 CreateSessionDescriptionMsg* param =
1213 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1214 param->observer->OnFailure(param->error);
1215 delete param;
1216 break;
1217 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001218 case MSG_GETSTATS: {
1219 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001220 StatsReports reports;
1221 stats_->GetStats(param->track, &reports);
1222 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001223 delete param;
1224 break;
1225 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001226 default:
deadbeef0a6c4ca2015-10-06 11:38:28 -07001227 RTC_DCHECK(false && "Not implemented");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 break;
1229 }
1230}
1231
deadbeefab9b2d12015-10-14 11:33:11 -07001232void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
1233 AudioTrackInterface* audio_track,
1234 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001235 receivers_.push_back(new AudioRtpReceiver(audio_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001236}
1237
deadbeefab9b2d12015-10-14 11:33:11 -07001238void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
1239 VideoTrackInterface* video_track,
1240 uint32_t ssrc) {
deadbeef70ab1a12015-09-28 16:53:55 -07001241 receivers_.push_back(new VideoRtpReceiver(video_track, ssrc, session_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242}
1243
deadbeef70ab1a12015-09-28 16:53:55 -07001244// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1245// description.
deadbeefab9b2d12015-10-14 11:33:11 -07001246void PeerConnection::DestroyAudioReceiver(MediaStreamInterface* stream,
1247 AudioTrackInterface* audio_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001248 auto it = FindReceiverForTrack(audio_track);
1249 if (it == receivers_.end()) {
1250 LOG(LS_WARNING) << "RtpReceiver for track with id " << audio_track->id()
1251 << " doesn't exist.";
1252 } else {
1253 (*it)->Stop();
1254 receivers_.erase(it);
1255 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256}
1257
deadbeefab9b2d12015-10-14 11:33:11 -07001258void PeerConnection::DestroyVideoReceiver(MediaStreamInterface* stream,
1259 VideoTrackInterface* video_track) {
deadbeef70ab1a12015-09-28 16:53:55 -07001260 auto it = FindReceiverForTrack(video_track);
1261 if (it == receivers_.end()) {
1262 LOG(LS_WARNING) << "RtpReceiver for track with id " << video_track->id()
1263 << " doesn't exist.";
1264 } else {
1265 (*it)->Stop();
1266 receivers_.erase(it);
1267 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268}
deadbeef70ab1a12015-09-28 16:53:55 -07001269
deadbeef8f46c632015-10-26 14:11:17 -07001270void PeerConnection::CreateAudioSender(MediaStreamInterface* stream,
1271 AudioTrackInterface* audio_track,
1272 uint32_t ssrc) {
1273 senders_.push_back(new AudioRtpSender(audio_track, ssrc, session_.get()));
1274 stats_->AddLocalAudioTrack(audio_track, ssrc);
1275}
1276
1277void PeerConnection::CreateVideoSender(MediaStreamInterface* stream,
1278 VideoTrackInterface* video_track,
1279 uint32_t ssrc) {
1280 senders_.push_back(new VideoRtpSender(video_track, ssrc, session_.get()));
1281}
1282
1283// TODO(deadbeef): Keep RtpSenders around even if track goes away in local
1284// description.
1285void PeerConnection::DestroyAudioSender(MediaStreamInterface* stream,
1286 AudioTrackInterface* audio_track,
1287 uint32_t ssrc) {
1288 auto it = FindSenderForTrack(audio_track);
1289 if (it == senders_.end()) {
1290 LOG(LS_WARNING) << "RtpSender for track with id " << audio_track->id()
1291 << " doesn't exist.";
1292 return;
1293 } else {
1294 (*it)->Stop();
1295 senders_.erase(it);
1296 }
1297 stats_->RemoveLocalAudioTrack(audio_track, ssrc);
1298}
1299
1300void PeerConnection::DestroyVideoSender(MediaStreamInterface* stream,
1301 VideoTrackInterface* video_track) {
1302 auto it = FindSenderForTrack(video_track);
1303 if (it == senders_.end()) {
1304 LOG(LS_WARNING) << "RtpSender for track with id " << video_track->id()
1305 << " doesn't exist.";
1306 return;
1307 } else {
1308 (*it)->Stop();
1309 senders_.erase(it);
1310 }
1311}
1312
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313void PeerConnection::OnIceConnectionChange(
1314 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001315 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001316 // After transitioning to "closed", ignore any additional states from
1317 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001318 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001319 return;
1320 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001322 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323}
1324
1325void PeerConnection::OnIceGatheringChange(
1326 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001327 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328 if (IsClosed()) {
1329 return;
1330 }
1331 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001332 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333}
1334
1335void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001336 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001337 observer_->OnIceCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338}
1339
1340void PeerConnection::OnIceComplete() {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001341 RTC_DCHECK(signaling_thread()->IsCurrent());
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001342 observer_->OnIceComplete();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343}
1344
Peter Thatcher54360512015-07-08 11:08:35 -07001345void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001346 RTC_DCHECK(signaling_thread()->IsCurrent());
Peter Thatcher54360512015-07-08 11:08:35 -07001347 observer_->OnIceConnectionReceivingChange(receiving);
1348}
1349
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001350void PeerConnection::ChangeSignalingState(
1351 PeerConnectionInterface::SignalingState signaling_state) {
1352 signaling_state_ = signaling_state;
1353 if (signaling_state == kClosed) {
1354 ice_connection_state_ = kIceConnectionClosed;
1355 observer_->OnIceConnectionChange(ice_connection_state_);
1356 if (ice_gathering_state_ != kIceGatheringComplete) {
1357 ice_gathering_state_ = kIceGatheringComplete;
1358 observer_->OnIceGatheringChange(ice_gathering_state_);
1359 }
1360 }
1361 observer_->OnSignalingChange(signaling_state_);
1362 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
1363}
1364
deadbeefab9b2d12015-10-14 11:33:11 -07001365void PeerConnection::PostSetSessionDescriptionFailure(
1366 SetSessionDescriptionObserver* observer,
1367 const std::string& error) {
1368 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1369 msg->error = error;
1370 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
1371}
1372
1373void PeerConnection::PostCreateSessionDescriptionFailure(
1374 CreateSessionDescriptionObserver* observer,
1375 const std::string& error) {
1376 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1377 msg->error = error;
1378 signaling_thread()->Post(this, MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
1379}
1380
1381bool PeerConnection::GetOptionsForOffer(
1382 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1383 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001384 if (!ConvertRtcOptionsForOffer(rtc_options, session_options)) {
1385 return false;
1386 }
1387
deadbeef8f46c632015-10-26 14:11:17 -07001388 SetStreams(session_options, local_streams_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001389 // Offer to receive audio/video if the constraint is not set and there are
1390 // send streams, or we're currently receiving.
1391 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1392 session_options->recv_audio =
1393 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1394 !remote_audio_tracks_.empty();
1395 }
1396 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1397 session_options->recv_video =
1398 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1399 !remote_video_tracks_.empty();
1400 }
1401 session_options->bundle_enabled =
1402 session_options->bundle_enabled &&
1403 (session_options->has_audio() || session_options->has_video() ||
1404 session_options->has_data());
1405
deadbeefab9b2d12015-10-14 11:33:11 -07001406 if (session_->data_channel_type() == cricket::DCT_SCTP && HasDataChannels()) {
1407 session_options->data_channel_type = cricket::DCT_SCTP;
1408 }
1409 return true;
1410}
1411
1412bool PeerConnection::GetOptionsForAnswer(
1413 const MediaConstraintsInterface* constraints,
1414 cricket::MediaSessionOptions* session_options) {
deadbeefab9b2d12015-10-14 11:33:11 -07001415 session_options->recv_audio = false;
1416 session_options->recv_video = false;
deadbeefab9b2d12015-10-14 11:33:11 -07001417 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1418 return false;
1419 }
1420
deadbeef8f46c632015-10-26 14:11:17 -07001421 SetStreams(session_options, local_streams_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001422 session_options->bundle_enabled =
1423 session_options->bundle_enabled &&
1424 (session_options->has_audio() || session_options->has_video() ||
1425 session_options->has_data());
1426
deadbeefab9b2d12015-10-14 11:33:11 -07001427 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1428 // are not signaled in the SDP so does not go through that path and must be
1429 // handled here.
1430 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1431 session_options->data_channel_type = cricket::DCT_SCTP;
1432 }
1433 return true;
1434}
1435
1436void PeerConnection::UpdateRemoteStreamsList(
1437 const cricket::StreamParamsVec& streams,
1438 cricket::MediaType media_type,
1439 StreamCollection* new_streams) {
1440 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1441
1442 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeef8f46c632015-10-26 14:11:17 -07001443 // the
1444 // new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001445 auto track_it = current_tracks->begin();
1446 while (track_it != current_tracks->end()) {
1447 const TrackInfo& info = *track_it;
1448 const cricket::StreamParams* params =
1449 cricket::GetStreamBySsrc(streams, info.ssrc);
1450 if (!params || params->id != info.track_id) {
1451 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1452 track_it = current_tracks->erase(track_it);
1453 } else {
1454 ++track_it;
1455 }
1456 }
1457
1458 // Find new and active tracks.
1459 for (const cricket::StreamParams& params : streams) {
1460 // The sync_label is the MediaStream label and the |stream.id| is the
1461 // track id.
1462 const std::string& stream_label = params.sync_label;
1463 const std::string& track_id = params.id;
1464 uint32_t ssrc = params.first_ssrc();
1465
1466 rtc::scoped_refptr<MediaStreamInterface> stream =
1467 remote_streams_->find(stream_label);
1468 if (!stream) {
1469 // This is a new MediaStream. Create a new remote MediaStream.
1470 stream = remote_stream_factory_->CreateMediaStream(stream_label);
1471 remote_streams_->AddStream(stream);
1472 new_streams->AddStream(stream);
1473 }
1474
1475 const TrackInfo* track_info =
1476 FindTrackInfo(*current_tracks, stream_label, track_id);
1477 if (!track_info) {
1478 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1479 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1480 }
1481 }
1482}
1483
1484void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1485 const std::string& track_id,
1486 uint32_t ssrc,
1487 cricket::MediaType media_type) {
1488 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1489
1490 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1491 AudioTrackInterface* audio_track =
1492 remote_stream_factory_->AddAudioTrack(stream, track_id);
1493 CreateAudioReceiver(stream, audio_track, ssrc);
1494 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1495 VideoTrackInterface* video_track =
1496 remote_stream_factory_->AddVideoTrack(stream, track_id);
1497 CreateVideoReceiver(stream, video_track, ssrc);
1498 } else {
1499 RTC_DCHECK(false && "Invalid media type");
1500 }
1501}
1502
1503void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1504 const std::string& track_id,
1505 cricket::MediaType media_type) {
1506 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1507
1508 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1509 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1510 stream->FindAudioTrack(track_id);
1511 if (audio_track) {
1512 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1513 stream->RemoveTrack(audio_track);
1514 DestroyAudioReceiver(stream, audio_track);
1515 }
1516 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1517 rtc::scoped_refptr<VideoTrackInterface> video_track =
1518 stream->FindVideoTrack(track_id);
1519 if (video_track) {
1520 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1521 stream->RemoveTrack(video_track);
1522 DestroyVideoReceiver(stream, video_track);
1523 }
1524 } else {
1525 ASSERT(false && "Invalid media type");
1526 }
1527}
1528
1529void PeerConnection::UpdateEndedRemoteMediaStreams() {
1530 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1531 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1532 MediaStreamInterface* stream = remote_streams_->at(i);
1533 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1534 streams_to_remove.push_back(stream);
1535 }
1536 }
1537
1538 for (const auto& stream : streams_to_remove) {
1539 remote_streams_->RemoveStream(stream);
1540 observer_->OnRemoveStream(stream);
1541 }
1542}
1543
1544void PeerConnection::MaybeCreateDefaultStream() {
1545 if (!remote_info_.IsDefaultMediaStreamNeeded()) {
1546 return;
1547 }
1548
1549 bool default_created = false;
1550
1551 rtc::scoped_refptr<MediaStreamInterface> default_remote_stream =
1552 remote_streams_->find(kDefaultStreamLabel);
1553 if (default_remote_stream == nullptr) {
1554 default_created = true;
1555 default_remote_stream =
1556 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
1557 remote_streams_->AddStream(default_remote_stream);
1558 }
1559 if (remote_info_.default_audio_track_needed &&
1560 default_remote_stream->GetAudioTracks().size() == 0) {
1561 remote_audio_tracks_.push_back(
1562 TrackInfo(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0));
1563 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
1564 cricket::MEDIA_TYPE_AUDIO);
1565 }
1566 if (remote_info_.default_video_track_needed &&
1567 default_remote_stream->GetVideoTracks().size() == 0) {
1568 remote_video_tracks_.push_back(
1569 TrackInfo(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0));
1570 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
1571 cricket::MEDIA_TYPE_VIDEO);
1572 }
1573 if (default_created) {
1574 stats_->AddStream(default_remote_stream);
1575 observer_->OnAddStream(default_remote_stream);
1576 }
1577}
1578
1579void PeerConnection::EndRemoteTracks(cricket::MediaType media_type) {
1580 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1581 for (TrackInfos::iterator track_it = current_tracks->begin();
1582 track_it != current_tracks->end(); ++track_it) {
1583 const TrackInfo& info = *track_it;
1584 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
1585 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1586 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
1587 // There's no guarantee the track is still available, e.g. the track may
1588 // have been removed from the stream by javascript.
1589 if (track) {
1590 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1591 }
1592 }
1593 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1594 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
1595 // There's no guarantee the track is still available, e.g. the track may
1596 // have been removed from the stream by javascript.
1597 if (track) {
1598 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
1599 }
1600 }
1601 }
1602}
1603
1604void PeerConnection::UpdateLocalTracks(
1605 const std::vector<cricket::StreamParams>& streams,
1606 cricket::MediaType media_type) {
1607 TrackInfos* current_tracks = GetLocalTracks(media_type);
1608
1609 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1610 // don't match the new StreamParam.
1611 TrackInfos::iterator track_it = current_tracks->begin();
1612 while (track_it != current_tracks->end()) {
1613 const TrackInfo& info = *track_it;
1614 const cricket::StreamParams* params =
1615 cricket::GetStreamBySsrc(streams, info.ssrc);
1616 if (!params || params->id != info.track_id ||
1617 params->sync_label != info.stream_label) {
1618 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1619 media_type);
1620 track_it = current_tracks->erase(track_it);
1621 } else {
1622 ++track_it;
1623 }
1624 }
1625
1626 // Find new and active tracks.
1627 for (const cricket::StreamParams& params : streams) {
1628 // The sync_label is the MediaStream label and the |stream.id| is the
1629 // track id.
1630 const std::string& stream_label = params.sync_label;
1631 const std::string& track_id = params.id;
1632 uint32_t ssrc = params.first_ssrc();
1633 const TrackInfo* track_info =
1634 FindTrackInfo(*current_tracks, stream_label, track_id);
1635 if (!track_info) {
1636 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1637 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1638 }
1639 }
1640}
1641
1642void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1643 const std::string& track_id,
1644 uint32_t ssrc,
1645 cricket::MediaType media_type) {
deadbeef8f46c632015-10-26 14:11:17 -07001646 MediaStreamInterface* stream = local_streams_->find(stream_label);
1647 if (!stream) {
1648 LOG(LS_WARNING) << "An unknown local MediaStream with label "
1649 << stream_label << " has been configured.";
deadbeefab9b2d12015-10-14 11:33:11 -07001650 return;
1651 }
1652
deadbeef8f46c632015-10-26 14:11:17 -07001653 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1654 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1655 if (!audio_track) {
1656 LOG(LS_WARNING) << "An unknown local AudioTrack with id , " << track_id
1657 << " has been configured.";
1658 return;
1659 }
1660 CreateAudioSender(stream, audio_track, ssrc);
1661 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1662 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1663 if (!video_track) {
1664 LOG(LS_WARNING) << "An unknown local VideoTrack with id , " << track_id
1665 << " has been configured.";
1666 return;
1667 }
1668 CreateVideoSender(stream, video_track, ssrc);
1669 } else {
1670 RTC_DCHECK(false && "Invalid media type");
deadbeefab9b2d12015-10-14 11:33:11 -07001671 }
1672}
1673
1674void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1675 const std::string& track_id,
1676 uint32_t ssrc,
1677 cricket::MediaType media_type) {
deadbeef8f46c632015-10-26 14:11:17 -07001678 MediaStreamInterface* stream = local_streams_->find(stream_label);
1679 if (!stream) {
1680 // This is the normal case. I.e., RemoveLocalStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001681 // SessionDescriptions has been renegotiated.
1682 return;
1683 }
deadbeef8f46c632015-10-26 14:11:17 -07001684 // A track has been removed from the SessionDescription but the MediaStream
1685 // is still associated with PeerConnection. This only occurs if the SDP
1686 // doesn't match with the calls to AddLocalStream and RemoveLocalStream.
1687 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1688 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
1689 if (!audio_track) {
1690 return;
1691 }
1692 DestroyAudioSender(stream, audio_track, ssrc);
1693 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
1694 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
1695 if (!video_track) {
1696 return;
1697 }
1698 DestroyVideoSender(stream, video_track);
1699 } else {
1700 RTC_DCHECK(false && "Invalid media type.");
deadbeefab9b2d12015-10-14 11:33:11 -07001701 }
1702}
1703
1704void PeerConnection::UpdateLocalRtpDataChannels(
1705 const cricket::StreamParamsVec& streams) {
1706 std::vector<std::string> existing_channels;
1707
1708 // Find new and active data channels.
1709 for (const cricket::StreamParams& params : streams) {
1710 // |it->sync_label| is actually the data channel label. The reason is that
1711 // we use the same naming of data channels as we do for
1712 // MediaStreams and Tracks.
1713 // For MediaStreams, the sync_label is the MediaStream label and the
1714 // track label is the same as |streamid|.
1715 const std::string& channel_label = params.sync_label;
1716 auto data_channel_it = rtp_data_channels_.find(channel_label);
1717 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
1718 continue;
1719 }
1720 // Set the SSRC the data channel should use for sending.
1721 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1722 existing_channels.push_back(data_channel_it->first);
1723 }
1724
1725 UpdateClosingRtpDataChannels(existing_channels, true);
1726}
1727
1728void PeerConnection::UpdateRemoteRtpDataChannels(
1729 const cricket::StreamParamsVec& streams) {
1730 std::vector<std::string> existing_channels;
1731
1732 // Find new and active data channels.
1733 for (const cricket::StreamParams& params : streams) {
1734 // The data channel label is either the mslabel or the SSRC if the mslabel
1735 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1736 std::string label = params.sync_label.empty()
1737 ? rtc::ToString(params.first_ssrc())
1738 : params.sync_label;
1739 auto data_channel_it = rtp_data_channels_.find(label);
1740 if (data_channel_it == rtp_data_channels_.end()) {
1741 // This is a new data channel.
1742 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1743 } else {
1744 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1745 }
1746 existing_channels.push_back(label);
1747 }
1748
1749 UpdateClosingRtpDataChannels(existing_channels, false);
1750}
1751
1752void PeerConnection::UpdateClosingRtpDataChannels(
1753 const std::vector<std::string>& active_channels,
1754 bool is_local_update) {
1755 auto it = rtp_data_channels_.begin();
1756 while (it != rtp_data_channels_.end()) {
1757 DataChannel* data_channel = it->second;
1758 if (std::find(active_channels.begin(), active_channels.end(),
1759 data_channel->label()) != active_channels.end()) {
1760 ++it;
1761 continue;
1762 }
1763
1764 if (is_local_update) {
1765 data_channel->SetSendSsrc(0);
1766 } else {
1767 data_channel->RemotePeerRequestClose();
1768 }
1769
1770 if (data_channel->state() == DataChannel::kClosed) {
1771 rtp_data_channels_.erase(it);
1772 it = rtp_data_channels_.begin();
1773 } else {
1774 ++it;
1775 }
1776 }
1777}
1778
1779void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1780 uint32_t remote_ssrc) {
1781 rtc::scoped_refptr<DataChannel> channel(
1782 InternalCreateDataChannel(label, nullptr));
1783 if (!channel.get()) {
1784 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1785 << "CreateDataChannel failed.";
1786 return;
1787 }
1788 channel->SetReceiveSsrc(remote_ssrc);
1789 observer_->OnDataChannel(
1790 DataChannelProxy::Create(signaling_thread(), channel));
1791}
1792
1793rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
1794 const std::string& label,
1795 const InternalDataChannelInit* config) {
1796 if (IsClosed()) {
1797 return nullptr;
1798 }
1799 if (session_->data_channel_type() == cricket::DCT_NONE) {
1800 LOG(LS_ERROR)
1801 << "InternalCreateDataChannel: Data is not supported in this call.";
1802 return nullptr;
1803 }
1804 InternalDataChannelInit new_config =
1805 config ? (*config) : InternalDataChannelInit();
1806 if (session_->data_channel_type() == cricket::DCT_SCTP) {
1807 if (new_config.id < 0) {
1808 rtc::SSLRole role;
1809 if (session_->GetSslRole(&role) &&
1810 !sid_allocator_.AllocateSid(role, &new_config.id)) {
1811 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1812 return nullptr;
1813 }
1814 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
1815 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1816 << "because the id is already in use or out of range.";
1817 return nullptr;
1818 }
1819 }
1820
1821 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1822 session_.get(), session_->data_channel_type(), label, new_config));
1823 if (!channel) {
1824 sid_allocator_.ReleaseSid(new_config.id);
1825 return nullptr;
1826 }
1827
1828 if (channel->data_channel_type() == cricket::DCT_RTP) {
1829 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
1830 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
1831 << " already exists.";
1832 return nullptr;
1833 }
1834 rtp_data_channels_[channel->label()] = channel;
1835 } else {
1836 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
1837 sctp_data_channels_.push_back(channel);
1838 channel->SignalClosed.connect(this,
1839 &PeerConnection::OnSctpDataChannelClosed);
1840 }
1841
1842 return channel;
1843}
1844
1845bool PeerConnection::HasDataChannels() const {
1846 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
1847}
1848
1849void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
1850 for (const auto& channel : sctp_data_channels_) {
1851 if (channel->id() < 0) {
1852 int sid;
1853 if (!sid_allocator_.AllocateSid(role, &sid)) {
1854 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
1855 continue;
1856 }
1857 channel->SetSctpSid(sid);
1858 }
1859 }
1860}
1861
1862void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
1863 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
1864 ++it) {
1865 if (it->get() == channel) {
1866 if (channel->id() >= 0) {
1867 sid_allocator_.ReleaseSid(channel->id());
1868 }
1869 sctp_data_channels_.erase(it);
1870 return;
1871 }
1872 }
1873}
1874
1875void PeerConnection::OnVoiceChannelDestroyed() {
1876 EndRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
1877}
1878
1879void PeerConnection::OnVideoChannelDestroyed() {
1880 EndRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
1881}
1882
1883void PeerConnection::OnDataChannelCreated() {
1884 for (const auto& channel : sctp_data_channels_) {
1885 channel->OnTransportChannelCreated();
1886 }
1887}
1888
1889void PeerConnection::OnDataChannelDestroyed() {
1890 // Use a temporary copy of the RTP/SCTP DataChannel list because the
1891 // DataChannel may callback to us and try to modify the list.
1892 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
1893 temp_rtp_dcs.swap(rtp_data_channels_);
1894 for (const auto& kv : temp_rtp_dcs) {
1895 kv.second->OnTransportChannelDestroyed();
1896 }
1897
1898 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
1899 temp_sctp_dcs.swap(sctp_data_channels_);
1900 for (const auto& channel : temp_sctp_dcs) {
1901 channel->OnTransportChannelDestroyed();
1902 }
1903}
1904
1905void PeerConnection::OnDataChannelOpenMessage(
1906 const std::string& label,
1907 const InternalDataChannelInit& config) {
1908 rtc::scoped_refptr<DataChannel> channel(
1909 InternalCreateDataChannel(label, &config));
1910 if (!channel.get()) {
1911 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
1912 return;
1913 }
1914
1915 observer_->OnDataChannel(
1916 DataChannelProxy::Create(signaling_thread(), channel));
1917}
1918
deadbeef70ab1a12015-09-28 16:53:55 -07001919std::vector<rtc::scoped_refptr<RtpSenderInterface>>::iterator
1920PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
1921 return std::find_if(
1922 senders_.begin(), senders_.end(),
1923 [track](const rtc::scoped_refptr<RtpSenderInterface>& sender) {
1924 return sender->track() == track;
1925 });
1926}
1927
1928std::vector<rtc::scoped_refptr<RtpReceiverInterface>>::iterator
1929PeerConnection::FindReceiverForTrack(MediaStreamTrackInterface* track) {
1930 return std::find_if(
1931 receivers_.begin(), receivers_.end(),
1932 [track](const rtc::scoped_refptr<RtpReceiverInterface>& receiver) {
1933 return receiver->track() == track;
1934 });
1935}
1936
deadbeefab9b2d12015-10-14 11:33:11 -07001937PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
1938 cricket::MediaType media_type) {
1939 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1940 media_type == cricket::MEDIA_TYPE_VIDEO);
1941 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
1942 : &remote_video_tracks_;
1943}
1944
1945PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
1946 cricket::MediaType media_type) {
1947 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
1948 media_type == cricket::MEDIA_TYPE_VIDEO);
1949 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
1950 : &local_video_tracks_;
1951}
1952
1953const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
1954 const PeerConnection::TrackInfos& infos,
1955 const std::string& stream_label,
1956 const std::string track_id) const {
1957 for (const TrackInfo& track_info : infos) {
1958 if (track_info.stream_label == stream_label &&
1959 track_info.track_id == track_id) {
1960 return &track_info;
1961 }
1962 }
1963 return nullptr;
1964}
1965
1966DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
1967 for (const auto& channel : sctp_data_channels_) {
1968 if (channel->id() == sid) {
1969 return channel;
1970 }
1971 }
1972 return nullptr;
1973}
1974
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975} // namespace webrtc