blob: fde45104d61ddfafee2791b1e297d164ab6425ac [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/webrtcsession.h"
29
pbos@webrtc.org371243d2014-03-07 15:22:04 +000030#include <limits.h>
31
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032#include <algorithm>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033#include <vector>
34
35#include "talk/app/webrtc/jsepicecandidate.h"
36#include "talk/app/webrtc/jsepsessiondescription.h"
37#include "talk/app/webrtc/mediaconstraintsinterface.h"
38#include "talk/app/webrtc/mediastreamsignaling.h"
39#include "talk/app/webrtc/peerconnectioninterface.h"
wu@webrtc.org91053e72013-08-10 07:18:04 +000040#include "talk/app/webrtc/webrtcsessiondescriptionfactory.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000041#include "talk/media/base/constants.h"
42#include "talk/media/base/videocapturer.h"
43#include "talk/session/media/channel.h"
44#include "talk/session/media/channelmanager.h"
45#include "talk/session/media/mediasession.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000046#include "webrtc/base/basictypes.h"
jbauchac8869e2015-07-03 01:36:14 -070047#include "webrtc/base/checks.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000048#include "webrtc/base/helpers.h"
49#include "webrtc/base/logging.h"
50#include "webrtc/base/stringencode.h"
51#include "webrtc/base/stringutils.h"
pthatcher@webrtc.org40b276e2014-12-12 02:44:30 +000052#include "webrtc/p2p/base/portallocator.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
54using cricket::ContentInfo;
55using cricket::ContentInfos;
56using cricket::MediaContentDescription;
57using cricket::SessionDescription;
58using cricket::TransportInfo;
59
Guo-wei Shieh3d564c12015-08-19 16:51:15 -070060using cricket::LOCAL_PORT_TYPE;
61using cricket::STUN_PORT_TYPE;
62using cricket::RELAY_PORT_TYPE;
63using cricket::PRFLX_PORT_TYPE;
64
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065namespace webrtc {
66
henrike@webrtc.org28e20752013-07-10 00:45:36 +000067// Error messages
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000068const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
69 "is enabled.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000070const char kCreateChannelFailed[] = "Failed to create channels.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071const char kInvalidCandidates[] = "Description contains invalid candidates.";
72const char kInvalidSdp[] = "Invalid session description.";
73const char kMlineMismatch[] =
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000074 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
75const char kPushDownTDFailed[] =
76 "Failed to push down transport description:";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000077const char kSdpWithoutDtlsFingerprint[] =
78 "Called with SDP without DTLS fingerprint.";
79const char kSdpWithoutSdesCrypto[] =
80 "Called with SDP without SDES crypto.";
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +000081const char kSdpWithoutIceUfragPwd[] =
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000082 "Called with SDP without ice-ufrag and ice-pwd.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083const char kSessionError[] = "Session error code: ";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000084const char kSessionErrorDesc[] = "Session error description: ";
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +000085const char kDtlsSetupFailureRtp[] =
86 "Couldn't set up DTLS-SRTP on RTP channel.";
87const char kDtlsSetupFailureRtcp[] =
88 "Couldn't set up DTLS-SRTP on RTCP channel.";
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +000089const int kMaxUnsignalledRecvStreams = 20;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
Guo-wei Shieh3d564c12015-08-19 16:51:15 -070091IceCandidatePairType GetIceCandidatePairCounter(
92 const cricket::Candidate& local,
93 const cricket::Candidate& remote) {
94 const auto& l = local.type();
95 const auto& r = remote.type();
96 const auto& host = LOCAL_PORT_TYPE;
97 const auto& srflx = STUN_PORT_TYPE;
98 const auto& relay = RELAY_PORT_TYPE;
99 const auto& prflx = PRFLX_PORT_TYPE;
100 if (l == host && r == host)
101 return kIceCandidatePairHostHost;
102 if (l == host && r == srflx)
103 return kIceCandidatePairHostSrflx;
104 if (l == host && r == relay)
105 return kIceCandidatePairHostRelay;
106 if (l == host && r == prflx)
107 return kIceCandidatePairHostPrflx;
108 if (l == srflx && r == host)
109 return kIceCandidatePairSrflxHost;
110 if (l == srflx && r == srflx)
111 return kIceCandidatePairSrflxSrflx;
112 if (l == srflx && r == relay)
113 return kIceCandidatePairSrflxRelay;
114 if (l == srflx && r == prflx)
115 return kIceCandidatePairSrflxPrflx;
116 if (l == relay && r == host)
117 return kIceCandidatePairRelayHost;
118 if (l == relay && r == srflx)
119 return kIceCandidatePairRelaySrflx;
120 if (l == relay && r == relay)
121 return kIceCandidatePairRelayRelay;
122 if (l == relay && r == prflx)
123 return kIceCandidatePairRelayPrflx;
124 if (l == prflx && r == host)
125 return kIceCandidatePairPrflxHost;
126 if (l == prflx && r == srflx)
127 return kIceCandidatePairPrflxSrflx;
128 if (l == prflx && r == relay)
129 return kIceCandidatePairPrflxRelay;
130 return kIceCandidatePairMax;
131}
132
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133// Compares |answer| against |offer|. Comparision is done
134// for number of m-lines in answer against offer. If matches true will be
135// returned otherwise false.
136static bool VerifyMediaDescriptions(
137 const SessionDescription* answer, const SessionDescription* offer) {
138 if (offer->contents().size() != answer->contents().size())
139 return false;
140
141 for (size_t i = 0; i < offer->contents().size(); ++i) {
142 if ((offer->contents()[i].name) != answer->contents()[i].name) {
143 return false;
144 }
wu@webrtc.org4e393072014-04-07 17:04:35 +0000145 const MediaContentDescription* offer_mdesc =
146 static_cast<const MediaContentDescription*>(
147 offer->contents()[i].description);
148 const MediaContentDescription* answer_mdesc =
149 static_cast<const MediaContentDescription*>(
150 answer->contents()[i].description);
151 if (offer_mdesc->type() != answer_mdesc->type()) {
152 return false;
153 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000154 }
155 return true;
156}
157
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000158// Checks that each non-rejected content has SDES crypto keys or a DTLS
159// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
160// keys, will be caught in Transport negotiation, and backstopped by Channel's
161// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000162static bool VerifyCrypto(const SessionDescription* desc,
163 bool dtls_enabled,
164 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000165 const ContentInfos& contents = desc->contents();
166 for (size_t index = 0; index < contents.size(); ++index) {
167 const ContentInfo* cinfo = &contents[index];
168 if (cinfo->rejected) {
169 continue;
170 }
171
172 // If the content isn't rejected, crypto must be present.
173 const MediaContentDescription* media =
174 static_cast<const MediaContentDescription*>(cinfo->description);
175 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
176 if (!media || !tinfo) {
177 // Something is not right.
178 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000179 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180 return false;
181 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000182 if (dtls_enabled) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000183 if (!tinfo->description.identity_fingerprint) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000184 LOG(LS_WARNING) <<
185 "Session description must have DTLS fingerprint if DTLS enabled.";
186 *error = kSdpWithoutDtlsFingerprint;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000187 return false;
188 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000189 } else {
190 if (media->cryptos().empty()) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000191 LOG(LS_WARNING) <<
192 "Session description must have SDES when DTLS disabled.";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000193 *error = kSdpWithoutSdesCrypto;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000194 return false;
195 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000196 }
197 }
198
199 return true;
200}
201
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000202// Checks that each non-rejected content has ice-ufrag and ice-pwd set.
203static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
204 const ContentInfos& contents = desc->contents();
205 for (size_t index = 0; index < contents.size(); ++index) {
206 const ContentInfo* cinfo = &contents[index];
207 if (cinfo->rejected) {
208 continue;
209 }
210
211 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
212 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
213 if (!tinfo) {
214 // Something is not right.
215 LOG(LS_ERROR) << kInvalidSdp;
216 return false;
217 }
218 if (tinfo->description.ice_ufrag.empty() ||
219 tinfo->description.ice_pwd.empty()) {
220 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
221 return false;
222 }
223 }
224 return true;
225}
226
wu@webrtc.org91053e72013-08-10 07:18:04 +0000227// Forces |sdesc->crypto_required| to the appropriate state based on the
228// current security policy, to ensure a failure occurs if there is an error
229// in crypto negotiation.
230// Called when processing the local session description.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000231static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
232 SessionDescription* sdesc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000233 if (!sdesc) {
234 return;
235 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000236
wu@webrtc.org91053e72013-08-10 07:18:04 +0000237 // Updating the |crypto_required_| in MediaContentDescription to the
238 // appropriate state based on the current security policy.
239 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
240 iter != sdesc->contents().end(); ++iter) {
241 if (cricket::IsMediaContent(&*iter)) {
242 MediaContentDescription* mdesc =
243 static_cast<MediaContentDescription*> (iter->description);
244 if (mdesc) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000245 mdesc->set_crypto_required(type);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000246 }
247 }
248 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249}
250
251static bool GetAudioSsrcByTrackId(
252 const SessionDescription* session_description,
253 const std::string& track_id, uint32 *ssrc) {
254 const cricket::ContentInfo* audio_info =
255 cricket::GetFirstAudioContent(session_description);
256 if (!audio_info) {
257 LOG(LS_ERROR) << "Audio not used in this call";
258 return false;
259 }
260
261 const cricket::MediaContentDescription* audio_content =
262 static_cast<const cricket::MediaContentDescription*>(
263 audio_info->description);
tommi@webrtc.org586f2ed2015-01-22 23:00:41 +0000264 const cricket::StreamParams* stream =
265 cricket::GetStreamByIds(audio_content->streams(), "", track_id);
266 if (!stream) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000267 return false;
268 }
tommi@webrtc.org586f2ed2015-01-22 23:00:41 +0000269
270 *ssrc = stream->first_ssrc();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271 return true;
272}
273
274static bool GetTrackIdBySsrc(const SessionDescription* session_description,
275 uint32 ssrc, std::string* track_id) {
276 ASSERT(track_id != NULL);
277
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000278 const cricket::ContentInfo* audio_info =
279 cricket::GetFirstAudioContent(session_description);
jiayl@webrtc.orge21cc9a2014-08-28 22:21:34 +0000280 if (audio_info) {
281 const cricket::MediaContentDescription* audio_content =
282 static_cast<const cricket::MediaContentDescription*>(
283 audio_info->description);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000284
tommi@webrtc.org586f2ed2015-01-22 23:00:41 +0000285 const auto* found =
286 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
287 if (found) {
288 *track_id = found->id;
jiayl@webrtc.orge21cc9a2014-08-28 22:21:34 +0000289 return true;
290 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000291 }
292
293 const cricket::ContentInfo* video_info =
294 cricket::GetFirstVideoContent(session_description);
jiayl@webrtc.orge21cc9a2014-08-28 22:21:34 +0000295 if (video_info) {
296 const cricket::MediaContentDescription* video_content =
297 static_cast<const cricket::MediaContentDescription*>(
298 video_info->description);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000299
tommi@webrtc.org586f2ed2015-01-22 23:00:41 +0000300 const auto* found =
301 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
302 if (found) {
303 *track_id = found->id;
jiayl@webrtc.orge21cc9a2014-08-28 22:21:34 +0000304 return true;
305 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000306 }
307 return false;
308}
309
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000310static bool BadSdp(const std::string& source,
311 const std::string& type,
312 const std::string& reason,
313 std::string* err_desc) {
314 std::ostringstream desc;
315 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
316
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000317 if (err_desc) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000318 *err_desc = desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000319 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000320 LOG(LS_ERROR) << desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000321 return false;
322}
323
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000324static bool BadSdp(cricket::ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000325 const std::string& type,
326 const std::string& reason,
327 std::string* err_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000328 if (source == cricket::CS_LOCAL) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000329 return BadSdp("local", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000330 } else {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000331 return BadSdp("remote", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000332 }
333}
334
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000335static bool BadLocalSdp(const std::string& type,
336 const std::string& reason,
337 std::string* err_desc) {
338 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
339}
340
341static bool BadRemoteSdp(const std::string& type,
342 const std::string& reason,
343 std::string* err_desc) {
344 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
345}
346
347static bool BadOfferSdp(cricket::ContentSource source,
348 const std::string& reason,
349 std::string* err_desc) {
350 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
351}
352
353static bool BadPranswerSdp(cricket::ContentSource source,
354 const std::string& reason,
355 std::string* err_desc) {
356 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
357 reason, err_desc);
358}
359
360static bool BadAnswerSdp(cricket::ContentSource source,
361 const std::string& reason,
362 std::string* err_desc) {
363 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000364}
365
366#define GET_STRING_OF_STATE(state) \
367 case cricket::BaseSession::state: \
368 result = #state; \
369 break;
370
371static std::string GetStateString(cricket::BaseSession::State state) {
372 std::string result;
373 switch (state) {
374 GET_STRING_OF_STATE(STATE_INIT)
375 GET_STRING_OF_STATE(STATE_SENTINITIATE)
376 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
377 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
378 GET_STRING_OF_STATE(STATE_SENTACCEPT)
379 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
380 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
381 GET_STRING_OF_STATE(STATE_SENTMODIFY)
382 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
383 GET_STRING_OF_STATE(STATE_SENTREJECT)
384 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
385 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
386 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
387 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
388 GET_STRING_OF_STATE(STATE_INPROGRESS)
389 GET_STRING_OF_STATE(STATE_DEINIT)
390 default:
391 ASSERT(false);
392 break;
393 }
394 return result;
395}
396
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000397#define GET_STRING_OF_ERROR_CODE(err) \
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000398 case cricket::BaseSession::err: \
399 result = #err; \
400 break;
401
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000402static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000403 std::string result;
404 switch (err) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000405 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
406 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
407 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
408 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
409 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
410 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000411 default:
412 ASSERT(false);
413 break;
414 }
415 return result;
416}
417
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000418static std::string MakeErrorString(const std::string& error,
419 const std::string& desc) {
420 std::ostringstream ret;
421 ret << error << " " << desc;
422 return ret.str();
423}
424
425static std::string MakeTdErrorString(const std::string& desc) {
426 return MakeErrorString(kPushDownTDFailed, desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000427}
428
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000429// Set |option| to the highest-priority value of |key| in the optional
430// constraints if the key is found and has a valid value.
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000431template<typename T>
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000432static void SetOptionFromOptionalConstraint(
433 const MediaConstraintsInterface* constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000434 const std::string& key, cricket::Settable<T>* option) {
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000435 if (!constraints) {
436 return;
437 }
438 std::string string_value;
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000439 T value;
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000440 if (constraints->GetOptional().FindFirst(key, &string_value)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000441 if (rtc::FromString(string_value, &value)) {
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000442 option->Set(value);
443 }
444 }
445}
446
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +0000447uint32 ConvertIceTransportTypeToCandidateFilter(
448 PeerConnectionInterface::IceTransportsType type) {
449 switch (type) {
450 case PeerConnectionInterface::kNone:
451 return cricket::CF_NONE;
452 case PeerConnectionInterface::kRelay:
453 return cricket::CF_RELAY;
454 case PeerConnectionInterface::kNoHost:
455 return (cricket::CF_ALL & ~cricket::CF_HOST);
456 case PeerConnectionInterface::kAll:
457 return cricket::CF_ALL;
458 default: ASSERT(false);
459 }
460 return cricket::CF_NONE;
461}
462
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000463// Help class used to remember if a a remote peer has requested ice restart by
464// by sending a description with new ice ufrag and password.
465class IceRestartAnswerLatch {
466 public:
467 IceRestartAnswerLatch() : ice_restart_(false) { }
468
wu@webrtc.org91053e72013-08-10 07:18:04 +0000469 // Returns true if CheckForRemoteIceRestart has been called with a new session
470 // description where ice password and ufrag has changed since last time
471 // Reset() was called.
472 bool Get() const {
473 return ice_restart_;
474 }
475
476 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000477 if (ice_restart_) {
478 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000479 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000480 }
481
honghaiz503726c2015-07-31 12:37:38 -0700482 bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
483 const SessionDescriptionInterface* new_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000484 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
honghaiz503726c2015-07-31 12:37:38 -0700485 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000486 }
487 const SessionDescription* new_sd = new_desc->description();
488 const SessionDescription* old_sd = old_desc->description();
489 const ContentInfos& contents = new_sd->contents();
490 for (size_t index = 0; index < contents.size(); ++index) {
491 const ContentInfo* cinfo = &contents[index];
492 if (cinfo->rejected) {
493 continue;
494 }
495 // If the content isn't rejected, check if ufrag and password has
496 // changed.
497 const cricket::TransportDescription* new_transport_desc =
498 new_sd->GetTransportDescriptionByName(cinfo->name);
499 const cricket::TransportDescription* old_transport_desc =
500 old_sd->GetTransportDescriptionByName(cinfo->name);
501 if (!new_transport_desc || !old_transport_desc) {
502 // No transport description exist. This is not an ice restart.
503 continue;
504 }
jiayl@webrtc.orgdb397e52014-06-20 16:32:09 +0000505 if (cricket::IceCredentialsChanged(old_transport_desc->ice_ufrag,
506 old_transport_desc->ice_pwd,
507 new_transport_desc->ice_ufrag,
508 new_transport_desc->ice_pwd)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000509 LOG(LS_INFO) << "Remote peer request ice restart.";
510 ice_restart_ = true;
honghaiz503726c2015-07-31 12:37:38 -0700511 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000512 }
513 }
honghaiz503726c2015-07-31 12:37:38 -0700514 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000515 }
516
517 private:
518 bool ice_restart_;
519};
520
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000521WebRtcSession::WebRtcSession(
522 cricket::ChannelManager* channel_manager,
523 rtc::Thread* signaling_thread,
524 rtc::Thread* worker_thread,
525 cricket::PortAllocator* port_allocator,
526 MediaStreamSignaling* mediastream_signaling)
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +0000527 : cricket::BaseSession(signaling_thread,
528 worker_thread,
529 port_allocator,
530 rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX),
531 cricket::NS_JINGLE_RTP,
532 false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533 // RFC 3264: The numeric value of the session id and version in the
534 // o line MUST be representable with a "64 bit signed integer".
535 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
536 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000537 mediastream_signaling_(mediastream_signaling),
538 ice_observer_(NULL),
539 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
Peter Thatcher54360512015-07-08 11:08:35 -0700540 ice_connection_receiving_(true),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000541 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000542 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000543 data_channel_type_(cricket::DCT_NONE),
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +0000544 ice_restart_latch_(new IceRestartAnswerLatch),
545 metrics_observer_(NULL) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000546}
547
548WebRtcSession::~WebRtcSession() {
tommi0f620f42015-07-09 03:25:02 -0700549 ASSERT(signaling_thread()->IsCurrent());
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000550 // Destroy video_channel_ first since it may have a pointer to the
551 // voice_channel_.
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +0000552 if (video_channel_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000553 SignalVideoChannelDestroyed();
554 channel_manager_->DestroyVideoChannel(video_channel_.release());
555 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +0000556 if (voice_channel_) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000557 SignalVoiceChannelDestroyed();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +0200558 channel_manager_->DestroyVoiceChannel(voice_channel_.release(), nullptr);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000559 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +0000560 if (data_channel_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000561 SignalDataChannelDestroyed();
562 channel_manager_->DestroyDataChannel(data_channel_.release());
563 }
564 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
565 delete saved_candidates_[i];
566 }
567 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568}
569
wu@webrtc.org91053e72013-08-10 07:18:04 +0000570bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000571 const PeerConnectionFactoryInterface::Options& options,
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000572 const MediaConstraintsInterface* constraints,
Henrik Boström5e56c592015-08-11 10:33:13 +0200573 rtc::scoped_ptr<DtlsIdentityStoreInterface> dtls_identity_store,
Henrik Lundin64dad832015-05-11 12:44:23 +0200574 const PeerConnectionInterface::RTCConfiguration& rtc_configuration) {
575 bundle_policy_ = rtc_configuration.bundle_policy;
Peter Thatcheraf55ccc2015-05-21 07:48:41 -0700576 rtcp_mux_policy_ = rtc_configuration.rtcp_mux_policy;
Joachim Bauch04e5b492015-05-29 09:40:39 +0200577 SetSslMaxProtocolVersion(options.ssl_max_version);
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000578
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579 // TODO(perkj): Take |constraints| into consideration. Return false if not all
580 // mandatory constraints can be fulfilled. Note that |constraints|
581 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000582 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000583
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000584 if (options.disable_encryption) {
585 dtls_enabled_ = false;
586 } else {
Henrik Boström5e56c592015-08-11 10:33:13 +0200587 // Enable DTLS by default if we have a |dtls_identity_store|.
588 dtls_enabled_ = (dtls_identity_store != nullptr);
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000589 // |constraints| can override the default |dtls_enabled_| value.
590 if (FindConstraint(
591 constraints,
592 MediaConstraintsInterface::kEnableDtlsSrtp,
593 &value, NULL)) {
594 dtls_enabled_ = value;
595 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000596 }
597
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000599 // It takes precendence over the disable_sctp_data_channels
600 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601 if (FindConstraint(
602 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
603 &value, NULL) && value) {
604 LOG(LS_INFO) << "Allowing RTP data engine.";
605 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000606 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000607 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000608 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000609 LOG(LS_INFO) << "Allowing SCTP data engine.";
610 data_channel_type_ = cricket::DCT_SCTP;
611 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000612 }
613 if (data_channel_type_ != cricket::DCT_NONE) {
614 mediastream_signaling_->SetDataChannelFactory(this);
615 }
616
wu@webrtc.orgde305012013-10-31 15:40:38 +0000617 // Find DSCP constraint.
618 if (FindConstraint(
619 constraints,
620 MediaConstraintsInterface::kEnableDscp,
621 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000622 audio_options_.dscp.Set(value);
623 video_options_.dscp.Set(value);
624 }
625
626 // Find Suspend Below Min Bitrate constraint.
627 if (FindConstraint(
628 constraints,
629 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
630 &value,
631 NULL)) {
632 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000633 }
634
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000635 SetOptionFromOptionalConstraint(constraints,
636 MediaConstraintsInterface::kScreencastMinBitrate,
637 &video_options_.screencast_min_bitrate);
638
639 // Find constraints for cpu overuse detection.
640 SetOptionFromOptionalConstraint(constraints,
641 MediaConstraintsInterface::kCpuUnderuseThreshold,
642 &video_options_.cpu_underuse_threshold);
643 SetOptionFromOptionalConstraint(constraints,
644 MediaConstraintsInterface::kCpuOveruseThreshold,
645 &video_options_.cpu_overuse_threshold);
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000646 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000647 MediaConstraintsInterface::kCpuOveruseDetection,
648 &video_options_.cpu_overuse_detection);
649 SetOptionFromOptionalConstraint(constraints,
650 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
651 &video_options_.cpu_overuse_encode_usage);
652 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000653 MediaConstraintsInterface::kCpuUnderuseEncodeRsdThreshold,
654 &video_options_.cpu_underuse_encode_rsd_threshold);
655 SetOptionFromOptionalConstraint(constraints,
656 MediaConstraintsInterface::kCpuOveruseEncodeRsdThreshold,
657 &video_options_.cpu_overuse_encode_rsd_threshold);
buildbot@webrtc.orgdb563902014-06-13 13:05:48 +0000658
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000659 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +0000660 MediaConstraintsInterface::kNumUnsignalledRecvStreams,
661 &video_options_.unsignalled_recv_stream_limit);
662 if (video_options_.unsignalled_recv_stream_limit.IsSet()) {
663 int stream_limit;
664 video_options_.unsignalled_recv_stream_limit.Get(&stream_limit);
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000665 stream_limit = std::min(kMaxUnsignalledRecvStreams, stream_limit);
666 stream_limit = std::max(0, stream_limit);
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +0000667 video_options_.unsignalled_recv_stream_limit.Set(stream_limit);
668 }
669
670 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000671 MediaConstraintsInterface::kHighStartBitrate,
672 &video_options_.video_start_bitrate);
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000673
674 if (FindConstraint(
675 constraints,
676 MediaConstraintsInterface::kVeryHighBitrate,
677 &value,
678 NULL)) {
679 video_options_.video_highest_bitrate.Set(
680 cricket::VideoOptions::VERY_HIGH);
681 } else if (FindConstraint(
682 constraints,
683 MediaConstraintsInterface::kHighBitrate,
684 &value,
685 NULL)) {
686 video_options_.video_highest_bitrate.Set(
687 cricket::VideoOptions::HIGH);
688 }
689
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000690 SetOptionFromOptionalConstraint(constraints,
691 MediaConstraintsInterface::kCombinedAudioVideoBwe,
692 &audio_options_.combined_audio_video_bwe);
693
Henrik Lundin64dad832015-05-11 12:44:23 +0200694 audio_options_.audio_jitter_buffer_max_packets.Set(
695 rtc_configuration.audio_jitter_buffer_max_packets);
696
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200697 audio_options_.audio_jitter_buffer_fast_accelerate.Set(
698 rtc_configuration.audio_jitter_buffer_fast_accelerate);
699
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 const cricket::VideoCodec default_codec(
701 JsepSessionDescription::kDefaultVideoCodecId,
702 JsepSessionDescription::kDefaultVideoCodecName,
703 JsepSessionDescription::kMaxVideoCodecWidth,
704 JsepSessionDescription::kMaxVideoCodecHeight,
705 JsepSessionDescription::kDefaultVideoCodecFramerate,
706 JsepSessionDescription::kDefaultVideoCodecPreference);
707 channel_manager_->SetDefaultVideoEncoderConfig(
708 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000709
710 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
711 signaling_thread(),
712 channel_manager_,
713 mediastream_signaling_,
Henrik Boström5e56c592015-08-11 10:33:13 +0200714 dtls_identity_store.Pass(),
wu@webrtc.org91053e72013-08-10 07:18:04 +0000715 this,
716 id(),
717 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000718 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000719
720 webrtc_session_desc_factory_->SignalIdentityReady.connect(
721 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000722
wu@webrtc.org97077a32013-10-25 21:18:33 +0000723 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000724 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000725 }
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +0000726 port_allocator()->set_candidate_filter(
Henrik Lundin64dad832015-05-11 12:44:23 +0200727 ConvertIceTransportTypeToCandidateFilter(rtc_configuration.type));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728 return true;
729}
730
731void WebRtcSession::Terminate() {
732 SetState(STATE_RECEIVEDTERMINATE);
733 RemoveUnusedChannelsAndTransports(NULL);
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +0000734 ASSERT(!voice_channel_);
735 ASSERT(!video_channel_);
736 ASSERT(!data_channel_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737}
738
739bool WebRtcSession::StartCandidatesAllocation() {
740 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
741 // from TransportProxy to start gathering ice candidates.
742 SpeculativelyConnectAllTransportChannels();
743 if (!saved_candidates_.empty()) {
744 // If there are saved candidates which arrived before local description is
745 // set, copy those to remote description.
746 CopySavedCandidates(remote_desc_.get());
747 }
748 // Push remote candidates present in remote description to transport channels.
749 UseCandidatesInSessionDescription(remote_desc_.get());
750 return true;
751}
752
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000753void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
754 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000755}
756
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000757cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
758 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000759}
760
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000761bool WebRtcSession::GetSslRole(rtc::SSLRole* role) {
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000762 if (local_description() == NULL || remote_description() == NULL) {
763 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
764 << "SSL Role of the session.";
765 return false;
766 }
767
768 // TODO(mallinath) - Return role of each transport, as role may differ from
769 // one another.
770 // In current implementaion we just return the role of first transport in the
771 // transport map.
772 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
773 iter != transport_proxies().end(); ++iter) {
774 if (iter->second->impl()) {
775 return iter->second->impl()->GetSslRole(role);
776 }
777 }
778 return false;
779}
780
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000781void WebRtcSession::CreateOffer(
782 CreateSessionDescriptionObserver* observer,
783 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
784 webrtc_session_desc_factory_->CreateOffer(observer, options);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000785}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000786
wu@webrtc.org91053e72013-08-10 07:18:04 +0000787void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
788 const MediaConstraintsInterface* constraints) {
789 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790}
791
792bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
793 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000794 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000795 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000796
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000797 // Validate SDP.
798 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
799 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800 }
801
802 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000803 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 if (state() == STATE_INIT && action == kOffer) {
805 set_initiator(true);
806 }
807
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000808 cricket::SecurePolicy sdes_policy =
809 webrtc_session_desc_factory_->SdesPolicy();
810 cricket::CryptoType crypto_required = dtls_enabled_ ?
811 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
812 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000814 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000815
816 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000817 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818
819 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000820 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 // TODO(mallinath) - Handle CreateChannel failure, as new local description
822 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000823 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824 }
825
826 // Remove channel and transport proxies, if MediaContentDescription is
827 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000828 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000830 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831 return false;
832 }
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +0000833
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 // Kick starting the ice candidates allocation.
835 StartCandidatesAllocation();
836
837 // Update state and SSRC of local MediaStreams and DataChannels based on the
838 // local session description.
839 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
840
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000841 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000842 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
843 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
844 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000845 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000846 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 }
848 return true;
849}
850
851bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
852 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000853 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000854 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000855
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000856 // Validate SDP.
857 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
858 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000859 }
860
861 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000862 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000863 if (action == kOffer && !CreateChannels(desc->description())) {
864 // TODO(mallinath) - Handle CreateChannel failure, as new local description
865 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000866 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000867 }
868
869 // Remove channel and transport proxies, if MediaContentDescription is
870 // rejected.
871 RemoveUnusedChannelsAndTransports(desc->description());
872
873 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
874 // is called.
875 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000876 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877 return false;
878 }
879
880 // Update remote MediaStreams.
881 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
882 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000883 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884 }
885
886 // Copy all saved candidates.
887 CopySavedCandidates(desc);
honghaiz503726c2015-07-31 12:37:38 -0700888
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 // Check if this new SessionDescription contains new ice ufrag and password
890 // that indicates the remote peer requests ice restart.
honghaiz503726c2015-07-31 12:37:38 -0700891 bool ice_restart =
892 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(), desc);
893 // We retain all received candidates only if ICE is not restarted.
894 // When ICE is restarted, all previous candidates belong to an old generation
895 // and should not be kept.
896 if (!ice_restart) {
897 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
898 remote_desc_.get(), desc);
899 }
900
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000901 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000902
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000903 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000904 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
905 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
906 }
907
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000909 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000911
912 // Set the the ICE connection state to connecting since the connection may
913 // become writable with peer reflexive candidates before any remote candidate
914 // is signaled.
915 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
916 // is to have a new signal the indicates a change in checking state from the
917 // transport and expose a new checking() member from transport that can be
918 // read to determine the current checking state. The existing SignalConnecting
919 // actually means "gathering candidates", so cannot be be used here.
920 if (desc->type() != SessionDescriptionInterface::kOffer &&
921 ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew) {
922 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
923 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924 return true;
925}
926
927bool WebRtcSession::UpdateSessionState(
928 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929 std::string* err_desc) {
930 // If there's already a pending error then no state transition should happen.
931 // But all call-sites should be verifying this before calling us!
932 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000933 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000935 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
936 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 }
938 SetState(source == cricket::CS_LOCAL ?
939 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000940 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
941 SetError(BaseSession::ERROR_CONTENT, *err_desc);
942 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000944 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 }
946 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000947 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
948 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 }
950 EnableChannels();
951 SetState(source == cricket::CS_LOCAL ?
952 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000953 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
954 SetError(BaseSession::ERROR_CONTENT, *err_desc);
955 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000957 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958 }
959 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000960 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
961 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962 }
963 MaybeEnableMuxingSupport();
964 EnableChannels();
965 SetState(source == cricket::CS_LOCAL ?
966 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000967 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
968 SetError(BaseSession::ERROR_CONTENT, *err_desc);
969 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000971 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972 }
973 }
974 return true;
975}
976
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000977bool WebRtcSession::PushdownMediaDescription(
978 cricket::ContentAction action,
979 cricket::ContentSource source,
980 std::string* err) {
981 auto set_content = [this, action, source, err](cricket::BaseChannel* ch) {
982 if (!ch) {
983 return true;
984 } else if (source == cricket::CS_LOCAL) {
985 return ch->PushdownLocalDescription(
986 base_local_description(), action, err);
987 } else {
988 return ch->PushdownRemoteDescription(
989 base_remote_description(), action, err);
990 }
991 };
992
993 return (set_content(voice_channel()) &&
994 set_content(video_channel()) &&
995 set_content(data_channel()));
996}
997
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
999 if (type == SessionDescriptionInterface::kOffer) {
1000 return WebRtcSession::kOffer;
1001 } else if (type == SessionDescriptionInterface::kPrAnswer) {
1002 return WebRtcSession::kPrAnswer;
1003 } else if (type == SessionDescriptionInterface::kAnswer) {
1004 return WebRtcSession::kAnswer;
1005 }
1006 ASSERT(false && "unknown action type");
1007 return WebRtcSession::kOffer;
1008}
1009
pthatcher@webrtc.orgc04a97f2015-03-16 19:31:40 +00001010bool WebRtcSession::GetTransportStats(cricket::SessionStats* stats) {
1011 ASSERT(signaling_thread()->IsCurrent());
1012
1013 const auto get_transport_stats = [stats](const std::string& content_name,
1014 cricket::Transport* transport) {
1015 const std::string& transport_id = transport->content_name();
1016 stats->proxy_to_transport[content_name] = transport_id;
1017 if (stats->transport_stats.find(transport_id)
1018 != stats->transport_stats.end()) {
1019 // Transport stats already done for this transport.
1020 return true;
1021 }
1022
1023 cricket::TransportStats tstats;
1024 if (!transport->GetStats(&tstats)) {
1025 return false;
1026 }
1027
1028 stats->transport_stats[transport_id] = tstats;
1029 return true;
1030 };
1031
1032 for (const auto& kv : transport_proxies()) {
1033 cricket::Transport* transport = kv.second->impl();
1034 if (transport && !get_transport_stats(kv.first, transport)) {
1035 return false;
1036 }
1037 }
1038 return true;
1039}
1040
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
1042 if (state() == STATE_INIT) {
1043 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1044 << "without any offer (local or remote) "
1045 << "session description.";
1046 return false;
1047 }
1048
1049 if (!candidate) {
1050 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
1051 return false;
1052 }
1053
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001054 bool valid = false;
1055 if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
1056 if (valid) {
1057 LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
1058 saved_candidates_.push_back(
1059 new JsepIceCandidate(candidate->sdp_mid(),
1060 candidate->sdp_mline_index(),
1061 candidate->candidate()));
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +00001062 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001063 return valid;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064 }
1065
1066 // Add this candidate to the remote session description.
1067 if (!remote_desc_->AddCandidate(candidate)) {
1068 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
1069 return false;
1070 }
1071
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001072 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073}
1074
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001075bool WebRtcSession::SetIceTransports(
1076 PeerConnectionInterface::IceTransportsType type) {
1077 return port_allocator()->set_candidate_filter(
1078 ConvertIceTransportTypeToCandidateFilter(type));
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001079}
1080
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001081bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001082 if (!base_local_description())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 return false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001084 return webrtc::GetTrackIdBySsrc(base_local_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085}
1086
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001087bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001088 if (!base_remote_description())
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001089 return false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001090 return webrtc::GetTrackIdBySsrc(base_remote_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091}
1092
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001093std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001095 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096 return desc.str();
1097}
1098
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001099void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
1100 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 ASSERT(signaling_thread()->IsCurrent());
1102 if (!voice_channel_) {
1103 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
1104 return;
1105 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001106 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
1107 // SetRenderer() can fail if the ssrc does not match any playout channel.
1108 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
1109 return;
1110 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001111 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
1112 // Allow that SetOutputScaling fail if |enable| is false but assert
1113 // otherwise. This in the normal case when the underlying media channel has
1114 // already been deleted.
1115 ASSERT(enable == false);
1116 }
1117}
1118
1119void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001120 const cricket::AudioOptions& options,
1121 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122 ASSERT(signaling_thread()->IsCurrent());
1123 if (!voice_channel_) {
1124 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
1125 return;
1126 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001127 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
1128 // SetRenderer() can fail if the ssrc does not match any send channel.
1129 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
1130 return;
1131 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132 if (!voice_channel_->MuteStream(ssrc, !enable)) {
1133 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1134 // This in the normal case when the underlying media channel has already
1135 // been deleted.
1136 ASSERT(enable == false);
1137 return;
1138 }
1139 if (enable)
1140 voice_channel_->SetChannelOptions(options);
1141}
1142
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001143void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
1144 ASSERT(signaling_thread()->IsCurrent());
1145 ASSERT(volume >= 0 && volume <= 10);
1146 if (!voice_channel_) {
1147 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
1148 return;
1149 }
1150
1151 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
1152 ASSERT(false);
1153}
1154
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001155bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1156 cricket::VideoCapturer* camera) {
1157 ASSERT(signaling_thread()->IsCurrent());
1158
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001159 if (!video_channel_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1161 // support video.
1162 LOG(LS_WARNING) << "Video not used in this call.";
1163 return false;
1164 }
1165 if (!video_channel_->SetCapturer(ssrc, camera)) {
1166 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1167 // This in the normal case when the underlying media channel has already
1168 // been deleted.
1169 ASSERT(camera == NULL);
1170 return false;
1171 }
1172 return true;
1173}
1174
1175void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1176 bool enable,
1177 cricket::VideoRenderer* renderer) {
1178 ASSERT(signaling_thread()->IsCurrent());
1179 if (!video_channel_) {
1180 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1181 return;
1182 }
1183 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1184 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1185 // This in the normal case when the underlying media channel has already
1186 // been deleted.
1187 ASSERT(renderer == NULL);
1188 }
1189}
1190
1191void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1192 const cricket::VideoOptions* options) {
1193 ASSERT(signaling_thread()->IsCurrent());
1194 if (!video_channel_) {
1195 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1196 return;
1197 }
1198 if (!video_channel_->MuteStream(ssrc, !enable)) {
1199 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1200 // This in the normal case when the underlying media channel has already
1201 // been deleted.
1202 ASSERT(enable == false);
1203 return;
1204 }
1205 if (enable && options)
1206 video_channel_->SetChannelOptions(*options);
1207}
1208
1209bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1210 ASSERT(signaling_thread()->IsCurrent());
1211 if (!voice_channel_) {
1212 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1213 return false;
1214 }
1215 uint32 send_ssrc = 0;
1216 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1217 // exists.
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001218 if (!GetAudioSsrcByTrackId(base_local_description(), track_id,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001219 &send_ssrc)) {
1220 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1221 return false;
1222 }
1223 return voice_channel_->CanInsertDtmf();
1224}
1225
1226bool WebRtcSession::InsertDtmf(const std::string& track_id,
1227 int code, int duration) {
1228 ASSERT(signaling_thread()->IsCurrent());
1229 if (!voice_channel_) {
1230 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1231 return false;
1232 }
1233 uint32 send_ssrc = 0;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001234 if (!VERIFY(GetAudioSsrcByTrackId(base_local_description(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 track_id, &send_ssrc))) {
1236 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1237 return false;
1238 }
1239 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1240 cricket::DF_SEND)) {
1241 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1242 return false;
1243 }
1244 return true;
1245}
1246
1247sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1248 return &SignalVoiceChannelDestroyed;
1249}
1250
wu@webrtc.org78187522013-10-07 23:32:02 +00001251bool WebRtcSession::SendData(const cricket::SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001252 const rtc::Buffer& payload,
wu@webrtc.org78187522013-10-07 23:32:02 +00001253 cricket::SendDataResult* result) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001254 if (!data_channel_) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001255 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1256 return false;
1257 }
1258 return data_channel_->SendData(params, payload, result);
1259}
1260
1261bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001262 if (!data_channel_) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001263 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1264 return false;
1265 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001266 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1267 &DataChannel::OnChannelReady);
1268 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1269 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001270 return true;
1271}
1272
1273void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001274 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001275 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1276 return;
1277 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001278 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1279 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1280}
1281
bemasc@webrtc.org9b5467e2014-12-04 23:16:52 +00001282void WebRtcSession::AddSctpDataStream(int sid) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001283 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001284 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1285 return;
1286 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001287 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1288 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001289}
1290
bemasc@webrtc.org9b5467e2014-12-04 23:16:52 +00001291void WebRtcSession::RemoveSctpDataStream(int sid) {
1292 mediastream_signaling_->RemoveSctpDataChannel(sid);
jiayl@webrtc.org2eaac182014-06-17 16:02:46 +00001293
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001294 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001295 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1296 << "NULL.";
1297 return;
1298 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001299 data_channel_->RemoveRecvStream(sid);
1300 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001301}
1302
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001303bool WebRtcSession::ReadyToSendData() const {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001304 return data_channel_ && data_channel_->ready_to_send_data();
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001305}
1306
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001307rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001308 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001309 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 if (state() == STATE_RECEIVEDTERMINATE) {
1311 return NULL;
1312 }
1313 if (data_channel_type_ == cricket::DCT_NONE) {
1314 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1315 return NULL;
1316 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001317 InternalDataChannelInit new_config =
1318 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319 if (data_channel_type_ == cricket::DCT_SCTP) {
1320 if (new_config.id < 0) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001321 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001322 if (GetSslRole(&role) &&
1323 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1325 return NULL;
1326 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001327 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1329 << "because the id is already in use or out of range.";
1330 return NULL;
1331 }
1332 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001333
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001334 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001335 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001336 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339 return channel;
1340}
1341
1342cricket::DataChannelType WebRtcSession::data_channel_type() const {
1343 return data_channel_type_;
1344}
1345
wu@webrtc.org91053e72013-08-10 07:18:04 +00001346bool WebRtcSession::IceRestartPending() const {
1347 return ice_restart_latch_->Get();
1348}
1349
1350void WebRtcSession::ResetIceRestartLatch() {
1351 ice_restart_latch_->Reset();
1352}
1353
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001354void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001355 SetIdentity(identity);
1356}
1357
1358bool WebRtcSession::waiting_for_identity() const {
1359 return webrtc_session_desc_factory_->waiting_for_identity();
1360}
1361
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001362void WebRtcSession::SetIceConnectionState(
1363 PeerConnectionInterface::IceConnectionState state) {
1364 if (ice_connection_state_ == state) {
1365 return;
1366 }
1367
1368 // ASSERT that the requested transition is allowed. Note that
1369 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1370 // within PeerConnection). This switch statement should compile away when
1371 // ASSERTs are disabled.
1372 switch (ice_connection_state_) {
1373 case PeerConnectionInterface::kIceConnectionNew:
1374 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1375 break;
1376 case PeerConnectionInterface::kIceConnectionChecking:
1377 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1378 state == PeerConnectionInterface::kIceConnectionConnected);
1379 break;
1380 case PeerConnectionInterface::kIceConnectionConnected:
1381 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1382 state == PeerConnectionInterface::kIceConnectionChecking ||
1383 state == PeerConnectionInterface::kIceConnectionCompleted);
1384 break;
1385 case PeerConnectionInterface::kIceConnectionCompleted:
1386 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1387 state == PeerConnectionInterface::kIceConnectionDisconnected);
1388 break;
1389 case PeerConnectionInterface::kIceConnectionFailed:
1390 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1391 break;
1392 case PeerConnectionInterface::kIceConnectionDisconnected:
1393 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1394 state == PeerConnectionInterface::kIceConnectionConnected ||
1395 state == PeerConnectionInterface::kIceConnectionCompleted ||
1396 state == PeerConnectionInterface::kIceConnectionFailed);
1397 break;
1398 case PeerConnectionInterface::kIceConnectionClosed:
1399 ASSERT(false);
1400 break;
1401 default:
1402 ASSERT(false);
1403 break;
1404 }
1405
1406 ice_connection_state_ = state;
1407 if (ice_observer_) {
1408 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1409 }
1410}
1411
1412void WebRtcSession::OnTransportRequestSignaling(
1413 cricket::Transport* transport) {
1414 ASSERT(signaling_thread()->IsCurrent());
1415 transport->OnSignalingReady();
1416 if (ice_observer_) {
1417 ice_observer_->OnIceGatheringChange(
1418 PeerConnectionInterface::kIceGatheringGathering);
1419 }
1420}
1421
1422void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1423 ASSERT(signaling_thread()->IsCurrent());
1424 // start monitoring for the write state of the transport.
1425 OnTransportWritable(transport);
1426}
1427
1428void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1429 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001431 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 } else if (transport->HasChannels()) {
1433 // If the current state is Connected or Completed, then there were writable
1434 // channels but now there are not, so the next state must be Disconnected.
1435 if (ice_connection_state_ ==
1436 PeerConnectionInterface::kIceConnectionConnected ||
1437 ice_connection_state_ ==
1438 PeerConnectionInterface::kIceConnectionCompleted) {
1439 SetIceConnectionState(
1440 PeerConnectionInterface::kIceConnectionDisconnected);
1441 }
1442 }
1443}
1444
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001445void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1446 ASSERT(signaling_thread()->IsCurrent());
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001447 PeerConnectionInterface::IceConnectionState old_state = ice_connection_state_;
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001448 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001449 // Only report once when Ice connection is completed.
1450 if (old_state != PeerConnectionInterface::kIceConnectionCompleted) {
jbauchac8869e2015-07-03 01:36:14 -07001451 cricket::TransportStats stats;
1452 if (metrics_observer_ && transport->GetStats(&stats)) {
1453 ReportBestConnectionState(stats);
1454 ReportNegotiatedCiphers(stats);
1455 }
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001456 }
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001457}
1458
1459void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1460 ASSERT(signaling_thread()->IsCurrent());
1461 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1462}
1463
Peter Thatcher54360512015-07-08 11:08:35 -07001464void WebRtcSession::OnTransportReceiving(cricket::Transport* transport) {
1465 ASSERT(signaling_thread()->IsCurrent());
1466 // The ice connection is considered receiving if at least one transport is
1467 // receiving on any channels.
1468 bool receiving = false;
1469 for (const auto& kv : transport_proxies()) {
1470 cricket::Transport* transport = kv.second->impl();
1471 if (transport && transport->any_channel_receiving()) {
1472 receiving = true;
1473 break;
1474 }
1475 }
1476 SetIceConnectionReceiving(receiving);
1477}
1478
1479void WebRtcSession::SetIceConnectionReceiving(bool receiving) {
1480 if (ice_connection_receiving_ == receiving) {
1481 return;
1482 }
1483 ice_connection_receiving_ = receiving;
1484 if (ice_observer_) {
1485 ice_observer_->OnIceConnectionReceivingChange(receiving);
1486 }
1487}
1488
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489void WebRtcSession::OnTransportProxyCandidatesReady(
1490 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1491 ASSERT(signaling_thread()->IsCurrent());
1492 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1493}
1494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495void WebRtcSession::OnCandidatesAllocationDone() {
1496 ASSERT(signaling_thread()->IsCurrent());
1497 if (ice_observer_) {
1498 ice_observer_->OnIceGatheringChange(
1499 PeerConnectionInterface::kIceGatheringComplete);
1500 ice_observer_->OnIceComplete();
1501 }
1502}
1503
1504// Enabling voice and video channel.
1505void WebRtcSession::EnableChannels() {
1506 if (voice_channel_ && !voice_channel_->enabled())
1507 voice_channel_->Enable(true);
1508
1509 if (video_channel_ && !video_channel_->enabled())
1510 video_channel_->Enable(true);
1511
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001512 if (data_channel_ && !data_channel_->enabled())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001513 data_channel_->Enable(true);
1514}
1515
1516void WebRtcSession::ProcessNewLocalCandidate(
1517 const std::string& content_name,
1518 const cricket::Candidates& candidates) {
1519 int sdp_mline_index;
1520 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1521 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1522 << content_name << " not found";
1523 return;
1524 }
1525
1526 for (cricket::Candidates::const_iterator citer = candidates.begin();
1527 citer != candidates.end(); ++citer) {
1528 // Use content_name as the candidate media id.
1529 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1530 if (ice_observer_) {
1531 ice_observer_->OnIceCandidate(&candidate);
1532 }
1533 if (local_desc_) {
1534 local_desc_->AddCandidate(&candidate);
1535 }
1536 }
1537}
1538
1539// Returns the media index for a local ice candidate given the content name.
1540bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1541 int* sdp_mline_index) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001542 if (!base_local_description() || !sdp_mline_index)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001543 return false;
1544
1545 bool content_found = false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001546 const ContentInfos& contents = base_local_description()->contents();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 for (size_t index = 0; index < contents.size(); ++index) {
1548 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001549 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001550 content_found = true;
1551 break;
1552 }
1553 }
1554 return content_found;
1555}
1556
1557bool WebRtcSession::UseCandidatesInSessionDescription(
1558 const SessionDescriptionInterface* remote_desc) {
1559 if (!remote_desc)
1560 return true;
1561 bool ret = true;
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001562
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1564 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1565 for (size_t n = 0; n < candidates->count(); ++n) {
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001566 const IceCandidateInterface* candidate = candidates->at(n);
1567 bool valid = false;
1568 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1569 if (valid) {
1570 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
1571 saved_candidates_.push_back(
1572 new JsepIceCandidate(candidate->sdp_mid(),
1573 candidate->sdp_mline_index(),
1574 candidate->candidate()));
1575 }
1576 continue;
1577 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001578 ret = UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 if (!ret)
1580 break;
1581 }
1582 }
1583 return ret;
1584}
1585
1586bool WebRtcSession::UseCandidate(
1587 const IceCandidateInterface* candidate) {
1588
1589 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001590 size_t remote_content_size = base_remote_description()->contents().size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591 if (mediacontent_index >= remote_content_size) {
1592 LOG(LS_ERROR)
1593 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1594 return false;
1595 }
1596
1597 cricket::ContentInfo content =
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001598 base_remote_description()->contents()[mediacontent_index];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001599 std::vector<cricket::Candidate> candidates;
1600 candidates.push_back(candidate->candidate());
1601 // Invoking BaseSession method to handle remote candidates.
1602 std::string error;
1603 if (OnRemoteCandidates(content.name, candidates, &error)) {
1604 // Candidates successfully submitted for checking.
1605 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1606 ice_connection_state_ ==
1607 PeerConnectionInterface::kIceConnectionDisconnected) {
1608 // If state is New, then the session has just gotten its first remote ICE
1609 // candidates, so go to Checking.
1610 // If state is Disconnected, the session is re-using old candidates or
1611 // receiving additional ones, so go to Checking.
1612 // If state is Connected, stay Connected.
1613 // TODO(bemasc): If state is Connected, and the new candidates are for a
1614 // newly added transport, then the state actually _should_ move to
1615 // checking. Add a way to distinguish that case.
1616 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1617 }
1618 // TODO(bemasc): If state is Completed, go back to Connected.
1619 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001620 if (!error.empty()) {
1621 LOG(LS_WARNING) << error;
1622 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001623 }
1624 return true;
1625}
1626
1627void WebRtcSession::RemoveUnusedChannelsAndTransports(
1628 const SessionDescription* desc) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001629 // Destroy video_channel_ first since it may have a pointer to the
1630 // voice_channel_.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001631 const cricket::ContentInfo* video_info =
1632 cricket::GetFirstVideoContent(desc);
1633 if ((!video_info || video_info->rejected) && video_channel_) {
1634 mediastream_signaling_->OnVideoChannelClose();
1635 SignalVideoChannelDestroyed();
1636 const std::string content_name = video_channel_->content_name();
1637 channel_manager_->DestroyVideoChannel(video_channel_.release());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001638 DestroyTransportProxy(content_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001639 }
1640
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001641 const cricket::ContentInfo* voice_info =
1642 cricket::GetFirstAudioContent(desc);
1643 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1644 mediastream_signaling_->OnAudioChannelClose();
1645 SignalVoiceChannelDestroyed();
1646 const std::string content_name = voice_channel_->content_name();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001647 channel_manager_->DestroyVoiceChannel(voice_channel_.release(),
1648 video_channel_.get());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001649 DestroyTransportProxy(content_name);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001650 }
1651
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652 const cricket::ContentInfo* data_info =
1653 cricket::GetFirstDataContent(desc);
1654 if ((!data_info || data_info->rejected) && data_channel_) {
1655 mediastream_signaling_->OnDataChannelClose();
1656 SignalDataChannelDestroyed();
1657 const std::string content_name = data_channel_->content_name();
1658 channel_manager_->DestroyDataChannel(data_channel_.release());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001659 DestroyTransportProxy(content_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001660 }
1661}
1662
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001663// TODO(mallinath) - Add a correct error code if the channels are not creatued
1664// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001665bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001666 // Creating the media channels and transport proxies.
1667 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1668 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001669 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001670 LOG(LS_ERROR) << "Failed to create voice channel.";
1671 return false;
1672 }
1673 }
1674
1675 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1676 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001677 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001678 LOG(LS_ERROR) << "Failed to create video channel.";
1679 return false;
1680 }
1681 }
1682
1683 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1684 if (data_channel_type_ != cricket::DCT_NONE &&
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001685 data && !data->rejected && !data_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001686 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687 LOG(LS_ERROR) << "Failed to create data channel.";
1688 return false;
1689 }
1690 }
1691
Peter Thatcheraf55ccc2015-05-21 07:48:41 -07001692 if (rtcp_mux_policy_ == PeerConnectionInterface::kRtcpMuxPolicyRequire) {
1693 if (voice_channel()) {
1694 voice_channel()->ActivateRtcpMux();
1695 }
1696 if (video_channel()) {
1697 video_channel()->ActivateRtcpMux();
1698 }
1699 if (data_channel()) {
1700 data_channel()->ActivateRtcpMux();
1701 }
1702 }
1703
Donald Curtis0e209b02015-03-24 09:29:54 -07001704 // Enable bundle before when kMaxBundle policy is in effect.
1705 if (bundle_policy_ == PeerConnectionInterface::kBundlePolicyMaxBundle) {
Peter Thatcher4eddf182015-04-30 10:55:59 -07001706 const cricket::ContentGroup* bundle_group = desc->GetGroupByName(
1707 cricket::GROUP_TYPE_BUNDLE);
1708 if (!bundle_group) {
Donald Curtis0e209b02015-03-24 09:29:54 -07001709 LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
1710 return false;
1711 }
Peter Thatcher4eddf182015-04-30 10:55:59 -07001712 if (!BaseSession::BundleContentGroup(bundle_group)) {
Donald Curtis0e209b02015-03-24 09:29:54 -07001713 LOG(LS_WARNING) << "max-bundle failed to enable bundling.";
1714 return false;
1715 }
1716 }
1717
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 return true;
1719}
1720
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001721bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
Jelena Marusicc28a8962015-05-29 15:05:44 +02001723 this, content->name, true, audio_options_));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001724 if (!voice_channel_) {
wu@webrtc.orgde305012013-10-31 15:40:38 +00001725 return false;
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001726 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001727
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001728 voice_channel_->SignalDtlsSetupFailure.connect(
1729 this, &WebRtcSession::OnDtlsSetupFailure);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001730 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731}
1732
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001733bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734 video_channel_.reset(channel_manager_->CreateVideoChannel(
buildbot@webrtc.org1ecbe452014-10-14 20:29:28 +00001735 this, content->name, true, video_options_, voice_channel_.get()));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001736 if (!video_channel_) {
1737 return false;
1738 }
1739
1740 video_channel_->SignalDtlsSetupFailure.connect(
1741 this, &WebRtcSession::OnDtlsSetupFailure);
1742 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001743}
1744
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001745bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001746 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001747 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001748 this, content->name, !sctp, data_channel_type_));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001749 if (!data_channel_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001750 return false;
1751 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001752
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001753 if (sctp) {
1754 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001755 data_channel_->SignalDataReceived.connect(
1756 this, &WebRtcSession::OnDataChannelMessageReceived);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +00001757 data_channel_->SignalStreamClosedRemotely.connect(
1758 mediastream_signaling_,
1759 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001760 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001761
1762 data_channel_->SignalDtlsSetupFailure.connect(
1763 this, &WebRtcSession::OnDtlsSetupFailure);
wu@webrtc.org91053e72013-08-10 07:18:04 +00001764 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765}
1766
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001767void WebRtcSession::OnDtlsSetupFailure(cricket::BaseChannel*, bool rtcp) {
1768 SetError(BaseSession::ERROR_TRANSPORT, rtcp ? kDtlsSetupFailureRtcp :
1769 kDtlsSetupFailureRtp);
1770}
1771
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001772void WebRtcSession::CopySavedCandidates(
1773 SessionDescriptionInterface* dest_desc) {
1774 if (!dest_desc) {
1775 ASSERT(false);
1776 return;
1777 }
1778 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1779 dest_desc->AddCandidate(saved_candidates_[i]);
1780 delete saved_candidates_[i];
1781 }
1782 saved_candidates_.clear();
1783}
1784
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001785void WebRtcSession::OnDataChannelMessageReceived(
1786 cricket::DataChannel* channel,
1787 const cricket::ReceiveDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001788 const rtc::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001789 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001790 if (params.type == cricket::DMT_CONTROL &&
1791 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1792 // Received CONTROL on unused sid, process as an OPEN message.
1793 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001795 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796}
1797
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001798// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001799bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001800 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1801 if (!bundle_enabled)
1802 return true;
1803
1804 const cricket::ContentGroup* bundle_group =
1805 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1806 ASSERT(bundle_group != NULL);
1807
1808 const cricket::ContentInfos& contents = desc->contents();
1809 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1810 citer != contents.end(); ++citer) {
1811 const cricket::ContentInfo* content = (&*citer);
1812 ASSERT(content != NULL);
1813 if (bundle_group->HasContentName(content->name) &&
1814 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1815 if (!HasRtcpMuxEnabled(content))
1816 return false;
1817 }
1818 }
1819 // RTCP-MUX is enabled in all the contents.
1820 return true;
1821}
1822
1823bool WebRtcSession::HasRtcpMuxEnabled(
1824 const cricket::ContentInfo* content) {
1825 const cricket::MediaContentDescription* description =
1826 static_cast<cricket::MediaContentDescription*>(content->description);
1827 return description->rtcp_mux();
1828}
1829
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001830bool WebRtcSession::ValidateSessionDescription(
1831 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001832 cricket::ContentSource source, std::string* err_desc) {
1833 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001834 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001835 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001836 }
1837
1838 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001839 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001840 }
1841
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001842 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001843 Action action = GetAction(sdesc->type());
1844 if (source == cricket::CS_LOCAL) {
1845 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001846 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001847 } else {
1848 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001849 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001850 }
1851
1852 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001853 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001854 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1855 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001856 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001857 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001858 }
1859
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001860 // Verify ice-ufrag and ice-pwd.
1861 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001862 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001863 }
1864
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001865 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001866 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001867 }
1868
1869 // Verify m-lines in Answer when compared against Offer.
1870 if (action == kAnswer) {
1871 const cricket::SessionDescription* offer_desc =
1872 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1873 local_description()->description();
1874 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001875 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001876 }
1877 }
1878
1879 return true;
1880}
1881
1882bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1883 return ((action == kOffer && state() == STATE_INIT) ||
1884 // update local offer
1885 (action == kOffer && state() == STATE_SENTINITIATE) ||
1886 // update the current ongoing session.
1887 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1888 (action == kOffer && state() == STATE_SENTACCEPT) ||
1889 (action == kOffer && state() == STATE_INPROGRESS) ||
1890 // accept remote offer
1891 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1892 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1893 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1894 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1895}
1896
1897bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1898 return ((action == kOffer && state() == STATE_INIT) ||
1899 // update remote offer
1900 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1901 // update the current ongoing session
1902 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1903 (action == kOffer && state() == STATE_SENTACCEPT) ||
1904 (action == kOffer && state() == STATE_INPROGRESS) ||
1905 // accept local offer
1906 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1907 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1908 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1909 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1910}
1911
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001912std::string WebRtcSession::GetSessionErrorMsg() {
1913 std::ostringstream desc;
1914 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1915 desc << kSessionErrorDesc << error_desc() << ".";
1916 return desc.str();
1917}
1918
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001919// We need to check the local/remote description for the Transport instead of
1920// the session, because a new Transport added during renegotiation may have
1921// them unset while the session has them set from the previous negotiation.
1922// Not doing so may trigger the auto generation of transport description and
1923// mess up DTLS identity information, ICE credential, etc.
1924bool WebRtcSession::ReadyToUseRemoteCandidate(
1925 const IceCandidateInterface* candidate,
1926 const SessionDescriptionInterface* remote_desc,
1927 bool* valid) {
1928 *valid = true;;
1929 cricket::TransportProxy* transport_proxy = NULL;
1930
1931 const SessionDescriptionInterface* current_remote_desc =
1932 remote_desc ? remote_desc : remote_description();
1933
1934 if (!current_remote_desc)
1935 return false;
1936
1937 size_t mediacontent_index =
1938 static_cast<size_t>(candidate->sdp_mline_index());
1939 size_t remote_content_size =
1940 current_remote_desc->description()->contents().size();
1941 if (mediacontent_index >= remote_content_size) {
1942 LOG(LS_ERROR)
1943 << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1944
1945 *valid = false;
1946 return false;
1947 }
1948
1949 cricket::ContentInfo content =
1950 current_remote_desc->description()->contents()[mediacontent_index];
1951 transport_proxy = GetTransportProxy(content.name);
1952
1953 return transport_proxy && transport_proxy->local_description_set() &&
1954 transport_proxy->remote_description_set();
1955}
1956
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001957// Walk through the ConnectionInfos to gather best connection usage
1958// for IPv4 and IPv6.
jbauchac8869e2015-07-03 01:36:14 -07001959void WebRtcSession::ReportBestConnectionState(
1960 const cricket::TransportStats& stats) {
1961 DCHECK(metrics_observer_ != NULL);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001962 for (cricket::TransportChannelStatsList::const_iterator it =
1963 stats.channel_stats.begin();
1964 it != stats.channel_stats.end(); ++it) {
1965 for (cricket::ConnectionInfos::const_iterator it_info =
1966 it->connection_infos.begin();
1967 it_info != it->connection_infos.end(); ++it_info) {
1968 if (!it_info->best_connection) {
1969 continue;
1970 }
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07001971
1972 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
1973 const cricket::Candidate& local = it_info->local_candidate;
1974 const cricket::Candidate& remote = it_info->remote_candidate;
1975
1976 // Increment the counter for IceCandidatePairType.
1977 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
1978 (local.type() == RELAY_PORT_TYPE &&
1979 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
1980 type = kEnumCounterIceCandidatePairTypeTcp;
1981 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
1982 type = kEnumCounterIceCandidatePairTypeUdp;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001983 } else {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07001984 CHECK(0);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001985 }
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07001986 metrics_observer_->IncrementEnumCounter(
1987 type, GetIceCandidatePairCounter(local, remote),
1988 kIceCandidatePairMax);
1989
1990 // Increment the counter for IP type.
1991 if (local.address().family() == AF_INET) {
1992 // TODO(guoweis): Remove this next line once IncrementEnumCounter
1993 // implemented for PeerConnectionMetrics.
1994 metrics_observer_->IncrementCounter(kBestConnections_IPv4);
1995
1996 metrics_observer_->IncrementEnumCounter(
1997 kEnumCounterAddressFamily, kBestConnections_IPv4,
1998 kPeerConnectionAddressFamilyCounter_Max);
1999
2000 } else if (local.address().family() == AF_INET6) {
2001 // TODO(guoweis): Remove this next line.
2002 metrics_observer_->IncrementCounter(kBestConnections_IPv6);
2003
2004 metrics_observer_->IncrementEnumCounter(
2005 kEnumCounterAddressFamily, kBestConnections_IPv6,
2006 kPeerConnectionAddressFamilyCounter_Max);
2007 } else {
2008 CHECK(0);
2009 }
2010
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002011 return;
2012 }
2013 }
2014}
2015
jbauchac8869e2015-07-03 01:36:14 -07002016void WebRtcSession::ReportNegotiatedCiphers(
2017 const cricket::TransportStats& stats) {
2018 DCHECK(metrics_observer_ != NULL);
2019 if (!dtls_enabled_ || stats.channel_stats.empty()) {
2020 return;
2021 }
2022
2023 const std::string& srtp_cipher = stats.channel_stats[0].srtp_cipher;
2024 const std::string& ssl_cipher = stats.channel_stats[0].ssl_cipher;
2025 if (srtp_cipher.empty() && ssl_cipher.empty()) {
2026 return;
2027 }
2028
2029 PeerConnectionMetricsName srtp_name;
2030 PeerConnectionMetricsName ssl_name;
2031 if (stats.content_name == cricket::CN_AUDIO) {
2032 srtp_name = kAudioSrtpCipher;
2033 ssl_name = kAudioSslCipher;
2034 } else if (stats.content_name == cricket::CN_VIDEO) {
2035 srtp_name = kVideoSrtpCipher;
2036 ssl_name = kVideoSslCipher;
2037 } else if (stats.content_name == cricket::CN_DATA) {
2038 srtp_name = kDataSrtpCipher;
2039 ssl_name = kDataSslCipher;
2040 } else {
2041 RTC_NOTREACHED();
2042 return;
2043 }
2044
2045 if (!srtp_cipher.empty()) {
2046 metrics_observer_->AddHistogramSample(srtp_name, srtp_cipher);
2047 }
2048 if (!ssl_cipher.empty()) {
2049 metrics_observer_->AddHistogramSample(ssl_name, ssl_cipher);
2050 }
2051}
2052
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002053} // namespace webrtc