blob: be567b88b4a88ddc853833da7a329fc9e95612de [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));
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700728
729 if (rtc_configuration.enable_localhost_ice_candidate) {
730 port_allocator()->set_flags(
731 port_allocator()->flags() |
732 cricket::PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE);
733 }
734
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 return true;
736}
737
738void WebRtcSession::Terminate() {
739 SetState(STATE_RECEIVEDTERMINATE);
740 RemoveUnusedChannelsAndTransports(NULL);
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +0000741 ASSERT(!voice_channel_);
742 ASSERT(!video_channel_);
743 ASSERT(!data_channel_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744}
745
746bool WebRtcSession::StartCandidatesAllocation() {
747 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
748 // from TransportProxy to start gathering ice candidates.
749 SpeculativelyConnectAllTransportChannels();
750 if (!saved_candidates_.empty()) {
751 // If there are saved candidates which arrived before local description is
752 // set, copy those to remote description.
753 CopySavedCandidates(remote_desc_.get());
754 }
755 // Push remote candidates present in remote description to transport channels.
756 UseCandidatesInSessionDescription(remote_desc_.get());
757 return true;
758}
759
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000760void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
761 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762}
763
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000764cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
765 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000766}
767
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000768bool WebRtcSession::GetSslRole(rtc::SSLRole* role) {
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000769 if (local_description() == NULL || remote_description() == NULL) {
770 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
771 << "SSL Role of the session.";
772 return false;
773 }
774
775 // TODO(mallinath) - Return role of each transport, as role may differ from
776 // one another.
777 // In current implementaion we just return the role of first transport in the
778 // transport map.
779 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
780 iter != transport_proxies().end(); ++iter) {
781 if (iter->second->impl()) {
782 return iter->second->impl()->GetSslRole(role);
783 }
784 }
785 return false;
786}
787
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000788void WebRtcSession::CreateOffer(
789 CreateSessionDescriptionObserver* observer,
790 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
791 webrtc_session_desc_factory_->CreateOffer(observer, options);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000792}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793
wu@webrtc.org91053e72013-08-10 07:18:04 +0000794void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
795 const MediaConstraintsInterface* constraints) {
796 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797}
798
799bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
800 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000801 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000802 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000803
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000804 // Validate SDP.
805 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
806 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 }
808
809 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000810 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 if (state() == STATE_INIT && action == kOffer) {
812 set_initiator(true);
813 }
814
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000815 cricket::SecurePolicy sdes_policy =
816 webrtc_session_desc_factory_->SdesPolicy();
817 cricket::CryptoType crypto_required = dtls_enabled_ ?
818 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
819 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000820 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000821 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822
823 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000824 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825
826 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000827 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828 // TODO(mallinath) - Handle CreateChannel failure, as new local description
829 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000830 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831 }
832
833 // Remove channel and transport proxies, if MediaContentDescription is
834 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000835 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000836
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000837 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 return false;
839 }
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +0000840
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 // Kick starting the ice candidates allocation.
842 StartCandidatesAllocation();
843
844 // Update state and SSRC of local MediaStreams and DataChannels based on the
845 // local session description.
846 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
847
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000848 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000849 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
850 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
851 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000853 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000854 }
855 return true;
856}
857
858bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
859 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000860 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000861 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000862
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000863 // Validate SDP.
864 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
865 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866 }
867
868 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000869 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870 if (action == kOffer && !CreateChannels(desc->description())) {
871 // TODO(mallinath) - Handle CreateChannel failure, as new local description
872 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000873 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874 }
875
876 // Remove channel and transport proxies, if MediaContentDescription is
877 // rejected.
878 RemoveUnusedChannelsAndTransports(desc->description());
879
880 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
881 // is called.
882 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000883 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884 return false;
885 }
886
887 // Update remote MediaStreams.
888 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
889 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000890 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891 }
892
893 // Copy all saved candidates.
894 CopySavedCandidates(desc);
honghaiz503726c2015-07-31 12:37:38 -0700895
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896 // Check if this new SessionDescription contains new ice ufrag and password
897 // that indicates the remote peer requests ice restart.
honghaiz503726c2015-07-31 12:37:38 -0700898 bool ice_restart =
899 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(), desc);
900 // We retain all received candidates only if ICE is not restarted.
901 // When ICE is restarted, all previous candidates belong to an old generation
902 // and should not be kept.
903 if (!ice_restart) {
904 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
905 remote_desc_.get(), desc);
906 }
907
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000908 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000909
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000910 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000911 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
912 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
913 }
914
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000916 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000918
919 // Set the the ICE connection state to connecting since the connection may
920 // become writable with peer reflexive candidates before any remote candidate
921 // is signaled.
922 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
923 // is to have a new signal the indicates a change in checking state from the
924 // transport and expose a new checking() member from transport that can be
925 // read to determine the current checking state. The existing SignalConnecting
926 // actually means "gathering candidates", so cannot be be used here.
927 if (desc->type() != SessionDescriptionInterface::kOffer &&
928 ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew) {
929 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
930 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 return true;
932}
933
934bool WebRtcSession::UpdateSessionState(
935 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936 std::string* err_desc) {
937 // If there's already a pending error then no state transition should happen.
938 // But all call-sites should be verifying this before calling us!
939 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000940 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000942 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
943 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944 }
945 SetState(source == cricket::CS_LOCAL ?
946 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000947 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
948 SetError(BaseSession::ERROR_CONTENT, *err_desc);
949 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000951 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 }
953 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000954 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
955 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 }
957 EnableChannels();
958 SetState(source == cricket::CS_LOCAL ?
959 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000960 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
961 SetError(BaseSession::ERROR_CONTENT, *err_desc);
962 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000964 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965 }
966 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000967 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
968 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 }
970 MaybeEnableMuxingSupport();
971 EnableChannels();
972 SetState(source == cricket::CS_LOCAL ?
973 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000974 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
975 SetError(BaseSession::ERROR_CONTENT, *err_desc);
976 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000978 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979 }
980 }
981 return true;
982}
983
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000984bool WebRtcSession::PushdownMediaDescription(
985 cricket::ContentAction action,
986 cricket::ContentSource source,
987 std::string* err) {
988 auto set_content = [this, action, source, err](cricket::BaseChannel* ch) {
989 if (!ch) {
990 return true;
991 } else if (source == cricket::CS_LOCAL) {
992 return ch->PushdownLocalDescription(
993 base_local_description(), action, err);
994 } else {
995 return ch->PushdownRemoteDescription(
996 base_remote_description(), action, err);
997 }
998 };
999
1000 return (set_content(voice_channel()) &&
1001 set_content(video_channel()) &&
1002 set_content(data_channel()));
1003}
1004
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
1006 if (type == SessionDescriptionInterface::kOffer) {
1007 return WebRtcSession::kOffer;
1008 } else if (type == SessionDescriptionInterface::kPrAnswer) {
1009 return WebRtcSession::kPrAnswer;
1010 } else if (type == SessionDescriptionInterface::kAnswer) {
1011 return WebRtcSession::kAnswer;
1012 }
1013 ASSERT(false && "unknown action type");
1014 return WebRtcSession::kOffer;
1015}
1016
pthatcher@webrtc.orgc04a97f2015-03-16 19:31:40 +00001017bool WebRtcSession::GetTransportStats(cricket::SessionStats* stats) {
1018 ASSERT(signaling_thread()->IsCurrent());
1019
1020 const auto get_transport_stats = [stats](const std::string& content_name,
1021 cricket::Transport* transport) {
1022 const std::string& transport_id = transport->content_name();
1023 stats->proxy_to_transport[content_name] = transport_id;
1024 if (stats->transport_stats.find(transport_id)
1025 != stats->transport_stats.end()) {
1026 // Transport stats already done for this transport.
1027 return true;
1028 }
1029
1030 cricket::TransportStats tstats;
1031 if (!transport->GetStats(&tstats)) {
1032 return false;
1033 }
1034
1035 stats->transport_stats[transport_id] = tstats;
1036 return true;
1037 };
1038
1039 for (const auto& kv : transport_proxies()) {
1040 cricket::Transport* transport = kv.second->impl();
1041 if (transport && !get_transport_stats(kv.first, transport)) {
1042 return false;
1043 }
1044 }
1045 return true;
1046}
1047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001048bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
1049 if (state() == STATE_INIT) {
1050 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1051 << "without any offer (local or remote) "
1052 << "session description.";
1053 return false;
1054 }
1055
1056 if (!candidate) {
1057 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
1058 return false;
1059 }
1060
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001061 bool valid = false;
1062 if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
1063 if (valid) {
1064 LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
1065 saved_candidates_.push_back(
1066 new JsepIceCandidate(candidate->sdp_mid(),
1067 candidate->sdp_mline_index(),
1068 candidate->candidate()));
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +00001069 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001070 return valid;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071 }
1072
1073 // Add this candidate to the remote session description.
1074 if (!remote_desc_->AddCandidate(candidate)) {
1075 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
1076 return false;
1077 }
1078
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001079 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080}
1081
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001082bool WebRtcSession::SetIceTransports(
1083 PeerConnectionInterface::IceTransportsType type) {
1084 return port_allocator()->set_candidate_filter(
1085 ConvertIceTransportTypeToCandidateFilter(type));
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001086}
1087
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001088bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001089 if (!base_local_description())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090 return false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001091 return webrtc::GetTrackIdBySsrc(base_local_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092}
1093
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001094bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001095 if (!base_remote_description())
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001096 return false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001097 return webrtc::GetTrackIdBySsrc(base_remote_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098}
1099
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001100std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001102 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001103 return desc.str();
1104}
1105
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001106void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
1107 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108 ASSERT(signaling_thread()->IsCurrent());
1109 if (!voice_channel_) {
1110 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
1111 return;
1112 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001113 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
1114 // SetRenderer() can fail if the ssrc does not match any playout channel.
1115 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
1116 return;
1117 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001118 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
1119 // Allow that SetOutputScaling fail if |enable| is false but assert
1120 // otherwise. This in the normal case when the underlying media channel has
1121 // already been deleted.
1122 ASSERT(enable == false);
1123 }
1124}
1125
1126void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001127 const cricket::AudioOptions& options,
1128 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129 ASSERT(signaling_thread()->IsCurrent());
1130 if (!voice_channel_) {
1131 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
1132 return;
1133 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001134 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
1135 // SetRenderer() can fail if the ssrc does not match any send channel.
1136 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
1137 return;
1138 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001139 if (!voice_channel_->MuteStream(ssrc, !enable)) {
1140 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1141 // This in the normal case when the underlying media channel has already
1142 // been deleted.
1143 ASSERT(enable == false);
1144 return;
1145 }
1146 if (enable)
1147 voice_channel_->SetChannelOptions(options);
1148}
1149
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001150void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
1151 ASSERT(signaling_thread()->IsCurrent());
1152 ASSERT(volume >= 0 && volume <= 10);
1153 if (!voice_channel_) {
1154 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
1155 return;
1156 }
1157
1158 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
1159 ASSERT(false);
1160}
1161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1163 cricket::VideoCapturer* camera) {
1164 ASSERT(signaling_thread()->IsCurrent());
1165
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001166 if (!video_channel_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1168 // support video.
1169 LOG(LS_WARNING) << "Video not used in this call.";
1170 return false;
1171 }
1172 if (!video_channel_->SetCapturer(ssrc, camera)) {
1173 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1174 // This in the normal case when the underlying media channel has already
1175 // been deleted.
1176 ASSERT(camera == NULL);
1177 return false;
1178 }
1179 return true;
1180}
1181
1182void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1183 bool enable,
1184 cricket::VideoRenderer* renderer) {
1185 ASSERT(signaling_thread()->IsCurrent());
1186 if (!video_channel_) {
1187 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1188 return;
1189 }
1190 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1191 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1192 // This in the normal case when the underlying media channel has already
1193 // been deleted.
1194 ASSERT(renderer == NULL);
1195 }
1196}
1197
1198void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1199 const cricket::VideoOptions* options) {
1200 ASSERT(signaling_thread()->IsCurrent());
1201 if (!video_channel_) {
1202 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1203 return;
1204 }
1205 if (!video_channel_->MuteStream(ssrc, !enable)) {
1206 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1207 // This in the normal case when the underlying media channel has already
1208 // been deleted.
1209 ASSERT(enable == false);
1210 return;
1211 }
1212 if (enable && options)
1213 video_channel_->SetChannelOptions(*options);
1214}
1215
1216bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1217 ASSERT(signaling_thread()->IsCurrent());
1218 if (!voice_channel_) {
1219 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1220 return false;
1221 }
1222 uint32 send_ssrc = 0;
1223 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1224 // exists.
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001225 if (!GetAudioSsrcByTrackId(base_local_description(), track_id,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001226 &send_ssrc)) {
1227 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1228 return false;
1229 }
1230 return voice_channel_->CanInsertDtmf();
1231}
1232
1233bool WebRtcSession::InsertDtmf(const std::string& track_id,
1234 int code, int duration) {
1235 ASSERT(signaling_thread()->IsCurrent());
1236 if (!voice_channel_) {
1237 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1238 return false;
1239 }
1240 uint32 send_ssrc = 0;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001241 if (!VERIFY(GetAudioSsrcByTrackId(base_local_description(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242 track_id, &send_ssrc))) {
1243 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1244 return false;
1245 }
1246 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1247 cricket::DF_SEND)) {
1248 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1249 return false;
1250 }
1251 return true;
1252}
1253
1254sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1255 return &SignalVoiceChannelDestroyed;
1256}
1257
wu@webrtc.org78187522013-10-07 23:32:02 +00001258bool WebRtcSession::SendData(const cricket::SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001259 const rtc::Buffer& payload,
wu@webrtc.org78187522013-10-07 23:32:02 +00001260 cricket::SendDataResult* result) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001261 if (!data_channel_) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001262 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1263 return false;
1264 }
1265 return data_channel_->SendData(params, payload, result);
1266}
1267
1268bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001269 if (!data_channel_) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001270 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1271 return false;
1272 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001273 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1274 &DataChannel::OnChannelReady);
1275 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1276 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001277 return true;
1278}
1279
1280void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001281 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001282 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1283 return;
1284 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001285 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1286 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1287}
1288
bemasc@webrtc.org9b5467e2014-12-04 23:16:52 +00001289void WebRtcSession::AddSctpDataStream(int sid) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001290 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001291 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1292 return;
1293 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001294 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1295 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001296}
1297
bemasc@webrtc.org9b5467e2014-12-04 23:16:52 +00001298void WebRtcSession::RemoveSctpDataStream(int sid) {
1299 mediastream_signaling_->RemoveSctpDataChannel(sid);
jiayl@webrtc.org2eaac182014-06-17 16:02:46 +00001300
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001301 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001302 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1303 << "NULL.";
1304 return;
1305 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001306 data_channel_->RemoveRecvStream(sid);
1307 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001308}
1309
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001310bool WebRtcSession::ReadyToSendData() const {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001311 return data_channel_ && data_channel_->ready_to_send_data();
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001312}
1313
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001314rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001315 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001316 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 if (state() == STATE_RECEIVEDTERMINATE) {
1318 return NULL;
1319 }
1320 if (data_channel_type_ == cricket::DCT_NONE) {
1321 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1322 return NULL;
1323 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001324 InternalDataChannelInit new_config =
1325 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 if (data_channel_type_ == cricket::DCT_SCTP) {
1327 if (new_config.id < 0) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001328 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001329 if (GetSslRole(&role) &&
1330 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001331 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1332 return NULL;
1333 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001334 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1336 << "because the id is already in use or out of range.";
1337 return NULL;
1338 }
1339 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001340
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001341 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001342 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001343 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001345
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 return channel;
1347}
1348
1349cricket::DataChannelType WebRtcSession::data_channel_type() const {
1350 return data_channel_type_;
1351}
1352
wu@webrtc.org91053e72013-08-10 07:18:04 +00001353bool WebRtcSession::IceRestartPending() const {
1354 return ice_restart_latch_->Get();
1355}
1356
1357void WebRtcSession::ResetIceRestartLatch() {
1358 ice_restart_latch_->Reset();
1359}
1360
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001361void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001362 SetIdentity(identity);
1363}
1364
1365bool WebRtcSession::waiting_for_identity() const {
1366 return webrtc_session_desc_factory_->waiting_for_identity();
1367}
1368
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369void WebRtcSession::SetIceConnectionState(
1370 PeerConnectionInterface::IceConnectionState state) {
1371 if (ice_connection_state_ == state) {
1372 return;
1373 }
1374
1375 // ASSERT that the requested transition is allowed. Note that
1376 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1377 // within PeerConnection). This switch statement should compile away when
1378 // ASSERTs are disabled.
1379 switch (ice_connection_state_) {
1380 case PeerConnectionInterface::kIceConnectionNew:
1381 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1382 break;
1383 case PeerConnectionInterface::kIceConnectionChecking:
1384 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1385 state == PeerConnectionInterface::kIceConnectionConnected);
1386 break;
1387 case PeerConnectionInterface::kIceConnectionConnected:
1388 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1389 state == PeerConnectionInterface::kIceConnectionChecking ||
1390 state == PeerConnectionInterface::kIceConnectionCompleted);
1391 break;
1392 case PeerConnectionInterface::kIceConnectionCompleted:
1393 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1394 state == PeerConnectionInterface::kIceConnectionDisconnected);
1395 break;
1396 case PeerConnectionInterface::kIceConnectionFailed:
1397 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1398 break;
1399 case PeerConnectionInterface::kIceConnectionDisconnected:
1400 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1401 state == PeerConnectionInterface::kIceConnectionConnected ||
1402 state == PeerConnectionInterface::kIceConnectionCompleted ||
1403 state == PeerConnectionInterface::kIceConnectionFailed);
1404 break;
1405 case PeerConnectionInterface::kIceConnectionClosed:
1406 ASSERT(false);
1407 break;
1408 default:
1409 ASSERT(false);
1410 break;
1411 }
1412
1413 ice_connection_state_ = state;
1414 if (ice_observer_) {
1415 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1416 }
1417}
1418
1419void WebRtcSession::OnTransportRequestSignaling(
1420 cricket::Transport* transport) {
1421 ASSERT(signaling_thread()->IsCurrent());
1422 transport->OnSignalingReady();
1423 if (ice_observer_) {
1424 ice_observer_->OnIceGatheringChange(
1425 PeerConnectionInterface::kIceGatheringGathering);
1426 }
1427}
1428
1429void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1430 ASSERT(signaling_thread()->IsCurrent());
1431 // start monitoring for the write state of the transport.
1432 OnTransportWritable(transport);
1433}
1434
1435void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1436 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001438 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439 } else if (transport->HasChannels()) {
1440 // If the current state is Connected or Completed, then there were writable
1441 // channels but now there are not, so the next state must be Disconnected.
1442 if (ice_connection_state_ ==
1443 PeerConnectionInterface::kIceConnectionConnected ||
1444 ice_connection_state_ ==
1445 PeerConnectionInterface::kIceConnectionCompleted) {
1446 SetIceConnectionState(
1447 PeerConnectionInterface::kIceConnectionDisconnected);
1448 }
1449 }
1450}
1451
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001452void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1453 ASSERT(signaling_thread()->IsCurrent());
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001454 PeerConnectionInterface::IceConnectionState old_state = ice_connection_state_;
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001455 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001456 // Only report once when Ice connection is completed.
1457 if (old_state != PeerConnectionInterface::kIceConnectionCompleted) {
jbauchac8869e2015-07-03 01:36:14 -07001458 cricket::TransportStats stats;
1459 if (metrics_observer_ && transport->GetStats(&stats)) {
1460 ReportBestConnectionState(stats);
1461 ReportNegotiatedCiphers(stats);
1462 }
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001463 }
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001464}
1465
1466void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1467 ASSERT(signaling_thread()->IsCurrent());
1468 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1469}
1470
Peter Thatcher54360512015-07-08 11:08:35 -07001471void WebRtcSession::OnTransportReceiving(cricket::Transport* transport) {
1472 ASSERT(signaling_thread()->IsCurrent());
1473 // The ice connection is considered receiving if at least one transport is
1474 // receiving on any channels.
1475 bool receiving = false;
1476 for (const auto& kv : transport_proxies()) {
1477 cricket::Transport* transport = kv.second->impl();
1478 if (transport && transport->any_channel_receiving()) {
1479 receiving = true;
1480 break;
1481 }
1482 }
1483 SetIceConnectionReceiving(receiving);
1484}
1485
1486void WebRtcSession::SetIceConnectionReceiving(bool receiving) {
1487 if (ice_connection_receiving_ == receiving) {
1488 return;
1489 }
1490 ice_connection_receiving_ = receiving;
1491 if (ice_observer_) {
1492 ice_observer_->OnIceConnectionReceivingChange(receiving);
1493 }
1494}
1495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001496void WebRtcSession::OnTransportProxyCandidatesReady(
1497 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1498 ASSERT(signaling_thread()->IsCurrent());
1499 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1500}
1501
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001502void WebRtcSession::OnCandidatesAllocationDone() {
1503 ASSERT(signaling_thread()->IsCurrent());
1504 if (ice_observer_) {
1505 ice_observer_->OnIceGatheringChange(
1506 PeerConnectionInterface::kIceGatheringComplete);
1507 ice_observer_->OnIceComplete();
1508 }
1509}
1510
1511// Enabling voice and video channel.
1512void WebRtcSession::EnableChannels() {
1513 if (voice_channel_ && !voice_channel_->enabled())
1514 voice_channel_->Enable(true);
1515
1516 if (video_channel_ && !video_channel_->enabled())
1517 video_channel_->Enable(true);
1518
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001519 if (data_channel_ && !data_channel_->enabled())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001520 data_channel_->Enable(true);
1521}
1522
1523void WebRtcSession::ProcessNewLocalCandidate(
1524 const std::string& content_name,
1525 const cricket::Candidates& candidates) {
1526 int sdp_mline_index;
1527 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1528 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1529 << content_name << " not found";
1530 return;
1531 }
1532
1533 for (cricket::Candidates::const_iterator citer = candidates.begin();
1534 citer != candidates.end(); ++citer) {
1535 // Use content_name as the candidate media id.
1536 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1537 if (ice_observer_) {
1538 ice_observer_->OnIceCandidate(&candidate);
1539 }
1540 if (local_desc_) {
1541 local_desc_->AddCandidate(&candidate);
1542 }
1543 }
1544}
1545
1546// Returns the media index for a local ice candidate given the content name.
1547bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1548 int* sdp_mline_index) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001549 if (!base_local_description() || !sdp_mline_index)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001550 return false;
1551
1552 bool content_found = false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001553 const ContentInfos& contents = base_local_description()->contents();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554 for (size_t index = 0; index < contents.size(); ++index) {
1555 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001556 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001557 content_found = true;
1558 break;
1559 }
1560 }
1561 return content_found;
1562}
1563
1564bool WebRtcSession::UseCandidatesInSessionDescription(
1565 const SessionDescriptionInterface* remote_desc) {
1566 if (!remote_desc)
1567 return true;
1568 bool ret = true;
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001569
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1571 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1572 for (size_t n = 0; n < candidates->count(); ++n) {
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001573 const IceCandidateInterface* candidate = candidates->at(n);
1574 bool valid = false;
1575 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1576 if (valid) {
1577 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
1578 saved_candidates_.push_back(
1579 new JsepIceCandidate(candidate->sdp_mid(),
1580 candidate->sdp_mline_index(),
1581 candidate->candidate()));
1582 }
1583 continue;
1584 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001585 ret = UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 if (!ret)
1587 break;
1588 }
1589 }
1590 return ret;
1591}
1592
1593bool WebRtcSession::UseCandidate(
1594 const IceCandidateInterface* candidate) {
1595
1596 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001597 size_t remote_content_size = base_remote_description()->contents().size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001598 if (mediacontent_index >= remote_content_size) {
1599 LOG(LS_ERROR)
1600 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1601 return false;
1602 }
1603
1604 cricket::ContentInfo content =
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001605 base_remote_description()->contents()[mediacontent_index];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001606 std::vector<cricket::Candidate> candidates;
1607 candidates.push_back(candidate->candidate());
1608 // Invoking BaseSession method to handle remote candidates.
1609 std::string error;
1610 if (OnRemoteCandidates(content.name, candidates, &error)) {
1611 // Candidates successfully submitted for checking.
1612 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1613 ice_connection_state_ ==
1614 PeerConnectionInterface::kIceConnectionDisconnected) {
1615 // If state is New, then the session has just gotten its first remote ICE
1616 // candidates, so go to Checking.
1617 // If state is Disconnected, the session is re-using old candidates or
1618 // receiving additional ones, so go to Checking.
1619 // If state is Connected, stay Connected.
1620 // TODO(bemasc): If state is Connected, and the new candidates are for a
1621 // newly added transport, then the state actually _should_ move to
1622 // checking. Add a way to distinguish that case.
1623 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1624 }
1625 // TODO(bemasc): If state is Completed, go back to Connected.
1626 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001627 if (!error.empty()) {
1628 LOG(LS_WARNING) << error;
1629 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630 }
1631 return true;
1632}
1633
1634void WebRtcSession::RemoveUnusedChannelsAndTransports(
1635 const SessionDescription* desc) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001636 // Destroy video_channel_ first since it may have a pointer to the
1637 // voice_channel_.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001638 const cricket::ContentInfo* video_info =
1639 cricket::GetFirstVideoContent(desc);
1640 if ((!video_info || video_info->rejected) && video_channel_) {
1641 mediastream_signaling_->OnVideoChannelClose();
1642 SignalVideoChannelDestroyed();
1643 const std::string content_name = video_channel_->content_name();
1644 channel_manager_->DestroyVideoChannel(video_channel_.release());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001645 DestroyTransportProxy(content_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001646 }
1647
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001648 const cricket::ContentInfo* voice_info =
1649 cricket::GetFirstAudioContent(desc);
1650 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1651 mediastream_signaling_->OnAudioChannelClose();
1652 SignalVoiceChannelDestroyed();
1653 const std::string content_name = voice_channel_->content_name();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001654 channel_manager_->DestroyVoiceChannel(voice_channel_.release(),
1655 video_channel_.get());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001656 DestroyTransportProxy(content_name);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001657 }
1658
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001659 const cricket::ContentInfo* data_info =
1660 cricket::GetFirstDataContent(desc);
1661 if ((!data_info || data_info->rejected) && data_channel_) {
1662 mediastream_signaling_->OnDataChannelClose();
1663 SignalDataChannelDestroyed();
1664 const std::string content_name = data_channel_->content_name();
1665 channel_manager_->DestroyDataChannel(data_channel_.release());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001666 DestroyTransportProxy(content_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001667 }
1668}
1669
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001670// TODO(mallinath) - Add a correct error code if the channels are not creatued
1671// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001673 // Creating the media channels and transport proxies.
1674 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1675 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001676 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001677 LOG(LS_ERROR) << "Failed to create voice channel.";
1678 return false;
1679 }
1680 }
1681
1682 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1683 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001684 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685 LOG(LS_ERROR) << "Failed to create video channel.";
1686 return false;
1687 }
1688 }
1689
1690 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1691 if (data_channel_type_ != cricket::DCT_NONE &&
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001692 data && !data->rejected && !data_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001693 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694 LOG(LS_ERROR) << "Failed to create data channel.";
1695 return false;
1696 }
1697 }
1698
Peter Thatcheraf55ccc2015-05-21 07:48:41 -07001699 if (rtcp_mux_policy_ == PeerConnectionInterface::kRtcpMuxPolicyRequire) {
1700 if (voice_channel()) {
1701 voice_channel()->ActivateRtcpMux();
1702 }
1703 if (video_channel()) {
1704 video_channel()->ActivateRtcpMux();
1705 }
1706 if (data_channel()) {
1707 data_channel()->ActivateRtcpMux();
1708 }
1709 }
1710
Donald Curtis0e209b02015-03-24 09:29:54 -07001711 // Enable bundle before when kMaxBundle policy is in effect.
1712 if (bundle_policy_ == PeerConnectionInterface::kBundlePolicyMaxBundle) {
Peter Thatcher4eddf182015-04-30 10:55:59 -07001713 const cricket::ContentGroup* bundle_group = desc->GetGroupByName(
1714 cricket::GROUP_TYPE_BUNDLE);
1715 if (!bundle_group) {
Donald Curtis0e209b02015-03-24 09:29:54 -07001716 LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
1717 return false;
1718 }
Peter Thatcher4eddf182015-04-30 10:55:59 -07001719 if (!BaseSession::BundleContentGroup(bundle_group)) {
Donald Curtis0e209b02015-03-24 09:29:54 -07001720 LOG(LS_WARNING) << "max-bundle failed to enable bundling.";
1721 return false;
1722 }
1723 }
1724
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001725 return true;
1726}
1727
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001728bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
Jelena Marusicc28a8962015-05-29 15:05:44 +02001730 this, content->name, true, audio_options_));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001731 if (!voice_channel_) {
wu@webrtc.orgde305012013-10-31 15:40:38 +00001732 return false;
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001733 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001734
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001735 voice_channel_->SignalDtlsSetupFailure.connect(
1736 this, &WebRtcSession::OnDtlsSetupFailure);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001737 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001738}
1739
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001740bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741 video_channel_.reset(channel_manager_->CreateVideoChannel(
buildbot@webrtc.org1ecbe452014-10-14 20:29:28 +00001742 this, content->name, true, video_options_, voice_channel_.get()));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001743 if (!video_channel_) {
1744 return false;
1745 }
1746
1747 video_channel_->SignalDtlsSetupFailure.connect(
1748 this, &WebRtcSession::OnDtlsSetupFailure);
1749 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001750}
1751
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001752bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001753 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001755 this, content->name, !sctp, data_channel_type_));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001756 if (!data_channel_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001757 return false;
1758 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001759
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001760 if (sctp) {
1761 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001762 data_channel_->SignalDataReceived.connect(
1763 this, &WebRtcSession::OnDataChannelMessageReceived);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +00001764 data_channel_->SignalStreamClosedRemotely.connect(
1765 mediastream_signaling_,
1766 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001767 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001768
1769 data_channel_->SignalDtlsSetupFailure.connect(
1770 this, &WebRtcSession::OnDtlsSetupFailure);
wu@webrtc.org91053e72013-08-10 07:18:04 +00001771 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001772}
1773
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001774void WebRtcSession::OnDtlsSetupFailure(cricket::BaseChannel*, bool rtcp) {
1775 SetError(BaseSession::ERROR_TRANSPORT, rtcp ? kDtlsSetupFailureRtcp :
1776 kDtlsSetupFailureRtp);
1777}
1778
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779void WebRtcSession::CopySavedCandidates(
1780 SessionDescriptionInterface* dest_desc) {
1781 if (!dest_desc) {
1782 ASSERT(false);
1783 return;
1784 }
1785 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1786 dest_desc->AddCandidate(saved_candidates_[i]);
1787 delete saved_candidates_[i];
1788 }
1789 saved_candidates_.clear();
1790}
1791
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001792void WebRtcSession::OnDataChannelMessageReceived(
1793 cricket::DataChannel* channel,
1794 const cricket::ReceiveDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001795 const rtc::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001796 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001797 if (params.type == cricket::DMT_CONTROL &&
1798 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1799 // Received CONTROL on unused sid, process as an OPEN message.
1800 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001802 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803}
1804
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001805// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001806bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001807 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1808 if (!bundle_enabled)
1809 return true;
1810
1811 const cricket::ContentGroup* bundle_group =
1812 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1813 ASSERT(bundle_group != NULL);
1814
1815 const cricket::ContentInfos& contents = desc->contents();
1816 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1817 citer != contents.end(); ++citer) {
1818 const cricket::ContentInfo* content = (&*citer);
1819 ASSERT(content != NULL);
1820 if (bundle_group->HasContentName(content->name) &&
1821 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1822 if (!HasRtcpMuxEnabled(content))
1823 return false;
1824 }
1825 }
1826 // RTCP-MUX is enabled in all the contents.
1827 return true;
1828}
1829
1830bool WebRtcSession::HasRtcpMuxEnabled(
1831 const cricket::ContentInfo* content) {
1832 const cricket::MediaContentDescription* description =
1833 static_cast<cricket::MediaContentDescription*>(content->description);
1834 return description->rtcp_mux();
1835}
1836
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001837bool WebRtcSession::ValidateSessionDescription(
1838 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001839 cricket::ContentSource source, std::string* err_desc) {
1840 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001841 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001842 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001843 }
1844
1845 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001846 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001847 }
1848
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001849 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001850 Action action = GetAction(sdesc->type());
1851 if (source == cricket::CS_LOCAL) {
1852 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001853 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001854 } else {
1855 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001856 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001857 }
1858
1859 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001860 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001861 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1862 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001863 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001864 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001865 }
1866
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001867 // Verify ice-ufrag and ice-pwd.
1868 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001869 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001870 }
1871
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001872 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001873 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001874 }
1875
1876 // Verify m-lines in Answer when compared against Offer.
1877 if (action == kAnswer) {
1878 const cricket::SessionDescription* offer_desc =
1879 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1880 local_description()->description();
1881 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001882 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001883 }
1884 }
1885
1886 return true;
1887}
1888
1889bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1890 return ((action == kOffer && state() == STATE_INIT) ||
1891 // update local offer
1892 (action == kOffer && state() == STATE_SENTINITIATE) ||
1893 // update the current ongoing session.
1894 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1895 (action == kOffer && state() == STATE_SENTACCEPT) ||
1896 (action == kOffer && state() == STATE_INPROGRESS) ||
1897 // accept remote offer
1898 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1899 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1900 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1901 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1902}
1903
1904bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1905 return ((action == kOffer && state() == STATE_INIT) ||
1906 // update remote offer
1907 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1908 // update the current ongoing session
1909 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1910 (action == kOffer && state() == STATE_SENTACCEPT) ||
1911 (action == kOffer && state() == STATE_INPROGRESS) ||
1912 // accept local offer
1913 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1914 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1915 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1916 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1917}
1918
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001919std::string WebRtcSession::GetSessionErrorMsg() {
1920 std::ostringstream desc;
1921 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1922 desc << kSessionErrorDesc << error_desc() << ".";
1923 return desc.str();
1924}
1925
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001926// We need to check the local/remote description for the Transport instead of
1927// the session, because a new Transport added during renegotiation may have
1928// them unset while the session has them set from the previous negotiation.
1929// Not doing so may trigger the auto generation of transport description and
1930// mess up DTLS identity information, ICE credential, etc.
1931bool WebRtcSession::ReadyToUseRemoteCandidate(
1932 const IceCandidateInterface* candidate,
1933 const SessionDescriptionInterface* remote_desc,
1934 bool* valid) {
1935 *valid = true;;
1936 cricket::TransportProxy* transport_proxy = NULL;
1937
1938 const SessionDescriptionInterface* current_remote_desc =
1939 remote_desc ? remote_desc : remote_description();
1940
1941 if (!current_remote_desc)
1942 return false;
1943
1944 size_t mediacontent_index =
1945 static_cast<size_t>(candidate->sdp_mline_index());
1946 size_t remote_content_size =
1947 current_remote_desc->description()->contents().size();
1948 if (mediacontent_index >= remote_content_size) {
1949 LOG(LS_ERROR)
1950 << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1951
1952 *valid = false;
1953 return false;
1954 }
1955
1956 cricket::ContentInfo content =
1957 current_remote_desc->description()->contents()[mediacontent_index];
1958 transport_proxy = GetTransportProxy(content.name);
1959
1960 return transport_proxy && transport_proxy->local_description_set() &&
1961 transport_proxy->remote_description_set();
1962}
1963
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001964// Walk through the ConnectionInfos to gather best connection usage
1965// for IPv4 and IPv6.
jbauchac8869e2015-07-03 01:36:14 -07001966void WebRtcSession::ReportBestConnectionState(
1967 const cricket::TransportStats& stats) {
1968 DCHECK(metrics_observer_ != NULL);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001969 for (cricket::TransportChannelStatsList::const_iterator it =
1970 stats.channel_stats.begin();
1971 it != stats.channel_stats.end(); ++it) {
1972 for (cricket::ConnectionInfos::const_iterator it_info =
1973 it->connection_infos.begin();
1974 it_info != it->connection_infos.end(); ++it_info) {
1975 if (!it_info->best_connection) {
1976 continue;
1977 }
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07001978
1979 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
1980 const cricket::Candidate& local = it_info->local_candidate;
1981 const cricket::Candidate& remote = it_info->remote_candidate;
1982
1983 // Increment the counter for IceCandidatePairType.
1984 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
1985 (local.type() == RELAY_PORT_TYPE &&
1986 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
1987 type = kEnumCounterIceCandidatePairTypeTcp;
1988 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
1989 type = kEnumCounterIceCandidatePairTypeUdp;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001990 } else {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07001991 CHECK(0);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001992 }
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07001993 metrics_observer_->IncrementEnumCounter(
1994 type, GetIceCandidatePairCounter(local, remote),
1995 kIceCandidatePairMax);
1996
1997 // Increment the counter for IP type.
1998 if (local.address().family() == AF_INET) {
1999 // TODO(guoweis): Remove this next line once IncrementEnumCounter
2000 // implemented for PeerConnectionMetrics.
2001 metrics_observer_->IncrementCounter(kBestConnections_IPv4);
2002
2003 metrics_observer_->IncrementEnumCounter(
2004 kEnumCounterAddressFamily, kBestConnections_IPv4,
2005 kPeerConnectionAddressFamilyCounter_Max);
2006
2007 } else if (local.address().family() == AF_INET6) {
2008 // TODO(guoweis): Remove this next line.
2009 metrics_observer_->IncrementCounter(kBestConnections_IPv6);
2010
2011 metrics_observer_->IncrementEnumCounter(
2012 kEnumCounterAddressFamily, kBestConnections_IPv6,
2013 kPeerConnectionAddressFamilyCounter_Max);
2014 } else {
2015 CHECK(0);
2016 }
2017
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002018 return;
2019 }
2020 }
2021}
2022
jbauchac8869e2015-07-03 01:36:14 -07002023void WebRtcSession::ReportNegotiatedCiphers(
2024 const cricket::TransportStats& stats) {
2025 DCHECK(metrics_observer_ != NULL);
2026 if (!dtls_enabled_ || stats.channel_stats.empty()) {
2027 return;
2028 }
2029
2030 const std::string& srtp_cipher = stats.channel_stats[0].srtp_cipher;
2031 const std::string& ssl_cipher = stats.channel_stats[0].ssl_cipher;
2032 if (srtp_cipher.empty() && ssl_cipher.empty()) {
2033 return;
2034 }
2035
2036 PeerConnectionMetricsName srtp_name;
2037 PeerConnectionMetricsName ssl_name;
2038 if (stats.content_name == cricket::CN_AUDIO) {
2039 srtp_name = kAudioSrtpCipher;
2040 ssl_name = kAudioSslCipher;
2041 } else if (stats.content_name == cricket::CN_VIDEO) {
2042 srtp_name = kVideoSrtpCipher;
2043 ssl_name = kVideoSslCipher;
2044 } else if (stats.content_name == cricket::CN_DATA) {
2045 srtp_name = kDataSrtpCipher;
2046 ssl_name = kDataSslCipher;
2047 } else {
2048 RTC_NOTREACHED();
2049 return;
2050 }
2051
2052 if (!srtp_cipher.empty()) {
2053 metrics_observer_->AddHistogramSample(srtp_name, srtp_cipher);
2054 }
2055 if (!ssl_cipher.empty()) {
2056 metrics_observer_->AddHistogramSample(ssl_name, ssl_cipher);
2057 }
2058}
2059
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002060} // namespace webrtc