blob: 3d192c22d10b8bc9e8dcf3ba961e4cdd55860363 [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
Henrik Boström87713d02015-08-25 09:53:21 +0200579 // Obtain a certificate from RTCConfiguration if any were provided (optional).
580 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
581 if (!rtc_configuration.certificates.empty()) {
582 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
583 // just picking the first one. The decision should be made based on the DTLS
584 // handshake. The DTLS negotiations need to know about all certificates.
585 certificate = rtc_configuration.certificates[0];
586 }
587
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000588 // TODO(perkj): Take |constraints| into consideration. Return false if not all
589 // mandatory constraints can be fulfilled. Note that |constraints|
590 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000592
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000593 if (options.disable_encryption) {
594 dtls_enabled_ = false;
595 } else {
Henrik Boström87713d02015-08-25 09:53:21 +0200596 // Enable DTLS by default if we have an identity store or a certificate.
597 dtls_enabled_ = (dtls_identity_store || certificate);
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000598 // |constraints| can override the default |dtls_enabled_| value.
599 if (FindConstraint(
600 constraints,
601 MediaConstraintsInterface::kEnableDtlsSrtp,
Henrik Boström87713d02015-08-25 09:53:21 +0200602 &value, nullptr)) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000603 dtls_enabled_ = value;
604 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000605 }
606
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000608 // It takes precendence over the disable_sctp_data_channels
609 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 if (FindConstraint(
611 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
612 &value, NULL) && value) {
613 LOG(LS_INFO) << "Allowing RTP data engine.";
614 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000615 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000616 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000617 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000618 LOG(LS_INFO) << "Allowing SCTP data engine.";
619 data_channel_type_ = cricket::DCT_SCTP;
620 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621 }
622 if (data_channel_type_ != cricket::DCT_NONE) {
623 mediastream_signaling_->SetDataChannelFactory(this);
624 }
625
wu@webrtc.orgde305012013-10-31 15:40:38 +0000626 // Find DSCP constraint.
627 if (FindConstraint(
628 constraints,
629 MediaConstraintsInterface::kEnableDscp,
630 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000631 audio_options_.dscp.Set(value);
632 video_options_.dscp.Set(value);
633 }
634
635 // Find Suspend Below Min Bitrate constraint.
636 if (FindConstraint(
637 constraints,
638 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
639 &value,
640 NULL)) {
641 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000642 }
643
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000644 SetOptionFromOptionalConstraint(constraints,
645 MediaConstraintsInterface::kScreencastMinBitrate,
646 &video_options_.screencast_min_bitrate);
647
648 // Find constraints for cpu overuse detection.
649 SetOptionFromOptionalConstraint(constraints,
650 MediaConstraintsInterface::kCpuUnderuseThreshold,
651 &video_options_.cpu_underuse_threshold);
652 SetOptionFromOptionalConstraint(constraints,
653 MediaConstraintsInterface::kCpuOveruseThreshold,
654 &video_options_.cpu_overuse_threshold);
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000655 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000656 MediaConstraintsInterface::kCpuOveruseDetection,
657 &video_options_.cpu_overuse_detection);
658 SetOptionFromOptionalConstraint(constraints,
659 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
660 &video_options_.cpu_overuse_encode_usage);
661 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000662 MediaConstraintsInterface::kCpuUnderuseEncodeRsdThreshold,
663 &video_options_.cpu_underuse_encode_rsd_threshold);
664 SetOptionFromOptionalConstraint(constraints,
665 MediaConstraintsInterface::kCpuOveruseEncodeRsdThreshold,
666 &video_options_.cpu_overuse_encode_rsd_threshold);
buildbot@webrtc.orgdb563902014-06-13 13:05:48 +0000667
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000668 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +0000669 MediaConstraintsInterface::kNumUnsignalledRecvStreams,
670 &video_options_.unsignalled_recv_stream_limit);
671 if (video_options_.unsignalled_recv_stream_limit.IsSet()) {
672 int stream_limit;
673 video_options_.unsignalled_recv_stream_limit.Get(&stream_limit);
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000674 stream_limit = std::min(kMaxUnsignalledRecvStreams, stream_limit);
675 stream_limit = std::max(0, stream_limit);
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +0000676 video_options_.unsignalled_recv_stream_limit.Set(stream_limit);
677 }
678
679 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000680 MediaConstraintsInterface::kHighStartBitrate,
681 &video_options_.video_start_bitrate);
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000682
683 if (FindConstraint(
684 constraints,
685 MediaConstraintsInterface::kVeryHighBitrate,
686 &value,
687 NULL)) {
688 video_options_.video_highest_bitrate.Set(
689 cricket::VideoOptions::VERY_HIGH);
690 } else if (FindConstraint(
691 constraints,
692 MediaConstraintsInterface::kHighBitrate,
693 &value,
694 NULL)) {
695 video_options_.video_highest_bitrate.Set(
696 cricket::VideoOptions::HIGH);
697 }
698
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000699 SetOptionFromOptionalConstraint(constraints,
700 MediaConstraintsInterface::kCombinedAudioVideoBwe,
701 &audio_options_.combined_audio_video_bwe);
702
Henrik Lundin64dad832015-05-11 12:44:23 +0200703 audio_options_.audio_jitter_buffer_max_packets.Set(
704 rtc_configuration.audio_jitter_buffer_max_packets);
705
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200706 audio_options_.audio_jitter_buffer_fast_accelerate.Set(
707 rtc_configuration.audio_jitter_buffer_fast_accelerate);
708
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000709 const cricket::VideoCodec default_codec(
710 JsepSessionDescription::kDefaultVideoCodecId,
711 JsepSessionDescription::kDefaultVideoCodecName,
712 JsepSessionDescription::kMaxVideoCodecWidth,
713 JsepSessionDescription::kMaxVideoCodecHeight,
714 JsepSessionDescription::kDefaultVideoCodecFramerate,
715 JsepSessionDescription::kDefaultVideoCodecPreference);
716 channel_manager_->SetDefaultVideoEncoderConfig(
717 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000718
Henrik Boström87713d02015-08-25 09:53:21 +0200719 if (!dtls_enabled_) {
720 // Construct with DTLS disabled.
721 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
722 signaling_thread(),
723 channel_manager_,
724 mediastream_signaling_,
725 this,
726 id(),
727 data_channel_type_));
728 } else {
729 // Construct with DTLS enabled.
730 if (!certificate) {
731 // Use the |dtls_identity_store| to generate a certificate.
732 DCHECK(dtls_identity_store);
733 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
734 signaling_thread(),
735 channel_manager_,
736 mediastream_signaling_,
737 dtls_identity_store.Pass(),
738 this,
739 id(),
740 data_channel_type_));
741 } else {
742 // Use the already generated certificate.
743 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
744 signaling_thread(),
745 channel_manager_,
746 mediastream_signaling_,
747 certificate,
748 this,
749 id(),
750 data_channel_type_));
751 }
752 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000753
754 webrtc_session_desc_factory_->SignalIdentityReady.connect(
755 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000756
wu@webrtc.org97077a32013-10-25 21:18:33 +0000757 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000758 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000759 }
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +0000760 port_allocator()->set_candidate_filter(
Henrik Lundin64dad832015-05-11 12:44:23 +0200761 ConvertIceTransportTypeToCandidateFilter(rtc_configuration.type));
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700762
763 if (rtc_configuration.enable_localhost_ice_candidate) {
764 port_allocator()->set_flags(
765 port_allocator()->flags() |
766 cricket::PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE);
767 }
768
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769 return true;
770}
771
772void WebRtcSession::Terminate() {
773 SetState(STATE_RECEIVEDTERMINATE);
774 RemoveUnusedChannelsAndTransports(NULL);
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +0000775 ASSERT(!voice_channel_);
776 ASSERT(!video_channel_);
777 ASSERT(!data_channel_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778}
779
780bool WebRtcSession::StartCandidatesAllocation() {
781 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
782 // from TransportProxy to start gathering ice candidates.
783 SpeculativelyConnectAllTransportChannels();
784 if (!saved_candidates_.empty()) {
785 // If there are saved candidates which arrived before local description is
786 // set, copy those to remote description.
787 CopySavedCandidates(remote_desc_.get());
788 }
789 // Push remote candidates present in remote description to transport channels.
790 UseCandidatesInSessionDescription(remote_desc_.get());
791 return true;
792}
793
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000794void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
795 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796}
797
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000798cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
799 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800}
801
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000802bool WebRtcSession::GetSslRole(rtc::SSLRole* role) {
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000803 if (local_description() == NULL || remote_description() == NULL) {
804 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
805 << "SSL Role of the session.";
806 return false;
807 }
808
809 // TODO(mallinath) - Return role of each transport, as role may differ from
810 // one another.
811 // In current implementaion we just return the role of first transport in the
812 // transport map.
813 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
814 iter != transport_proxies().end(); ++iter) {
815 if (iter->second->impl()) {
816 return iter->second->impl()->GetSslRole(role);
817 }
818 }
819 return false;
820}
821
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000822void WebRtcSession::CreateOffer(
823 CreateSessionDescriptionObserver* observer,
824 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
825 webrtc_session_desc_factory_->CreateOffer(observer, options);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000826}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827
wu@webrtc.org91053e72013-08-10 07:18:04 +0000828void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
829 const MediaConstraintsInterface* constraints) {
830 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831}
832
833bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
834 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000835 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000836 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000837
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000838 // Validate SDP.
839 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
840 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841 }
842
843 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000844 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000845 if (state() == STATE_INIT && action == kOffer) {
846 set_initiator(true);
847 }
848
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000849 cricket::SecurePolicy sdes_policy =
850 webrtc_session_desc_factory_->SdesPolicy();
851 cricket::CryptoType crypto_required = dtls_enabled_ ?
852 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
853 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000854 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000855 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000856
857 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000858 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000859
860 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000861 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862 // TODO(mallinath) - Handle CreateChannel failure, as new local description
863 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000864 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000865 }
866
867 // Remove channel and transport proxies, if MediaContentDescription is
868 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000869 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000871 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 return false;
873 }
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +0000874
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875 // Kick starting the ice candidates allocation.
876 StartCandidatesAllocation();
877
878 // Update state and SSRC of local MediaStreams and DataChannels based on the
879 // local session description.
880 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
881
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000882 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000883 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
884 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
885 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000887 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 }
889 return true;
890}
891
892bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
893 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000894 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000895 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000896
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000897 // Validate SDP.
898 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
899 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900 }
901
902 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000903 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904 if (action == kOffer && !CreateChannels(desc->description())) {
905 // TODO(mallinath) - Handle CreateChannel failure, as new local description
906 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000907 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908 }
909
910 // Remove channel and transport proxies, if MediaContentDescription is
911 // rejected.
912 RemoveUnusedChannelsAndTransports(desc->description());
913
914 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
915 // is called.
916 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000917 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 return false;
919 }
920
921 // Update remote MediaStreams.
922 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
923 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000924 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 }
926
927 // Copy all saved candidates.
928 CopySavedCandidates(desc);
honghaiz503726c2015-07-31 12:37:38 -0700929
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 // Check if this new SessionDescription contains new ice ufrag and password
931 // that indicates the remote peer requests ice restart.
honghaiz503726c2015-07-31 12:37:38 -0700932 bool ice_restart =
933 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(), desc);
934 // We retain all received candidates only if ICE is not restarted.
935 // When ICE is restarted, all previous candidates belong to an old generation
936 // and should not be kept.
937 if (!ice_restart) {
938 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
939 remote_desc_.get(), desc);
940 }
941
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000942 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000943
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000944 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000945 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
946 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
947 }
948
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000950 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000952
953 // Set the the ICE connection state to connecting since the connection may
954 // become writable with peer reflexive candidates before any remote candidate
955 // is signaled.
956 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
957 // is to have a new signal the indicates a change in checking state from the
958 // transport and expose a new checking() member from transport that can be
959 // read to determine the current checking state. The existing SignalConnecting
960 // actually means "gathering candidates", so cannot be be used here.
961 if (desc->type() != SessionDescriptionInterface::kOffer &&
962 ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew) {
963 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
964 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965 return true;
966}
967
968bool WebRtcSession::UpdateSessionState(
969 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 std::string* err_desc) {
971 // If there's already a pending error then no state transition should happen.
972 // But all call-sites should be verifying this before calling us!
973 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000974 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000975 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000976 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
977 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978 }
979 SetState(source == cricket::CS_LOCAL ?
980 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000981 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
982 SetError(BaseSession::ERROR_CONTENT, *err_desc);
983 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000985 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986 }
987 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000988 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
989 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990 }
991 EnableChannels();
992 SetState(source == cricket::CS_LOCAL ?
993 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +0000994 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
995 SetError(BaseSession::ERROR_CONTENT, *err_desc);
996 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000998 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 }
1000 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001001 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
1002 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001003 }
1004 MaybeEnableMuxingSupport();
1005 EnableChannels();
1006 SetState(source == cricket::CS_LOCAL ?
1007 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001008 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
1009 SetError(BaseSession::ERROR_CONTENT, *err_desc);
1010 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001012 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 }
1014 }
1015 return true;
1016}
1017
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001018bool WebRtcSession::PushdownMediaDescription(
1019 cricket::ContentAction action,
1020 cricket::ContentSource source,
1021 std::string* err) {
1022 auto set_content = [this, action, source, err](cricket::BaseChannel* ch) {
1023 if (!ch) {
1024 return true;
1025 } else if (source == cricket::CS_LOCAL) {
1026 return ch->PushdownLocalDescription(
1027 base_local_description(), action, err);
1028 } else {
1029 return ch->PushdownRemoteDescription(
1030 base_remote_description(), action, err);
1031 }
1032 };
1033
1034 return (set_content(voice_channel()) &&
1035 set_content(video_channel()) &&
1036 set_content(data_channel()));
1037}
1038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
1040 if (type == SessionDescriptionInterface::kOffer) {
1041 return WebRtcSession::kOffer;
1042 } else if (type == SessionDescriptionInterface::kPrAnswer) {
1043 return WebRtcSession::kPrAnswer;
1044 } else if (type == SessionDescriptionInterface::kAnswer) {
1045 return WebRtcSession::kAnswer;
1046 }
1047 ASSERT(false && "unknown action type");
1048 return WebRtcSession::kOffer;
1049}
1050
pthatcher@webrtc.orgc04a97f2015-03-16 19:31:40 +00001051bool WebRtcSession::GetTransportStats(cricket::SessionStats* stats) {
1052 ASSERT(signaling_thread()->IsCurrent());
1053
1054 const auto get_transport_stats = [stats](const std::string& content_name,
1055 cricket::Transport* transport) {
1056 const std::string& transport_id = transport->content_name();
1057 stats->proxy_to_transport[content_name] = transport_id;
1058 if (stats->transport_stats.find(transport_id)
1059 != stats->transport_stats.end()) {
1060 // Transport stats already done for this transport.
1061 return true;
1062 }
1063
1064 cricket::TransportStats tstats;
1065 if (!transport->GetStats(&tstats)) {
1066 return false;
1067 }
1068
1069 stats->transport_stats[transport_id] = tstats;
1070 return true;
1071 };
1072
1073 for (const auto& kv : transport_proxies()) {
1074 cricket::Transport* transport = kv.second->impl();
1075 if (transport && !get_transport_stats(kv.first, transport)) {
1076 return false;
1077 }
1078 }
1079 return true;
1080}
1081
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
1083 if (state() == STATE_INIT) {
1084 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1085 << "without any offer (local or remote) "
1086 << "session description.";
1087 return false;
1088 }
1089
1090 if (!candidate) {
1091 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
1092 return false;
1093 }
1094
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001095 bool valid = false;
1096 if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
1097 if (valid) {
1098 LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
1099 saved_candidates_.push_back(
1100 new JsepIceCandidate(candidate->sdp_mid(),
1101 candidate->sdp_mline_index(),
1102 candidate->candidate()));
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +00001103 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001104 return valid;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105 }
1106
1107 // Add this candidate to the remote session description.
1108 if (!remote_desc_->AddCandidate(candidate)) {
1109 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
1110 return false;
1111 }
1112
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001113 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001114}
1115
mallinath@webrtc.org3d81b1b2014-09-09 14:38:10 +00001116bool WebRtcSession::SetIceTransports(
1117 PeerConnectionInterface::IceTransportsType type) {
1118 return port_allocator()->set_candidate_filter(
1119 ConvertIceTransportTypeToCandidateFilter(type));
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001120}
1121
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001122bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001123 if (!base_local_description())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001124 return false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001125 return webrtc::GetTrackIdBySsrc(base_local_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126}
1127
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001128bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001129 if (!base_remote_description())
xians@webrtc.org4cb01282014-06-12 14:57:05 +00001130 return false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001131 return webrtc::GetTrackIdBySsrc(base_remote_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132}
1133
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001134std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001135 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001136 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001137 return desc.str();
1138}
1139
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001140void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
1141 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142 ASSERT(signaling_thread()->IsCurrent());
1143 if (!voice_channel_) {
1144 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
1145 return;
1146 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001147 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
1148 // SetRenderer() can fail if the ssrc does not match any playout channel.
1149 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
1150 return;
1151 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
1153 // Allow that SetOutputScaling fail if |enable| is false but assert
1154 // otherwise. This in the normal case when the underlying media channel has
1155 // already been deleted.
1156 ASSERT(enable == false);
1157 }
1158}
1159
1160void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001161 const cricket::AudioOptions& options,
1162 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 ASSERT(signaling_thread()->IsCurrent());
1164 if (!voice_channel_) {
1165 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
1166 return;
1167 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001168 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
1169 // SetRenderer() can fail if the ssrc does not match any send channel.
1170 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
1171 return;
1172 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 if (!voice_channel_->MuteStream(ssrc, !enable)) {
1174 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1175 // This in the normal case when the underlying media channel has already
1176 // been deleted.
1177 ASSERT(enable == false);
1178 return;
1179 }
1180 if (enable)
1181 voice_channel_->SetChannelOptions(options);
1182}
1183
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001184void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
1185 ASSERT(signaling_thread()->IsCurrent());
1186 ASSERT(volume >= 0 && volume <= 10);
1187 if (!voice_channel_) {
1188 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
1189 return;
1190 }
1191
1192 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
1193 ASSERT(false);
1194}
1195
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001196bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1197 cricket::VideoCapturer* camera) {
1198 ASSERT(signaling_thread()->IsCurrent());
1199
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001200 if (!video_channel_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1202 // support video.
1203 LOG(LS_WARNING) << "Video not used in this call.";
1204 return false;
1205 }
1206 if (!video_channel_->SetCapturer(ssrc, camera)) {
1207 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1208 // This in the normal case when the underlying media channel has already
1209 // been deleted.
1210 ASSERT(camera == NULL);
1211 return false;
1212 }
1213 return true;
1214}
1215
1216void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1217 bool enable,
1218 cricket::VideoRenderer* renderer) {
1219 ASSERT(signaling_thread()->IsCurrent());
1220 if (!video_channel_) {
1221 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1222 return;
1223 }
1224 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1225 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1226 // This in the normal case when the underlying media channel has already
1227 // been deleted.
1228 ASSERT(renderer == NULL);
1229 }
1230}
1231
1232void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1233 const cricket::VideoOptions* options) {
1234 ASSERT(signaling_thread()->IsCurrent());
1235 if (!video_channel_) {
1236 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1237 return;
1238 }
1239 if (!video_channel_->MuteStream(ssrc, !enable)) {
1240 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1241 // This in the normal case when the underlying media channel has already
1242 // been deleted.
1243 ASSERT(enable == false);
1244 return;
1245 }
1246 if (enable && options)
1247 video_channel_->SetChannelOptions(*options);
1248}
1249
1250bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1251 ASSERT(signaling_thread()->IsCurrent());
1252 if (!voice_channel_) {
1253 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1254 return false;
1255 }
1256 uint32 send_ssrc = 0;
1257 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1258 // exists.
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001259 if (!GetAudioSsrcByTrackId(base_local_description(), track_id,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260 &send_ssrc)) {
1261 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1262 return false;
1263 }
1264 return voice_channel_->CanInsertDtmf();
1265}
1266
1267bool WebRtcSession::InsertDtmf(const std::string& track_id,
1268 int code, int duration) {
1269 ASSERT(signaling_thread()->IsCurrent());
1270 if (!voice_channel_) {
1271 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1272 return false;
1273 }
1274 uint32 send_ssrc = 0;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001275 if (!VERIFY(GetAudioSsrcByTrackId(base_local_description(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 track_id, &send_ssrc))) {
1277 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1278 return false;
1279 }
1280 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1281 cricket::DF_SEND)) {
1282 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1283 return false;
1284 }
1285 return true;
1286}
1287
1288sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1289 return &SignalVoiceChannelDestroyed;
1290}
1291
wu@webrtc.org78187522013-10-07 23:32:02 +00001292bool WebRtcSession::SendData(const cricket::SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001293 const rtc::Buffer& payload,
wu@webrtc.org78187522013-10-07 23:32:02 +00001294 cricket::SendDataResult* result) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001295 if (!data_channel_) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001296 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1297 return false;
1298 }
1299 return data_channel_->SendData(params, payload, result);
1300}
1301
1302bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001303 if (!data_channel_) {
wu@webrtc.org78187522013-10-07 23:32:02 +00001304 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1305 return false;
1306 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001307 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1308 &DataChannel::OnChannelReady);
1309 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1310 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001311 return true;
1312}
1313
1314void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001315 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001316 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1317 return;
1318 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001319 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1320 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1321}
1322
bemasc@webrtc.org9b5467e2014-12-04 23:16:52 +00001323void WebRtcSession::AddSctpDataStream(int sid) {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001324 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001325 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1326 return;
1327 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001328 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1329 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001330}
1331
bemasc@webrtc.org9b5467e2014-12-04 23:16:52 +00001332void WebRtcSession::RemoveSctpDataStream(int sid) {
1333 mediastream_signaling_->RemoveSctpDataChannel(sid);
jiayl@webrtc.org2eaac182014-06-17 16:02:46 +00001334
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001335 if (!data_channel_) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001336 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1337 << "NULL.";
1338 return;
1339 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001340 data_channel_->RemoveRecvStream(sid);
1341 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001342}
1343
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001344bool WebRtcSession::ReadyToSendData() const {
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001345 return data_channel_ && data_channel_->ready_to_send_data();
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001346}
1347
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001348rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001349 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001350 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 if (state() == STATE_RECEIVEDTERMINATE) {
1352 return NULL;
1353 }
1354 if (data_channel_type_ == cricket::DCT_NONE) {
1355 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1356 return NULL;
1357 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001358 InternalDataChannelInit new_config =
1359 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 if (data_channel_type_ == cricket::DCT_SCTP) {
1361 if (new_config.id < 0) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001362 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001363 if (GetSslRole(&role) &&
1364 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1366 return NULL;
1367 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001368 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1370 << "because the id is already in use or out of range.";
1371 return NULL;
1372 }
1373 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001374
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001375 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001376 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001377 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001379
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380 return channel;
1381}
1382
1383cricket::DataChannelType WebRtcSession::data_channel_type() const {
1384 return data_channel_type_;
1385}
1386
wu@webrtc.org91053e72013-08-10 07:18:04 +00001387bool WebRtcSession::IceRestartPending() const {
1388 return ice_restart_latch_->Get();
1389}
1390
1391void WebRtcSession::ResetIceRestartLatch() {
1392 ice_restart_latch_->Reset();
1393}
1394
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001395void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001396 SetIdentity(identity);
1397}
1398
Henrik Boström87713d02015-08-25 09:53:21 +02001399bool WebRtcSession::waiting_for_identity_for_testing() const {
1400 return webrtc_session_desc_factory_->waiting_for_certificate_for_testing();
wu@webrtc.org91053e72013-08-10 07:18:04 +00001401}
1402
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403void WebRtcSession::SetIceConnectionState(
1404 PeerConnectionInterface::IceConnectionState state) {
1405 if (ice_connection_state_ == state) {
1406 return;
1407 }
1408
1409 // ASSERT that the requested transition is allowed. Note that
1410 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1411 // within PeerConnection). This switch statement should compile away when
1412 // ASSERTs are disabled.
1413 switch (ice_connection_state_) {
1414 case PeerConnectionInterface::kIceConnectionNew:
1415 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1416 break;
1417 case PeerConnectionInterface::kIceConnectionChecking:
1418 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1419 state == PeerConnectionInterface::kIceConnectionConnected);
1420 break;
1421 case PeerConnectionInterface::kIceConnectionConnected:
1422 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1423 state == PeerConnectionInterface::kIceConnectionChecking ||
1424 state == PeerConnectionInterface::kIceConnectionCompleted);
1425 break;
1426 case PeerConnectionInterface::kIceConnectionCompleted:
1427 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1428 state == PeerConnectionInterface::kIceConnectionDisconnected);
1429 break;
1430 case PeerConnectionInterface::kIceConnectionFailed:
1431 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1432 break;
1433 case PeerConnectionInterface::kIceConnectionDisconnected:
1434 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1435 state == PeerConnectionInterface::kIceConnectionConnected ||
1436 state == PeerConnectionInterface::kIceConnectionCompleted ||
1437 state == PeerConnectionInterface::kIceConnectionFailed);
1438 break;
1439 case PeerConnectionInterface::kIceConnectionClosed:
1440 ASSERT(false);
1441 break;
1442 default:
1443 ASSERT(false);
1444 break;
1445 }
1446
1447 ice_connection_state_ = state;
1448 if (ice_observer_) {
1449 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1450 }
1451}
1452
1453void WebRtcSession::OnTransportRequestSignaling(
1454 cricket::Transport* transport) {
1455 ASSERT(signaling_thread()->IsCurrent());
1456 transport->OnSignalingReady();
1457 if (ice_observer_) {
1458 ice_observer_->OnIceGatheringChange(
1459 PeerConnectionInterface::kIceGatheringGathering);
1460 }
1461}
1462
1463void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1464 ASSERT(signaling_thread()->IsCurrent());
1465 // start monitoring for the write state of the transport.
1466 OnTransportWritable(transport);
1467}
1468
1469void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1470 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001472 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 } else if (transport->HasChannels()) {
1474 // If the current state is Connected or Completed, then there were writable
1475 // channels but now there are not, so the next state must be Disconnected.
1476 if (ice_connection_state_ ==
1477 PeerConnectionInterface::kIceConnectionConnected ||
1478 ice_connection_state_ ==
1479 PeerConnectionInterface::kIceConnectionCompleted) {
1480 SetIceConnectionState(
1481 PeerConnectionInterface::kIceConnectionDisconnected);
1482 }
1483 }
1484}
1485
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001486void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1487 ASSERT(signaling_thread()->IsCurrent());
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001488 PeerConnectionInterface::IceConnectionState old_state = ice_connection_state_;
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001489 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001490 // Only report once when Ice connection is completed.
1491 if (old_state != PeerConnectionInterface::kIceConnectionCompleted) {
jbauchac8869e2015-07-03 01:36:14 -07001492 cricket::TransportStats stats;
1493 if (metrics_observer_ && transport->GetStats(&stats)) {
1494 ReportBestConnectionState(stats);
1495 ReportNegotiatedCiphers(stats);
1496 }
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001497 }
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001498}
1499
1500void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1501 ASSERT(signaling_thread()->IsCurrent());
1502 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1503}
1504
Peter Thatcher54360512015-07-08 11:08:35 -07001505void WebRtcSession::OnTransportReceiving(cricket::Transport* transport) {
1506 ASSERT(signaling_thread()->IsCurrent());
1507 // The ice connection is considered receiving if at least one transport is
1508 // receiving on any channels.
1509 bool receiving = false;
1510 for (const auto& kv : transport_proxies()) {
1511 cricket::Transport* transport = kv.second->impl();
1512 if (transport && transport->any_channel_receiving()) {
1513 receiving = true;
1514 break;
1515 }
1516 }
1517 SetIceConnectionReceiving(receiving);
1518}
1519
1520void WebRtcSession::SetIceConnectionReceiving(bool receiving) {
1521 if (ice_connection_receiving_ == receiving) {
1522 return;
1523 }
1524 ice_connection_receiving_ = receiving;
1525 if (ice_observer_) {
1526 ice_observer_->OnIceConnectionReceivingChange(receiving);
1527 }
1528}
1529
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001530void WebRtcSession::OnTransportProxyCandidatesReady(
1531 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1532 ASSERT(signaling_thread()->IsCurrent());
1533 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1534}
1535
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536void WebRtcSession::OnCandidatesAllocationDone() {
1537 ASSERT(signaling_thread()->IsCurrent());
1538 if (ice_observer_) {
1539 ice_observer_->OnIceGatheringChange(
1540 PeerConnectionInterface::kIceGatheringComplete);
1541 ice_observer_->OnIceComplete();
1542 }
1543}
1544
1545// Enabling voice and video channel.
1546void WebRtcSession::EnableChannels() {
1547 if (voice_channel_ && !voice_channel_->enabled())
1548 voice_channel_->Enable(true);
1549
1550 if (video_channel_ && !video_channel_->enabled())
1551 video_channel_->Enable(true);
1552
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001553 if (data_channel_ && !data_channel_->enabled())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554 data_channel_->Enable(true);
1555}
1556
1557void WebRtcSession::ProcessNewLocalCandidate(
1558 const std::string& content_name,
1559 const cricket::Candidates& candidates) {
1560 int sdp_mline_index;
1561 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1562 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1563 << content_name << " not found";
1564 return;
1565 }
1566
1567 for (cricket::Candidates::const_iterator citer = candidates.begin();
1568 citer != candidates.end(); ++citer) {
1569 // Use content_name as the candidate media id.
1570 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1571 if (ice_observer_) {
1572 ice_observer_->OnIceCandidate(&candidate);
1573 }
1574 if (local_desc_) {
1575 local_desc_->AddCandidate(&candidate);
1576 }
1577 }
1578}
1579
1580// Returns the media index for a local ice candidate given the content name.
1581bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1582 int* sdp_mline_index) {
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001583 if (!base_local_description() || !sdp_mline_index)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584 return false;
1585
1586 bool content_found = false;
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001587 const ContentInfos& contents = base_local_description()->contents();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001588 for (size_t index = 0; index < contents.size(); ++index) {
1589 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001590 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591 content_found = true;
1592 break;
1593 }
1594 }
1595 return content_found;
1596}
1597
1598bool WebRtcSession::UseCandidatesInSessionDescription(
1599 const SessionDescriptionInterface* remote_desc) {
1600 if (!remote_desc)
1601 return true;
1602 bool ret = true;
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001603
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001604 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1605 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1606 for (size_t n = 0; n < candidates->count(); ++n) {
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001607 const IceCandidateInterface* candidate = candidates->at(n);
1608 bool valid = false;
1609 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1610 if (valid) {
1611 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
1612 saved_candidates_.push_back(
1613 new JsepIceCandidate(candidate->sdp_mid(),
1614 candidate->sdp_mline_index(),
1615 candidate->candidate()));
1616 }
1617 continue;
1618 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001619 ret = UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001620 if (!ret)
1621 break;
1622 }
1623 }
1624 return ret;
1625}
1626
1627bool WebRtcSession::UseCandidate(
1628 const IceCandidateInterface* candidate) {
1629
1630 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001631 size_t remote_content_size = base_remote_description()->contents().size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001632 if (mediacontent_index >= remote_content_size) {
1633 LOG(LS_ERROR)
1634 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1635 return false;
1636 }
1637
1638 cricket::ContentInfo content =
pthatcher@webrtc.org592470b2015-03-16 21:15:37 +00001639 base_remote_description()->contents()[mediacontent_index];
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640 std::vector<cricket::Candidate> candidates;
1641 candidates.push_back(candidate->candidate());
1642 // Invoking BaseSession method to handle remote candidates.
1643 std::string error;
1644 if (OnRemoteCandidates(content.name, candidates, &error)) {
1645 // Candidates successfully submitted for checking.
1646 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1647 ice_connection_state_ ==
1648 PeerConnectionInterface::kIceConnectionDisconnected) {
1649 // If state is New, then the session has just gotten its first remote ICE
1650 // candidates, so go to Checking.
1651 // If state is Disconnected, the session is re-using old candidates or
1652 // receiving additional ones, so go to Checking.
1653 // If state is Connected, stay Connected.
1654 // TODO(bemasc): If state is Connected, and the new candidates are for a
1655 // newly added transport, then the state actually _should_ move to
1656 // checking. Add a way to distinguish that case.
1657 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1658 }
1659 // TODO(bemasc): If state is Completed, go back to Connected.
1660 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001661 if (!error.empty()) {
1662 LOG(LS_WARNING) << error;
1663 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001664 }
1665 return true;
1666}
1667
1668void WebRtcSession::RemoveUnusedChannelsAndTransports(
1669 const SessionDescription* desc) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001670 // Destroy video_channel_ first since it may have a pointer to the
1671 // voice_channel_.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672 const cricket::ContentInfo* video_info =
1673 cricket::GetFirstVideoContent(desc);
1674 if ((!video_info || video_info->rejected) && video_channel_) {
1675 mediastream_signaling_->OnVideoChannelClose();
1676 SignalVideoChannelDestroyed();
1677 const std::string content_name = video_channel_->content_name();
1678 channel_manager_->DestroyVideoChannel(video_channel_.release());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001679 DestroyTransportProxy(content_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680 }
1681
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001682 const cricket::ContentInfo* voice_info =
1683 cricket::GetFirstAudioContent(desc);
1684 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1685 mediastream_signaling_->OnAudioChannelClose();
1686 SignalVoiceChannelDestroyed();
1687 const std::string content_name = voice_channel_->content_name();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001688 channel_manager_->DestroyVoiceChannel(voice_channel_.release(),
1689 video_channel_.get());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001690 DestroyTransportProxy(content_name);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001691 }
1692
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001693 const cricket::ContentInfo* data_info =
1694 cricket::GetFirstDataContent(desc);
1695 if ((!data_info || data_info->rejected) && data_channel_) {
1696 mediastream_signaling_->OnDataChannelClose();
1697 SignalDataChannelDestroyed();
1698 const std::string content_name = data_channel_->content_name();
1699 channel_manager_->DestroyDataChannel(data_channel_.release());
bjornv@webrtc.org520a69e2015-02-04 12:45:44 +00001700 DestroyTransportProxy(content_name);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 }
1702}
1703
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001704// TODO(mallinath) - Add a correct error code if the channels are not creatued
1705// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 // Creating the media channels and transport proxies.
1708 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1709 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001710 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711 LOG(LS_ERROR) << "Failed to create voice channel.";
1712 return false;
1713 }
1714 }
1715
1716 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1717 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001718 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 LOG(LS_ERROR) << "Failed to create video channel.";
1720 return false;
1721 }
1722 }
1723
1724 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1725 if (data_channel_type_ != cricket::DCT_NONE &&
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001726 data && !data->rejected && !data_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001727 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001728 LOG(LS_ERROR) << "Failed to create data channel.";
1729 return false;
1730 }
1731 }
1732
Peter Thatcheraf55ccc2015-05-21 07:48:41 -07001733 if (rtcp_mux_policy_ == PeerConnectionInterface::kRtcpMuxPolicyRequire) {
1734 if (voice_channel()) {
1735 voice_channel()->ActivateRtcpMux();
1736 }
1737 if (video_channel()) {
1738 video_channel()->ActivateRtcpMux();
1739 }
1740 if (data_channel()) {
1741 data_channel()->ActivateRtcpMux();
1742 }
1743 }
1744
Donald Curtis0e209b02015-03-24 09:29:54 -07001745 // Enable bundle before when kMaxBundle policy is in effect.
1746 if (bundle_policy_ == PeerConnectionInterface::kBundlePolicyMaxBundle) {
Peter Thatcher4eddf182015-04-30 10:55:59 -07001747 const cricket::ContentGroup* bundle_group = desc->GetGroupByName(
1748 cricket::GROUP_TYPE_BUNDLE);
1749 if (!bundle_group) {
Donald Curtis0e209b02015-03-24 09:29:54 -07001750 LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
1751 return false;
1752 }
Peter Thatcher4eddf182015-04-30 10:55:59 -07001753 if (!BaseSession::BundleContentGroup(bundle_group)) {
Donald Curtis0e209b02015-03-24 09:29:54 -07001754 LOG(LS_WARNING) << "max-bundle failed to enable bundling.";
1755 return false;
1756 }
1757 }
1758
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759 return true;
1760}
1761
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001762bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
Jelena Marusicc28a8962015-05-29 15:05:44 +02001764 this, content->name, true, audio_options_));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001765 if (!voice_channel_) {
wu@webrtc.orgde305012013-10-31 15:40:38 +00001766 return false;
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001767 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001768
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001769 voice_channel_->SignalDtlsSetupFailure.connect(
1770 this, &WebRtcSession::OnDtlsSetupFailure);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001771 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001772}
1773
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001774bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775 video_channel_.reset(channel_manager_->CreateVideoChannel(
buildbot@webrtc.org1ecbe452014-10-14 20:29:28 +00001776 this, content->name, true, video_options_, voice_channel_.get()));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001777 if (!video_channel_) {
1778 return false;
1779 }
1780
1781 video_channel_->SignalDtlsSetupFailure.connect(
1782 this, &WebRtcSession::OnDtlsSetupFailure);
1783 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784}
1785
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001786bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001787 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001788 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001789 this, content->name, !sctp, data_channel_type_));
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001790 if (!data_channel_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001791 return false;
1792 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001793
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001794 if (sctp) {
1795 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001796 data_channel_->SignalDataReceived.connect(
1797 this, &WebRtcSession::OnDataChannelMessageReceived);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +00001798 data_channel_->SignalStreamClosedRemotely.connect(
1799 mediastream_signaling_,
1800 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001801 }
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001802
1803 data_channel_->SignalDtlsSetupFailure.connect(
1804 this, &WebRtcSession::OnDtlsSetupFailure);
wu@webrtc.org91053e72013-08-10 07:18:04 +00001805 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001806}
1807
pthatcher@webrtc.org4eeef582015-03-16 19:34:23 +00001808void WebRtcSession::OnDtlsSetupFailure(cricket::BaseChannel*, bool rtcp) {
1809 SetError(BaseSession::ERROR_TRANSPORT, rtcp ? kDtlsSetupFailureRtcp :
1810 kDtlsSetupFailureRtp);
1811}
1812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813void WebRtcSession::CopySavedCandidates(
1814 SessionDescriptionInterface* dest_desc) {
1815 if (!dest_desc) {
1816 ASSERT(false);
1817 return;
1818 }
1819 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1820 dest_desc->AddCandidate(saved_candidates_[i]);
1821 delete saved_candidates_[i];
1822 }
1823 saved_candidates_.clear();
1824}
1825
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001826void WebRtcSession::OnDataChannelMessageReceived(
1827 cricket::DataChannel* channel,
1828 const cricket::ReceiveDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001829 const rtc::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001830 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001831 if (params.type == cricket::DMT_CONTROL &&
1832 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1833 // Received CONTROL on unused sid, process as an OPEN message.
1834 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001835 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001836 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837}
1838
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001839// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001840bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001841 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1842 if (!bundle_enabled)
1843 return true;
1844
1845 const cricket::ContentGroup* bundle_group =
1846 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1847 ASSERT(bundle_group != NULL);
1848
1849 const cricket::ContentInfos& contents = desc->contents();
1850 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1851 citer != contents.end(); ++citer) {
1852 const cricket::ContentInfo* content = (&*citer);
1853 ASSERT(content != NULL);
1854 if (bundle_group->HasContentName(content->name) &&
1855 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1856 if (!HasRtcpMuxEnabled(content))
1857 return false;
1858 }
1859 }
1860 // RTCP-MUX is enabled in all the contents.
1861 return true;
1862}
1863
1864bool WebRtcSession::HasRtcpMuxEnabled(
1865 const cricket::ContentInfo* content) {
1866 const cricket::MediaContentDescription* description =
1867 static_cast<cricket::MediaContentDescription*>(content->description);
1868 return description->rtcp_mux();
1869}
1870
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001871bool WebRtcSession::ValidateSessionDescription(
1872 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001873 cricket::ContentSource source, std::string* err_desc) {
1874 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001875 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001876 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001877 }
1878
1879 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001880 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001881 }
1882
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001883 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001884 Action action = GetAction(sdesc->type());
1885 if (source == cricket::CS_LOCAL) {
1886 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001887 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001888 } else {
1889 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001890 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001891 }
1892
1893 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001894 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001895 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1896 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001897 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001898 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001899 }
1900
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001901 // Verify ice-ufrag and ice-pwd.
1902 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001903 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001904 }
1905
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001906 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001907 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001908 }
1909
1910 // Verify m-lines in Answer when compared against Offer.
1911 if (action == kAnswer) {
1912 const cricket::SessionDescription* offer_desc =
1913 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1914 local_description()->description();
1915 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001916 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001917 }
1918 }
1919
1920 return true;
1921}
1922
1923bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1924 return ((action == kOffer && state() == STATE_INIT) ||
1925 // update local offer
1926 (action == kOffer && state() == STATE_SENTINITIATE) ||
1927 // update the current ongoing session.
1928 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1929 (action == kOffer && state() == STATE_SENTACCEPT) ||
1930 (action == kOffer && state() == STATE_INPROGRESS) ||
1931 // accept remote offer
1932 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1933 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1934 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1935 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1936}
1937
1938bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1939 return ((action == kOffer && state() == STATE_INIT) ||
1940 // update remote offer
1941 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1942 // update the current ongoing session
1943 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1944 (action == kOffer && state() == STATE_SENTACCEPT) ||
1945 (action == kOffer && state() == STATE_INPROGRESS) ||
1946 // accept local offer
1947 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1948 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1949 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1950 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1951}
1952
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001953std::string WebRtcSession::GetSessionErrorMsg() {
1954 std::ostringstream desc;
1955 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1956 desc << kSessionErrorDesc << error_desc() << ".";
1957 return desc.str();
1958}
1959
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001960// We need to check the local/remote description for the Transport instead of
1961// the session, because a new Transport added during renegotiation may have
1962// them unset while the session has them set from the previous negotiation.
1963// Not doing so may trigger the auto generation of transport description and
1964// mess up DTLS identity information, ICE credential, etc.
1965bool WebRtcSession::ReadyToUseRemoteCandidate(
1966 const IceCandidateInterface* candidate,
1967 const SessionDescriptionInterface* remote_desc,
1968 bool* valid) {
1969 *valid = true;;
1970 cricket::TransportProxy* transport_proxy = NULL;
1971
1972 const SessionDescriptionInterface* current_remote_desc =
1973 remote_desc ? remote_desc : remote_description();
1974
1975 if (!current_remote_desc)
1976 return false;
1977
1978 size_t mediacontent_index =
1979 static_cast<size_t>(candidate->sdp_mline_index());
1980 size_t remote_content_size =
1981 current_remote_desc->description()->contents().size();
1982 if (mediacontent_index >= remote_content_size) {
1983 LOG(LS_ERROR)
1984 << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1985
1986 *valid = false;
1987 return false;
1988 }
1989
1990 cricket::ContentInfo content =
1991 current_remote_desc->description()->contents()[mediacontent_index];
1992 transport_proxy = GetTransportProxy(content.name);
1993
1994 return transport_proxy && transport_proxy->local_description_set() &&
1995 transport_proxy->remote_description_set();
1996}
1997
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001998// Walk through the ConnectionInfos to gather best connection usage
1999// for IPv4 and IPv6.
jbauchac8869e2015-07-03 01:36:14 -07002000void WebRtcSession::ReportBestConnectionState(
2001 const cricket::TransportStats& stats) {
2002 DCHECK(metrics_observer_ != NULL);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002003 for (cricket::TransportChannelStatsList::const_iterator it =
2004 stats.channel_stats.begin();
2005 it != stats.channel_stats.end(); ++it) {
2006 for (cricket::ConnectionInfos::const_iterator it_info =
2007 it->connection_infos.begin();
2008 it_info != it->connection_infos.end(); ++it_info) {
2009 if (!it_info->best_connection) {
2010 continue;
2011 }
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07002012
2013 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
2014 const cricket::Candidate& local = it_info->local_candidate;
2015 const cricket::Candidate& remote = it_info->remote_candidate;
2016
2017 // Increment the counter for IceCandidatePairType.
2018 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
2019 (local.type() == RELAY_PORT_TYPE &&
2020 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
2021 type = kEnumCounterIceCandidatePairTypeTcp;
2022 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
2023 type = kEnumCounterIceCandidatePairTypeUdp;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002024 } else {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07002025 CHECK(0);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002026 }
Guo-wei Shieh3d564c12015-08-19 16:51:15 -07002027 metrics_observer_->IncrementEnumCounter(
2028 type, GetIceCandidatePairCounter(local, remote),
2029 kIceCandidatePairMax);
2030
2031 // Increment the counter for IP type.
2032 if (local.address().family() == AF_INET) {
2033 // TODO(guoweis): Remove this next line once IncrementEnumCounter
2034 // implemented for PeerConnectionMetrics.
2035 metrics_observer_->IncrementCounter(kBestConnections_IPv4);
2036
2037 metrics_observer_->IncrementEnumCounter(
2038 kEnumCounterAddressFamily, kBestConnections_IPv4,
2039 kPeerConnectionAddressFamilyCounter_Max);
2040
2041 } else if (local.address().family() == AF_INET6) {
2042 // TODO(guoweis): Remove this next line.
2043 metrics_observer_->IncrementCounter(kBestConnections_IPv6);
2044
2045 metrics_observer_->IncrementEnumCounter(
2046 kEnumCounterAddressFamily, kBestConnections_IPv6,
2047 kPeerConnectionAddressFamilyCounter_Max);
2048 } else {
2049 CHECK(0);
2050 }
2051
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002052 return;
2053 }
2054 }
2055}
2056
jbauchac8869e2015-07-03 01:36:14 -07002057void WebRtcSession::ReportNegotiatedCiphers(
2058 const cricket::TransportStats& stats) {
2059 DCHECK(metrics_observer_ != NULL);
2060 if (!dtls_enabled_ || stats.channel_stats.empty()) {
2061 return;
2062 }
2063
2064 const std::string& srtp_cipher = stats.channel_stats[0].srtp_cipher;
2065 const std::string& ssl_cipher = stats.channel_stats[0].ssl_cipher;
2066 if (srtp_cipher.empty() && ssl_cipher.empty()) {
2067 return;
2068 }
2069
2070 PeerConnectionMetricsName srtp_name;
2071 PeerConnectionMetricsName ssl_name;
2072 if (stats.content_name == cricket::CN_AUDIO) {
2073 srtp_name = kAudioSrtpCipher;
2074 ssl_name = kAudioSslCipher;
2075 } else if (stats.content_name == cricket::CN_VIDEO) {
2076 srtp_name = kVideoSrtpCipher;
2077 ssl_name = kVideoSslCipher;
2078 } else if (stats.content_name == cricket::CN_DATA) {
2079 srtp_name = kDataSrtpCipher;
2080 ssl_name = kDataSslCipher;
2081 } else {
2082 RTC_NOTREACHED();
2083 return;
2084 }
2085
2086 if (!srtp_cipher.empty()) {
2087 metrics_observer_->AddHistogramSample(srtp_name, srtp_cipher);
2088 }
2089 if (!ssl_cipher.empty()) {
2090 metrics_observer_->AddHistogramSample(ssl_name, ssl_cipher);
2091 }
2092}
2093
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002094} // namespace webrtc